babylon.no-module.max.js 5.4 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208622096221062211622126221362214622156221662217622186221962220622216222262223622246222562226622276222862229622306223162232622336223462235622366223762238622396224062241622426224362244622456224662247622486224962250622516225262253622546225562256622576225862259622606226162262622636226462265622666226762268622696227062271622726227362274622756227662277622786227962280622816228262283622846228562286622876228862289622906229162292622936229462295622966229762298622996230062301623026230362304623056230662307623086230962310623116231262313623146231562316623176231862319623206232162322623236232462325623266232762328623296233062331623326233362334623356233662337623386233962340623416234262343623446234562346623476234862349623506235162352623536235462355623566235762358623596236062361623626236362364623656236662367623686236962370623716237262373623746237562376623776237862379623806238162382623836238462385623866238762388623896239062391623926239362394623956239662397623986239962400624016240262403624046240562406624076240862409624106241162412624136241462415624166241762418624196242062421624226242362424624256242662427624286242962430624316243262433624346243562436624376243862439624406244162442624436244462445624466244762448624496245062451624526245362454624556245662457624586245962460624616246262463624646246562466624676246862469624706247162472624736247462475624766247762478624796248062481624826248362484624856248662487624886248962490624916249262493624946249562496624976249862499625006250162502625036250462505625066250762508625096251062511625126251362514625156251662517625186251962520625216252262523625246252562526625276252862529625306253162532625336253462535625366253762538625396254062541625426254362544625456254662547625486254962550625516255262553625546255562556625576255862559625606256162562625636256462565625666256762568625696257062571625726257362574625756257662577625786257962580625816258262583625846258562586625876258862589625906259162592625936259462595625966259762598625996260062601626026260362604626056260662607626086260962610626116261262613626146261562616626176261862619626206262162622626236262462625626266262762628626296263062631626326263362634626356263662637626386263962640626416264262643626446264562646626476264862649626506265162652626536265462655626566265762658626596266062661626626266362664626656266662667626686266962670626716267262673626746267562676626776267862679626806268162682626836268462685626866268762688626896269062691626926269362694626956269662697626986269962700627016270262703627046270562706627076270862709627106271162712627136271462715627166271762718627196272062721627226272362724627256272662727627286272962730627316273262733627346273562736627376273862739627406274162742627436274462745627466274762748627496275062751627526275362754627556275662757627586275962760627616276262763627646276562766627676276862769627706277162772627736277462775627766277762778627796278062781627826278362784627856278662787627886278962790627916279262793627946279562796627976279862799628006280162802628036280462805628066280762808628096281062811628126281362814628156281662817628186281962820628216282262823628246282562826628276282862829628306283162832628336283462835628366283762838628396284062841628426284362844628456284662847628486284962850628516285262853628546285562856628576285862859628606286162862628636286462865628666286762868628696287062871628726287362874628756287662877628786287962880628816288262883628846288562886628876288862889628906289162892628936289462895628966289762898628996290062901629026290362904629056290662907629086290962910629116291262913629146291562916629176291862919629206292162922629236292462925629266292762928629296293062931629326293362934629356293662937629386293962940629416294262943629446294562946629476294862949629506295162952629536295462955629566295762958629596296062961629626296362964629656296662967629686296962970629716297262973629746297562976629776297862979629806298162982629836298462985629866298762988629896299062991629926299362994629956299662997629986299963000630016300263003630046300563006630076300863009630106301163012630136301463015630166301763018630196302063021630226302363024630256302663027630286302963030630316303263033630346303563036630376303863039630406304163042630436304463045630466304763048630496305063051630526305363054630556305663057630586305963060630616306263063630646306563066630676306863069630706307163072630736307463075630766307763078630796308063081630826308363084630856308663087630886308963090630916309263093630946309563096630976309863099631006310163102631036310463105631066310763108631096311063111631126311363114631156311663117631186311963120631216312263123631246312563126631276312863129631306313163132631336313463135631366313763138631396314063141631426314363144631456314663147631486314963150631516315263153631546315563156631576315863159631606316163162631636316463165631666316763168631696317063171631726317363174631756317663177631786317963180631816318263183631846318563186631876318863189631906319163192631936319463195631966319763198631996320063201632026320363204632056320663207632086320963210632116321263213632146321563216632176321863219632206322163222632236322463225632266322763228632296323063231632326323363234632356323663237632386323963240632416324263243632446324563246632476324863249632506325163252632536325463255632566325763258632596326063261632626326363264632656326663267632686326963270632716327263273632746327563276632776327863279632806328163282632836328463285632866328763288632896329063291632926329363294632956329663297632986329963300633016330263303633046330563306633076330863309633106331163312633136331463315633166331763318633196332063321633226332363324633256332663327633286332963330633316333263333633346333563336633376333863339633406334163342633436334463345633466334763348633496335063351633526335363354633556335663357633586335963360633616336263363633646336563366633676336863369633706337163372633736337463375633766337763378633796338063381633826338363384633856338663387633886338963390633916339263393633946339563396633976339863399634006340163402634036340463405634066340763408634096341063411634126341363414634156341663417634186341963420634216342263423634246342563426634276342863429634306343163432634336343463435634366343763438634396344063441634426344363444634456344663447634486344963450634516345263453634546345563456634576345863459634606346163462634636346463465634666346763468634696347063471634726347363474634756347663477634786347963480634816348263483634846348563486634876348863489634906349163492634936349463495634966349763498634996350063501635026350363504635056350663507635086350963510635116351263513635146351563516635176351863519635206352163522635236352463525635266352763528635296353063531635326353363534635356353663537635386353963540635416354263543635446354563546635476354863549635506355163552635536355463555635566355763558635596356063561635626356363564635656356663567635686356963570635716357263573635746357563576635776357863579635806358163582635836358463585635866358763588635896359063591635926359363594635956359663597635986359963600636016360263603636046360563606636076360863609636106361163612636136361463615636166361763618636196362063621636226362363624636256362663627636286362963630636316363263633636346363563636636376363863639636406364163642636436364463645636466364763648636496365063651636526365363654636556365663657636586365963660636616366263663636646366563666636676366863669636706367163672636736367463675636766367763678636796368063681636826368363684636856368663687636886368963690636916369263693636946369563696636976369863699637006370163702637036370463705637066370763708637096371063711637126371363714637156371663717637186371963720637216372263723637246372563726637276372863729637306373163732637336373463735637366373763738637396374063741637426374363744637456374663747637486374963750637516375263753637546375563756637576375863759637606376163762637636376463765637666376763768637696377063771637726377363774637756377663777637786377963780637816378263783637846378563786637876378863789637906379163792637936379463795637966379763798637996380063801638026380363804638056380663807638086380963810638116381263813638146381563816638176381863819638206382163822638236382463825638266382763828638296383063831638326383363834638356383663837638386383963840638416384263843638446384563846638476384863849638506385163852638536385463855638566385763858638596386063861638626386363864638656386663867638686386963870638716387263873638746387563876638776387863879638806388163882638836388463885638866388763888638896389063891638926389363894638956389663897638986389963900639016390263903639046390563906639076390863909639106391163912639136391463915639166391763918639196392063921639226392363924639256392663927639286392963930639316393263933639346393563936639376393863939639406394163942639436394463945639466394763948639496395063951639526395363954639556395663957639586395963960639616396263963639646396563966639676396863969639706397163972639736397463975639766397763978639796398063981639826398363984639856398663987639886398963990639916399263993639946399563996639976399863999640006400164002640036400464005640066400764008640096401064011640126401364014640156401664017640186401964020640216402264023640246402564026640276402864029640306403164032640336403464035640366403764038640396404064041640426404364044640456404664047640486404964050640516405264053640546405564056640576405864059640606406164062640636406464065640666406764068640696407064071640726407364074640756407664077640786407964080640816408264083640846408564086640876408864089640906409164092640936409464095640966409764098640996410064101641026410364104641056410664107641086410964110641116411264113641146411564116641176411864119641206412164122641236412464125641266412764128641296413064131641326413364134641356413664137641386413964140641416414264143641446414564146641476414864149641506415164152641536415464155641566415764158641596416064161641626416364164641656416664167641686416964170641716417264173641746417564176641776417864179641806418164182641836418464185641866418764188641896419064191641926419364194641956419664197641986419964200642016420264203642046420564206642076420864209642106421164212642136421464215642166421764218642196422064221642226422364224642256422664227642286422964230642316423264233642346423564236642376423864239642406424164242642436424464245642466424764248642496425064251642526425364254642556425664257642586425964260642616426264263642646426564266642676426864269642706427164272642736427464275642766427764278642796428064281642826428364284642856428664287642886428964290642916429264293642946429564296642976429864299643006430164302643036430464305643066430764308643096431064311643126431364314643156431664317643186431964320643216432264323643246432564326643276432864329643306433164332643336433464335643366433764338643396434064341643426434364344643456434664347643486434964350643516435264353643546435564356643576435864359643606436164362643636436464365643666436764368643696437064371643726437364374643756437664377643786437964380643816438264383643846438564386643876438864389643906439164392643936439464395643966439764398643996440064401644026440364404644056440664407644086440964410644116441264413644146441564416644176441864419644206442164422644236442464425644266442764428644296443064431644326443364434644356443664437644386443964440644416444264443644446444564446644476444864449644506445164452644536445464455644566445764458644596446064461644626446364464644656446664467644686446964470644716447264473644746447564476644776447864479644806448164482644836448464485644866448764488644896449064491644926449364494644956449664497644986449964500645016450264503645046450564506645076450864509645106451164512645136451464515645166451764518645196452064521645226452364524645256452664527645286452964530645316453264533645346453564536645376453864539645406454164542645436454464545645466454764548645496455064551645526455364554645556455664557645586455964560645616456264563645646456564566645676456864569645706457164572645736457464575645766457764578645796458064581645826458364584645856458664587645886458964590645916459264593645946459564596645976459864599646006460164602646036460464605646066460764608646096461064611646126461364614646156461664617646186461964620646216462264623646246462564626646276462864629646306463164632646336463464635646366463764638646396464064641646426464364644646456464664647646486464964650646516465264653646546465564656646576465864659646606466164662646636466464665646666466764668646696467064671646726467364674646756467664677646786467964680646816468264683646846468564686646876468864689646906469164692646936469464695646966469764698646996470064701647026470364704647056470664707647086470964710647116471264713647146471564716647176471864719647206472164722647236472464725647266472764728647296473064731647326473364734647356473664737647386473964740647416474264743647446474564746647476474864749647506475164752647536475464755647566475764758647596476064761647626476364764647656476664767647686476964770647716477264773647746477564776647776477864779647806478164782647836478464785647866478764788647896479064791647926479364794647956479664797647986479964800648016480264803648046480564806648076480864809648106481164812648136481464815648166481764818648196482064821648226482364824648256482664827648286482964830648316483264833648346483564836648376483864839648406484164842648436484464845648466484764848648496485064851648526485364854648556485664857648586485964860648616486264863648646486564866648676486864869648706487164872648736487464875648766487764878648796488064881648826488364884648856488664887648886488964890648916489264893648946489564896648976489864899649006490164902649036490464905649066490764908649096491064911649126491364914649156491664917649186491964920649216492264923649246492564926649276492864929649306493164932649336493464935649366493764938649396494064941649426494364944649456494664947649486494964950649516495264953649546495564956649576495864959649606496164962649636496464965649666496764968649696497064971649726497364974649756497664977649786497964980649816498264983649846498564986649876498864989649906499164992649936499464995649966499764998649996500065001650026500365004650056500665007650086500965010650116501265013650146501565016650176501865019650206502165022650236502465025650266502765028650296503065031650326503365034650356503665037650386503965040650416504265043650446504565046650476504865049650506505165052650536505465055650566505765058650596506065061650626506365064650656506665067650686506965070650716507265073650746507565076650776507865079650806508165082650836508465085650866508765088650896509065091650926509365094650956509665097650986509965100651016510265103651046510565106651076510865109651106511165112651136511465115651166511765118651196512065121651226512365124651256512665127651286512965130651316513265133651346513565136651376513865139651406514165142651436514465145651466514765148651496515065151651526515365154651556515665157651586515965160651616516265163651646516565166651676516865169651706517165172651736517465175651766517765178651796518065181651826518365184651856518665187651886518965190651916519265193651946519565196651976519865199652006520165202652036520465205652066520765208652096521065211652126521365214652156521665217652186521965220652216522265223652246522565226652276522865229652306523165232652336523465235652366523765238652396524065241652426524365244652456524665247652486524965250652516525265253652546525565256652576525865259652606526165262652636526465265652666526765268652696527065271652726527365274652756527665277652786527965280652816528265283652846528565286652876528865289652906529165292652936529465295652966529765298652996530065301653026530365304653056530665307653086530965310653116531265313653146531565316653176531865319653206532165322653236532465325653266532765328653296533065331653326533365334653356533665337653386533965340653416534265343653446534565346653476534865349653506535165352653536535465355653566535765358653596536065361653626536365364653656536665367653686536965370653716537265373653746537565376653776537865379653806538165382653836538465385653866538765388653896539065391653926539365394653956539665397653986539965400654016540265403654046540565406654076540865409654106541165412654136541465415654166541765418654196542065421654226542365424654256542665427654286542965430654316543265433654346543565436654376543865439654406544165442654436544465445654466544765448654496545065451654526545365454654556545665457654586545965460654616546265463654646546565466654676546865469654706547165472654736547465475654766547765478654796548065481654826548365484654856548665487654886548965490654916549265493654946549565496654976549865499655006550165502655036550465505655066550765508655096551065511655126551365514655156551665517655186551965520655216552265523655246552565526655276552865529655306553165532655336553465535655366553765538655396554065541655426554365544655456554665547655486554965550655516555265553655546555565556655576555865559655606556165562655636556465565655666556765568655696557065571655726557365574655756557665577655786557965580655816558265583655846558565586655876558865589655906559165592655936559465595655966559765598655996560065601656026560365604656056560665607656086560965610656116561265613656146561565616656176561865619656206562165622656236562465625656266562765628656296563065631656326563365634656356563665637656386563965640656416564265643656446564565646656476564865649656506565165652656536565465655656566565765658656596566065661656626566365664656656566665667656686566965670656716567265673656746567565676656776567865679656806568165682656836568465685656866568765688656896569065691656926569365694656956569665697656986569965700657016570265703657046570565706657076570865709657106571165712657136571465715657166571765718657196572065721657226572365724657256572665727657286572965730657316573265733657346573565736657376573865739657406574165742657436574465745657466574765748657496575065751657526575365754657556575665757657586575965760657616576265763657646576565766657676576865769657706577165772657736577465775657766577765778657796578065781657826578365784657856578665787657886578965790657916579265793657946579565796657976579865799658006580165802658036580465805658066580765808658096581065811658126581365814658156581665817658186581965820658216582265823658246582565826658276582865829658306583165832658336583465835658366583765838658396584065841658426584365844658456584665847658486584965850658516585265853658546585565856658576585865859658606586165862658636586465865658666586765868658696587065871658726587365874658756587665877658786587965880658816588265883658846588565886658876588865889658906589165892658936589465895658966589765898658996590065901659026590365904659056590665907659086590965910659116591265913659146591565916659176591865919659206592165922659236592465925659266592765928659296593065931659326593365934659356593665937659386593965940659416594265943659446594565946659476594865949659506595165952659536595465955659566595765958659596596065961659626596365964659656596665967659686596965970659716597265973659746597565976659776597865979659806598165982659836598465985659866598765988659896599065991659926599365994659956599665997659986599966000660016600266003660046600566006660076600866009660106601166012660136601466015660166601766018660196602066021660226602366024660256602666027660286602966030660316603266033660346603566036660376603866039660406604166042660436604466045660466604766048660496605066051660526605366054660556605666057660586605966060660616606266063660646606566066660676606866069660706607166072660736607466075660766607766078660796608066081660826608366084660856608666087660886608966090660916609266093660946609566096660976609866099661006610166102661036610466105661066610766108661096611066111661126611366114661156611666117661186611966120661216612266123661246612566126661276612866129661306613166132661336613466135661366613766138661396614066141661426614366144661456614666147661486614966150661516615266153661546615566156661576615866159661606616166162661636616466165661666616766168661696617066171661726617366174661756617666177661786617966180661816618266183661846618566186661876618866189661906619166192661936619466195661966619766198661996620066201662026620366204662056620666207662086620966210662116621266213662146621566216662176621866219662206622166222662236622466225662266622766228662296623066231662326623366234662356623666237662386623966240662416624266243662446624566246662476624866249662506625166252662536625466255662566625766258662596626066261662626626366264662656626666267662686626966270662716627266273662746627566276662776627866279662806628166282662836628466285662866628766288662896629066291662926629366294662956629666297662986629966300663016630266303663046630566306663076630866309663106631166312663136631466315663166631766318663196632066321663226632366324663256632666327663286632966330663316633266333663346633566336663376633866339663406634166342663436634466345663466634766348663496635066351663526635366354663556635666357663586635966360663616636266363663646636566366663676636866369663706637166372663736637466375663766637766378663796638066381663826638366384663856638666387663886638966390663916639266393663946639566396663976639866399664006640166402664036640466405664066640766408664096641066411664126641366414664156641666417664186641966420664216642266423664246642566426664276642866429664306643166432664336643466435664366643766438664396644066441664426644366444664456644666447664486644966450664516645266453664546645566456664576645866459664606646166462664636646466465664666646766468664696647066471664726647366474664756647666477664786647966480664816648266483664846648566486664876648866489664906649166492664936649466495664966649766498664996650066501665026650366504665056650666507665086650966510665116651266513665146651566516665176651866519665206652166522665236652466525665266652766528665296653066531665326653366534665356653666537665386653966540665416654266543665446654566546665476654866549665506655166552665536655466555665566655766558665596656066561665626656366564665656656666567665686656966570665716657266573665746657566576665776657866579665806658166582665836658466585665866658766588665896659066591665926659366594665956659666597665986659966600666016660266603666046660566606666076660866609666106661166612666136661466615666166661766618666196662066621666226662366624666256662666627666286662966630666316663266633666346663566636666376663866639666406664166642666436664466645666466664766648666496665066651666526665366654666556665666657666586665966660666616666266663666646666566666666676666866669666706667166672666736667466675666766667766678666796668066681666826668366684666856668666687666886668966690666916669266693666946669566696666976669866699667006670166702667036670466705667066670766708667096671066711667126671366714667156671666717667186671966720667216672266723667246672566726667276672866729667306673166732667336673466735667366673766738667396674066741667426674366744667456674666747667486674966750667516675266753667546675566756667576675866759667606676166762667636676466765667666676766768667696677066771667726677366774667756677666777667786677966780667816678266783667846678566786667876678866789667906679166792667936679466795667966679766798667996680066801668026680366804668056680666807668086680966810668116681266813668146681566816668176681866819668206682166822668236682466825668266682766828668296683066831668326683366834668356683666837668386683966840668416684266843668446684566846668476684866849668506685166852668536685466855668566685766858668596686066861668626686366864668656686666867668686686966870668716687266873668746687566876668776687866879668806688166882668836688466885668866688766888668896689066891668926689366894668956689666897668986689966900669016690266903669046690566906669076690866909669106691166912669136691466915669166691766918669196692066921669226692366924669256692666927669286692966930669316693266933669346693566936669376693866939669406694166942669436694466945669466694766948669496695066951669526695366954669556695666957669586695966960669616696266963669646696566966669676696866969669706697166972669736697466975669766697766978669796698066981669826698366984669856698666987669886698966990669916699266993669946699566996669976699866999670006700167002670036700467005670066700767008670096701067011670126701367014670156701667017670186701967020670216702267023670246702567026670276702867029670306703167032670336703467035670366703767038670396704067041670426704367044670456704667047670486704967050670516705267053670546705567056670576705867059670606706167062670636706467065670666706767068670696707067071670726707367074670756707667077670786707967080670816708267083670846708567086670876708867089670906709167092670936709467095670966709767098670996710067101671026710367104671056710667107671086710967110671116711267113671146711567116671176711867119671206712167122671236712467125671266712767128671296713067131671326713367134671356713667137671386713967140671416714267143671446714567146671476714867149671506715167152671536715467155671566715767158671596716067161671626716367164671656716667167671686716967170671716717267173671746717567176671776717867179671806718167182671836718467185671866718767188671896719067191671926719367194671956719667197671986719967200672016720267203672046720567206672076720867209672106721167212672136721467215672166721767218672196722067221672226722367224672256722667227672286722967230672316723267233672346723567236672376723867239672406724167242672436724467245672466724767248672496725067251672526725367254672556725667257672586725967260672616726267263672646726567266672676726867269672706727167272672736727467275672766727767278672796728067281672826728367284672856728667287672886728967290672916729267293672946729567296672976729867299673006730167302673036730467305673066730767308673096731067311673126731367314673156731667317673186731967320673216732267323673246732567326673276732867329673306733167332673336733467335673366733767338673396734067341673426734367344673456734667347673486734967350673516735267353673546735567356673576735867359673606736167362673636736467365673666736767368673696737067371673726737367374673756737667377673786737967380673816738267383673846738567386673876738867389673906739167392673936739467395673966739767398673996740067401674026740367404674056740667407674086740967410674116741267413674146741567416674176741867419674206742167422674236742467425674266742767428674296743067431674326743367434674356743667437674386743967440674416744267443674446744567446674476744867449674506745167452674536745467455674566745767458674596746067461674626746367464674656746667467674686746967470674716747267473674746747567476674776747867479674806748167482674836748467485674866748767488674896749067491674926749367494674956749667497674986749967500675016750267503675046750567506675076750867509675106751167512675136751467515675166751767518675196752067521675226752367524675256752667527675286752967530675316753267533675346753567536675376753867539675406754167542675436754467545675466754767548675496755067551675526755367554675556755667557675586755967560675616756267563675646756567566675676756867569675706757167572675736757467575675766757767578675796758067581675826758367584675856758667587675886758967590675916759267593675946759567596675976759867599676006760167602676036760467605676066760767608676096761067611676126761367614676156761667617676186761967620676216762267623676246762567626676276762867629676306763167632676336763467635676366763767638676396764067641676426764367644676456764667647676486764967650676516765267653676546765567656676576765867659676606766167662676636766467665676666766767668676696767067671676726767367674676756767667677676786767967680676816768267683676846768567686676876768867689676906769167692676936769467695676966769767698676996770067701677026770367704677056770667707677086770967710677116771267713677146771567716677176771867719677206772167722677236772467725677266772767728677296773067731677326773367734677356773667737677386773967740677416774267743677446774567746677476774867749677506775167752677536775467755677566775767758677596776067761677626776367764677656776667767677686776967770677716777267773677746777567776677776777867779677806778167782677836778467785677866778767788677896779067791677926779367794677956779667797677986779967800678016780267803678046780567806678076780867809678106781167812678136781467815678166781767818678196782067821678226782367824678256782667827678286782967830678316783267833678346783567836678376783867839678406784167842678436784467845678466784767848678496785067851678526785367854678556785667857678586785967860678616786267863678646786567866678676786867869678706787167872678736787467875678766787767878678796788067881678826788367884678856788667887678886788967890678916789267893678946789567896678976789867899679006790167902679036790467905679066790767908679096791067911679126791367914679156791667917679186791967920679216792267923679246792567926679276792867929679306793167932679336793467935679366793767938679396794067941679426794367944679456794667947679486794967950679516795267953679546795567956679576795867959679606796167962679636796467965679666796767968679696797067971679726797367974679756797667977679786797967980679816798267983679846798567986679876798867989679906799167992679936799467995679966799767998679996800068001680026800368004680056800668007680086800968010680116801268013680146801568016680176801868019680206802168022680236802468025680266802768028680296803068031680326803368034680356803668037680386803968040680416804268043680446804568046680476804868049680506805168052680536805468055680566805768058680596806068061680626806368064680656806668067680686806968070680716807268073680746807568076680776807868079680806808168082680836808468085680866808768088680896809068091680926809368094680956809668097680986809968100681016810268103681046810568106681076810868109681106811168112681136811468115681166811768118681196812068121681226812368124681256812668127681286812968130681316813268133681346813568136681376813868139681406814168142681436814468145681466814768148681496815068151681526815368154681556815668157681586815968160681616816268163681646816568166681676816868169681706817168172681736817468175681766817768178681796818068181681826818368184681856818668187681886818968190681916819268193681946819568196681976819868199682006820168202682036820468205682066820768208682096821068211682126821368214682156821668217682186821968220682216822268223682246822568226682276822868229682306823168232682336823468235682366823768238682396824068241682426824368244682456824668247682486824968250682516825268253682546825568256682576825868259682606826168262682636826468265682666826768268682696827068271682726827368274682756827668277682786827968280682816828268283682846828568286682876828868289682906829168292682936829468295682966829768298682996830068301683026830368304683056830668307683086830968310683116831268313683146831568316683176831868319683206832168322683236832468325683266832768328683296833068331683326833368334683356833668337683386833968340683416834268343683446834568346683476834868349683506835168352683536835468355683566835768358683596836068361683626836368364683656836668367683686836968370683716837268373683746837568376683776837868379683806838168382683836838468385683866838768388683896839068391683926839368394683956839668397683986839968400684016840268403684046840568406684076840868409684106841168412684136841468415684166841768418684196842068421684226842368424684256842668427684286842968430684316843268433684346843568436684376843868439684406844168442684436844468445684466844768448684496845068451684526845368454684556845668457684586845968460684616846268463684646846568466684676846868469684706847168472684736847468475684766847768478684796848068481684826848368484684856848668487684886848968490684916849268493684946849568496684976849868499685006850168502685036850468505685066850768508685096851068511685126851368514685156851668517685186851968520685216852268523685246852568526685276852868529685306853168532685336853468535685366853768538685396854068541685426854368544685456854668547685486854968550685516855268553685546855568556685576855868559685606856168562685636856468565685666856768568685696857068571685726857368574685756857668577685786857968580685816858268583685846858568586685876858868589685906859168592685936859468595685966859768598685996860068601686026860368604686056860668607686086860968610686116861268613686146861568616686176861868619686206862168622686236862468625686266862768628686296863068631686326863368634686356863668637686386863968640686416864268643686446864568646686476864868649686506865168652686536865468655686566865768658686596866068661686626866368664686656866668667686686866968670686716867268673686746867568676686776867868679686806868168682686836868468685686866868768688686896869068691686926869368694686956869668697686986869968700687016870268703687046870568706687076870868709687106871168712687136871468715687166871768718687196872068721687226872368724687256872668727687286872968730687316873268733687346873568736687376873868739687406874168742687436874468745687466874768748687496875068751687526875368754687556875668757687586875968760687616876268763687646876568766687676876868769687706877168772687736877468775687766877768778687796878068781687826878368784687856878668787687886878968790687916879268793687946879568796687976879868799688006880168802688036880468805688066880768808688096881068811688126881368814688156881668817688186881968820688216882268823688246882568826688276882868829688306883168832688336883468835688366883768838688396884068841688426884368844688456884668847688486884968850688516885268853688546885568856688576885868859688606886168862688636886468865688666886768868688696887068871688726887368874688756887668877688786887968880688816888268883688846888568886688876888868889688906889168892688936889468895688966889768898688996890068901689026890368904689056890668907689086890968910689116891268913689146891568916689176891868919689206892168922689236892468925689266892768928689296893068931689326893368934689356893668937689386893968940689416894268943689446894568946689476894868949689506895168952689536895468955689566895768958689596896068961689626896368964689656896668967689686896968970689716897268973689746897568976689776897868979689806898168982689836898468985689866898768988689896899068991689926899368994689956899668997689986899969000690016900269003690046900569006690076900869009690106901169012690136901469015690166901769018690196902069021690226902369024690256902669027690286902969030690316903269033690346903569036690376903869039690406904169042690436904469045690466904769048690496905069051690526905369054690556905669057690586905969060690616906269063690646906569066690676906869069690706907169072690736907469075690766907769078690796908069081690826908369084690856908669087690886908969090690916909269093690946909569096690976909869099691006910169102691036910469105691066910769108691096911069111691126911369114691156911669117691186911969120691216912269123691246912569126691276912869129691306913169132691336913469135691366913769138691396914069141691426914369144691456914669147691486914969150691516915269153691546915569156691576915869159691606916169162691636916469165691666916769168691696917069171691726917369174691756917669177691786917969180691816918269183691846918569186691876918869189691906919169192691936919469195691966919769198691996920069201692026920369204692056920669207692086920969210692116921269213692146921569216692176921869219692206922169222692236922469225692266922769228692296923069231692326923369234692356923669237692386923969240692416924269243692446924569246692476924869249692506925169252692536925469255692566925769258692596926069261692626926369264692656926669267692686926969270692716927269273692746927569276692776927869279692806928169282692836928469285692866928769288692896929069291692926929369294692956929669297692986929969300693016930269303693046930569306693076930869309693106931169312693136931469315693166931769318693196932069321693226932369324693256932669327693286932969330693316933269333693346933569336693376933869339693406934169342693436934469345693466934769348693496935069351693526935369354693556935669357693586935969360693616936269363693646936569366693676936869369693706937169372693736937469375693766937769378693796938069381693826938369384693856938669387693886938969390693916939269393693946939569396693976939869399694006940169402694036940469405694066940769408694096941069411694126941369414694156941669417694186941969420694216942269423694246942569426694276942869429694306943169432694336943469435694366943769438694396944069441694426944369444694456944669447694486944969450694516945269453694546945569456694576945869459694606946169462694636946469465694666946769468694696947069471694726947369474694756947669477694786947969480694816948269483694846948569486694876948869489694906949169492694936949469495694966949769498694996950069501695026950369504695056950669507695086950969510695116951269513695146951569516695176951869519695206952169522695236952469525695266952769528695296953069531695326953369534695356953669537695386953969540695416954269543695446954569546695476954869549695506955169552695536955469555695566955769558695596956069561695626956369564695656956669567695686956969570695716957269573695746957569576695776957869579695806958169582695836958469585695866958769588695896959069591695926959369594695956959669597695986959969600696016960269603696046960569606696076960869609696106961169612696136961469615696166961769618696196962069621696226962369624696256962669627696286962969630696316963269633696346963569636696376963869639696406964169642696436964469645696466964769648696496965069651696526965369654696556965669657696586965969660696616966269663696646966569666696676966869669696706967169672696736967469675696766967769678696796968069681696826968369684696856968669687696886968969690696916969269693696946969569696696976969869699697006970169702697036970469705697066970769708697096971069711697126971369714697156971669717697186971969720697216972269723697246972569726697276972869729697306973169732697336973469735697366973769738697396974069741697426974369744697456974669747697486974969750697516975269753697546975569756697576975869759697606976169762697636976469765697666976769768697696977069771697726977369774697756977669777697786977969780697816978269783697846978569786697876978869789697906979169792697936979469795697966979769798697996980069801698026980369804698056980669807698086980969810698116981269813698146981569816698176981869819698206982169822698236982469825698266982769828698296983069831698326983369834698356983669837698386983969840698416984269843698446984569846698476984869849698506985169852698536985469855698566985769858698596986069861698626986369864698656986669867698686986969870698716987269873698746987569876698776987869879698806988169882698836988469885698866988769888698896989069891698926989369894698956989669897698986989969900699016990269903699046990569906699076990869909699106991169912699136991469915699166991769918699196992069921699226992369924699256992669927699286992969930699316993269933699346993569936699376993869939699406994169942699436994469945699466994769948699496995069951699526995369954699556995669957699586995969960699616996269963699646996569966699676996869969699706997169972699736997469975699766997769978699796998069981699826998369984699856998669987699886998969990699916999269993699946999569996699976999869999700007000170002700037000470005700067000770008700097001070011700127001370014700157001670017700187001970020700217002270023700247002570026700277002870029700307003170032700337003470035700367003770038700397004070041700427004370044700457004670047700487004970050700517005270053700547005570056700577005870059700607006170062700637006470065700667006770068700697007070071700727007370074700757007670077700787007970080700817008270083700847008570086700877008870089700907009170092700937009470095700967009770098700997010070101701027010370104701057010670107701087010970110701117011270113701147011570116701177011870119701207012170122701237012470125701267012770128701297013070131701327013370134701357013670137701387013970140701417014270143701447014570146701477014870149701507015170152701537015470155701567015770158701597016070161701627016370164701657016670167701687016970170701717017270173701747017570176701777017870179701807018170182701837018470185701867018770188701897019070191701927019370194701957019670197701987019970200702017020270203702047020570206702077020870209702107021170212702137021470215702167021770218702197022070221702227022370224702257022670227702287022970230702317023270233702347023570236702377023870239702407024170242702437024470245702467024770248702497025070251702527025370254702557025670257702587025970260702617026270263702647026570266702677026870269702707027170272702737027470275702767027770278702797028070281702827028370284702857028670287702887028970290702917029270293702947029570296702977029870299703007030170302703037030470305703067030770308703097031070311703127031370314703157031670317703187031970320703217032270323703247032570326703277032870329703307033170332703337033470335703367033770338703397034070341703427034370344703457034670347703487034970350703517035270353703547035570356703577035870359703607036170362703637036470365703667036770368703697037070371703727037370374703757037670377703787037970380703817038270383703847038570386703877038870389703907039170392703937039470395703967039770398703997040070401704027040370404704057040670407704087040970410704117041270413704147041570416704177041870419704207042170422704237042470425704267042770428704297043070431704327043370434704357043670437704387043970440704417044270443704447044570446704477044870449704507045170452704537045470455704567045770458704597046070461704627046370464704657046670467704687046970470704717047270473704747047570476704777047870479704807048170482704837048470485704867048770488704897049070491704927049370494704957049670497704987049970500705017050270503705047050570506705077050870509705107051170512705137051470515705167051770518705197052070521705227052370524705257052670527705287052970530705317053270533705347053570536705377053870539705407054170542705437054470545705467054770548705497055070551705527055370554705557055670557705587055970560705617056270563705647056570566705677056870569705707057170572705737057470575705767057770578705797058070581705827058370584705857058670587705887058970590705917059270593705947059570596705977059870599706007060170602706037060470605706067060770608706097061070611706127061370614706157061670617706187061970620706217062270623706247062570626706277062870629706307063170632706337063470635706367063770638706397064070641706427064370644706457064670647706487064970650706517065270653706547065570656706577065870659706607066170662706637066470665706667066770668706697067070671706727067370674706757067670677706787067970680706817068270683706847068570686706877068870689706907069170692706937069470695706967069770698706997070070701707027070370704707057070670707707087070970710707117071270713707147071570716707177071870719707207072170722707237072470725707267072770728707297073070731707327073370734707357073670737707387073970740707417074270743707447074570746707477074870749707507075170752707537075470755707567075770758707597076070761707627076370764707657076670767707687076970770707717077270773707747077570776707777077870779707807078170782707837078470785707867078770788707897079070791707927079370794707957079670797707987079970800708017080270803708047080570806708077080870809708107081170812708137081470815708167081770818708197082070821708227082370824708257082670827708287082970830708317083270833708347083570836708377083870839708407084170842708437084470845708467084770848708497085070851708527085370854708557085670857708587085970860708617086270863708647086570866708677086870869708707087170872708737087470875708767087770878708797088070881708827088370884708857088670887708887088970890708917089270893708947089570896708977089870899709007090170902709037090470905709067090770908709097091070911709127091370914709157091670917709187091970920709217092270923709247092570926709277092870929709307093170932709337093470935709367093770938709397094070941709427094370944709457094670947709487094970950709517095270953709547095570956709577095870959709607096170962709637096470965709667096770968709697097070971709727097370974709757097670977709787097970980709817098270983709847098570986709877098870989709907099170992709937099470995709967099770998709997100071001710027100371004710057100671007710087100971010710117101271013710147101571016710177101871019710207102171022710237102471025710267102771028710297103071031710327103371034710357103671037710387103971040710417104271043710447104571046710477104871049710507105171052710537105471055710567105771058710597106071061710627106371064710657106671067710687106971070710717107271073710747107571076710777107871079710807108171082710837108471085710867108771088710897109071091710927109371094710957109671097710987109971100711017110271103711047110571106711077110871109711107111171112711137111471115711167111771118711197112071121711227112371124711257112671127711287112971130711317113271133711347113571136711377113871139711407114171142711437114471145711467114771148711497115071151711527115371154711557115671157711587115971160711617116271163711647116571166711677116871169711707117171172711737117471175711767117771178711797118071181711827118371184711857118671187711887118971190711917119271193711947119571196711977119871199712007120171202712037120471205712067120771208712097121071211712127121371214712157121671217712187121971220712217122271223712247122571226712277122871229712307123171232712337123471235712367123771238712397124071241712427124371244712457124671247712487124971250712517125271253712547125571256712577125871259712607126171262712637126471265712667126771268712697127071271712727127371274712757127671277712787127971280712817128271283712847128571286712877128871289712907129171292712937129471295712967129771298712997130071301713027130371304713057130671307713087130971310713117131271313713147131571316713177131871319713207132171322713237132471325713267132771328713297133071331713327133371334713357133671337713387133971340713417134271343713447134571346713477134871349713507135171352713537135471355713567135771358713597136071361713627136371364713657136671367713687136971370713717137271373713747137571376713777137871379713807138171382713837138471385713867138771388713897139071391713927139371394713957139671397713987139971400714017140271403714047140571406714077140871409714107141171412714137141471415714167141771418714197142071421714227142371424714257142671427714287142971430714317143271433714347143571436714377143871439714407144171442714437144471445714467144771448714497145071451714527145371454714557145671457714587145971460714617146271463714647146571466714677146871469714707147171472714737147471475714767147771478714797148071481714827148371484714857148671487714887148971490714917149271493714947149571496714977149871499715007150171502715037150471505715067150771508715097151071511715127151371514715157151671517715187151971520715217152271523715247152571526715277152871529715307153171532715337153471535715367153771538715397154071541715427154371544715457154671547715487154971550715517155271553715547155571556715577155871559715607156171562715637156471565715667156771568715697157071571715727157371574715757157671577715787157971580715817158271583715847158571586715877158871589715907159171592715937159471595715967159771598715997160071601716027160371604716057160671607716087160971610716117161271613716147161571616716177161871619716207162171622716237162471625716267162771628716297163071631716327163371634716357163671637716387163971640716417164271643716447164571646716477164871649716507165171652716537165471655716567165771658716597166071661716627166371664716657166671667716687166971670716717167271673716747167571676716777167871679716807168171682716837168471685716867168771688716897169071691716927169371694716957169671697716987169971700717017170271703717047170571706717077170871709717107171171712717137171471715717167171771718717197172071721717227172371724717257172671727717287172971730717317173271733717347173571736717377173871739717407174171742717437174471745717467174771748717497175071751717527175371754717557175671757717587175971760717617176271763717647176571766717677176871769717707177171772717737177471775717767177771778717797178071781717827178371784717857178671787717887178971790717917179271793717947179571796717977179871799718007180171802718037180471805718067180771808718097181071811718127181371814718157181671817718187181971820718217182271823718247182571826718277182871829718307183171832718337183471835718367183771838718397184071841718427184371844718457184671847718487184971850718517185271853718547185571856718577185871859718607186171862718637186471865718667186771868718697187071871718727187371874718757187671877718787187971880718817188271883718847188571886718877188871889718907189171892718937189471895718967189771898718997190071901719027190371904719057190671907719087190971910719117191271913719147191571916719177191871919719207192171922719237192471925719267192771928719297193071931719327193371934719357193671937719387193971940719417194271943719447194571946719477194871949719507195171952719537195471955719567195771958719597196071961719627196371964719657196671967719687196971970719717197271973719747197571976719777197871979719807198171982719837198471985719867198771988719897199071991719927199371994719957199671997719987199972000720017200272003720047200572006720077200872009720107201172012720137201472015720167201772018720197202072021720227202372024720257202672027720287202972030720317203272033720347203572036720377203872039720407204172042720437204472045720467204772048720497205072051720527205372054720557205672057720587205972060720617206272063720647206572066720677206872069720707207172072720737207472075720767207772078720797208072081720827208372084720857208672087720887208972090720917209272093720947209572096720977209872099721007210172102721037210472105721067210772108721097211072111721127211372114721157211672117721187211972120721217212272123721247212572126721277212872129721307213172132721337213472135721367213772138721397214072141721427214372144721457214672147721487214972150721517215272153721547215572156721577215872159721607216172162721637216472165721667216772168721697217072171721727217372174721757217672177721787217972180721817218272183721847218572186721877218872189721907219172192721937219472195721967219772198721997220072201722027220372204722057220672207722087220972210722117221272213722147221572216722177221872219722207222172222722237222472225722267222772228722297223072231722327223372234722357223672237722387223972240722417224272243722447224572246722477224872249722507225172252722537225472255722567225772258722597226072261722627226372264722657226672267722687226972270722717227272273722747227572276722777227872279722807228172282722837228472285722867228772288722897229072291722927229372294722957229672297722987229972300723017230272303723047230572306723077230872309723107231172312723137231472315723167231772318723197232072321723227232372324723257232672327723287232972330723317233272333723347233572336723377233872339723407234172342723437234472345723467234772348723497235072351723527235372354723557235672357723587235972360723617236272363723647236572366723677236872369723707237172372723737237472375723767237772378723797238072381723827238372384723857238672387723887238972390723917239272393723947239572396723977239872399724007240172402724037240472405724067240772408724097241072411724127241372414724157241672417724187241972420724217242272423724247242572426724277242872429724307243172432724337243472435724367243772438724397244072441724427244372444724457244672447724487244972450724517245272453724547245572456724577245872459724607246172462724637246472465724667246772468724697247072471724727247372474724757247672477724787247972480724817248272483724847248572486724877248872489724907249172492724937249472495724967249772498724997250072501725027250372504725057250672507725087250972510725117251272513725147251572516725177251872519725207252172522725237252472525725267252772528725297253072531725327253372534725357253672537725387253972540725417254272543725447254572546725477254872549725507255172552725537255472555725567255772558725597256072561725627256372564725657256672567725687256972570725717257272573725747257572576725777257872579725807258172582725837258472585725867258772588725897259072591725927259372594725957259672597725987259972600726017260272603726047260572606726077260872609726107261172612726137261472615726167261772618726197262072621726227262372624726257262672627726287262972630726317263272633726347263572636726377263872639726407264172642726437264472645726467264772648726497265072651726527265372654726557265672657726587265972660726617266272663726647266572666726677266872669726707267172672726737267472675726767267772678726797268072681726827268372684726857268672687726887268972690726917269272693726947269572696726977269872699727007270172702727037270472705727067270772708727097271072711727127271372714727157271672717727187271972720727217272272723727247272572726727277272872729727307273172732727337273472735727367273772738727397274072741727427274372744727457274672747727487274972750727517275272753727547275572756727577275872759727607276172762727637276472765727667276772768727697277072771727727277372774727757277672777727787277972780727817278272783727847278572786727877278872789727907279172792727937279472795727967279772798727997280072801728027280372804728057280672807728087280972810728117281272813728147281572816728177281872819728207282172822728237282472825728267282772828728297283072831728327283372834728357283672837728387283972840728417284272843728447284572846728477284872849728507285172852728537285472855728567285772858728597286072861728627286372864728657286672867728687286972870728717287272873728747287572876728777287872879728807288172882728837288472885728867288772888728897289072891728927289372894728957289672897728987289972900729017290272903729047290572906729077290872909729107291172912729137291472915729167291772918729197292072921729227292372924729257292672927729287292972930729317293272933729347293572936729377293872939729407294172942729437294472945729467294772948729497295072951729527295372954729557295672957729587295972960729617296272963729647296572966729677296872969729707297172972729737297472975729767297772978729797298072981729827298372984729857298672987729887298972990729917299272993729947299572996729977299872999730007300173002730037300473005730067300773008730097301073011730127301373014730157301673017730187301973020730217302273023730247302573026730277302873029730307303173032730337303473035730367303773038730397304073041730427304373044730457304673047730487304973050730517305273053730547305573056730577305873059730607306173062730637306473065730667306773068730697307073071730727307373074730757307673077730787307973080730817308273083730847308573086730877308873089730907309173092730937309473095730967309773098730997310073101731027310373104731057310673107731087310973110731117311273113731147311573116731177311873119731207312173122731237312473125731267312773128731297313073131731327313373134731357313673137731387313973140731417314273143731447314573146731477314873149731507315173152731537315473155731567315773158731597316073161731627316373164731657316673167731687316973170731717317273173731747317573176731777317873179731807318173182731837318473185731867318773188731897319073191731927319373194731957319673197731987319973200732017320273203732047320573206732077320873209732107321173212732137321473215732167321773218732197322073221732227322373224732257322673227732287322973230732317323273233732347323573236732377323873239732407324173242732437324473245732467324773248732497325073251732527325373254732557325673257732587325973260732617326273263732647326573266732677326873269732707327173272732737327473275732767327773278732797328073281732827328373284732857328673287732887328973290732917329273293732947329573296732977329873299733007330173302733037330473305733067330773308733097331073311733127331373314733157331673317733187331973320733217332273323733247332573326733277332873329733307333173332733337333473335733367333773338733397334073341733427334373344733457334673347733487334973350733517335273353733547335573356733577335873359733607336173362733637336473365733667336773368733697337073371733727337373374733757337673377733787337973380733817338273383733847338573386733877338873389733907339173392733937339473395733967339773398733997340073401734027340373404734057340673407734087340973410734117341273413734147341573416734177341873419734207342173422734237342473425734267342773428734297343073431734327343373434734357343673437734387343973440734417344273443734447344573446734477344873449734507345173452734537345473455734567345773458734597346073461734627346373464734657346673467734687346973470734717347273473734747347573476734777347873479734807348173482734837348473485734867348773488734897349073491734927349373494734957349673497734987349973500735017350273503735047350573506735077350873509735107351173512735137351473515735167351773518735197352073521735227352373524735257352673527735287352973530735317353273533735347353573536735377353873539735407354173542735437354473545735467354773548735497355073551735527355373554735557355673557735587355973560735617356273563735647356573566735677356873569735707357173572735737357473575735767357773578735797358073581735827358373584735857358673587735887358973590735917359273593735947359573596735977359873599736007360173602736037360473605736067360773608736097361073611736127361373614736157361673617736187361973620736217362273623736247362573626736277362873629736307363173632736337363473635736367363773638736397364073641736427364373644736457364673647736487364973650736517365273653736547365573656736577365873659736607366173662736637366473665736667366773668736697367073671736727367373674736757367673677736787367973680736817368273683736847368573686736877368873689736907369173692736937369473695736967369773698736997370073701737027370373704737057370673707737087370973710737117371273713737147371573716737177371873719737207372173722737237372473725737267372773728737297373073731737327373373734737357373673737737387373973740737417374273743737447374573746737477374873749737507375173752737537375473755737567375773758737597376073761737627376373764737657376673767737687376973770737717377273773737747377573776737777377873779737807378173782737837378473785737867378773788737897379073791737927379373794737957379673797737987379973800738017380273803738047380573806738077380873809738107381173812738137381473815738167381773818738197382073821738227382373824738257382673827738287382973830738317383273833738347383573836738377383873839738407384173842738437384473845738467384773848738497385073851738527385373854738557385673857738587385973860738617386273863738647386573866738677386873869738707387173872738737387473875738767387773878738797388073881738827388373884738857388673887738887388973890738917389273893738947389573896738977389873899739007390173902739037390473905739067390773908739097391073911739127391373914739157391673917739187391973920739217392273923739247392573926739277392873929739307393173932739337393473935739367393773938739397394073941739427394373944739457394673947739487394973950739517395273953739547395573956739577395873959739607396173962739637396473965739667396773968739697397073971739727397373974739757397673977739787397973980739817398273983739847398573986739877398873989739907399173992739937399473995739967399773998739997400074001740027400374004740057400674007740087400974010740117401274013740147401574016740177401874019740207402174022740237402474025740267402774028740297403074031740327403374034740357403674037740387403974040740417404274043740447404574046740477404874049740507405174052740537405474055740567405774058740597406074061740627406374064740657406674067740687406974070740717407274073740747407574076740777407874079740807408174082740837408474085740867408774088740897409074091740927409374094740957409674097740987409974100741017410274103741047410574106741077410874109741107411174112741137411474115741167411774118741197412074121741227412374124741257412674127741287412974130741317413274133741347413574136741377413874139741407414174142741437414474145741467414774148741497415074151741527415374154741557415674157741587415974160741617416274163741647416574166741677416874169741707417174172741737417474175741767417774178741797418074181741827418374184741857418674187741887418974190741917419274193741947419574196741977419874199742007420174202742037420474205742067420774208742097421074211742127421374214742157421674217742187421974220742217422274223742247422574226742277422874229742307423174232742337423474235742367423774238742397424074241742427424374244742457424674247742487424974250742517425274253742547425574256742577425874259742607426174262742637426474265742667426774268742697427074271742727427374274742757427674277742787427974280742817428274283742847428574286742877428874289742907429174292742937429474295742967429774298742997430074301743027430374304743057430674307743087430974310743117431274313743147431574316743177431874319743207432174322743237432474325743267432774328743297433074331743327433374334743357433674337743387433974340743417434274343743447434574346743477434874349743507435174352743537435474355743567435774358743597436074361743627436374364743657436674367743687436974370743717437274373743747437574376743777437874379743807438174382743837438474385743867438774388743897439074391743927439374394743957439674397743987439974400744017440274403744047440574406744077440874409744107441174412744137441474415744167441774418744197442074421744227442374424744257442674427744287442974430744317443274433744347443574436744377443874439744407444174442744437444474445744467444774448744497445074451744527445374454744557445674457744587445974460744617446274463744647446574466744677446874469744707447174472744737447474475744767447774478744797448074481744827448374484744857448674487744887448974490744917449274493744947449574496744977449874499745007450174502745037450474505745067450774508745097451074511745127451374514745157451674517745187451974520745217452274523745247452574526745277452874529745307453174532745337453474535745367453774538745397454074541745427454374544745457454674547745487454974550745517455274553745547455574556745577455874559745607456174562745637456474565745667456774568745697457074571745727457374574745757457674577745787457974580745817458274583745847458574586745877458874589745907459174592745937459474595745967459774598745997460074601746027460374604746057460674607746087460974610746117461274613746147461574616746177461874619746207462174622746237462474625746267462774628746297463074631746327463374634746357463674637746387463974640746417464274643746447464574646746477464874649746507465174652746537465474655746567465774658746597466074661746627466374664746657466674667746687466974670746717467274673746747467574676746777467874679746807468174682746837468474685746867468774688746897469074691746927469374694746957469674697746987469974700747017470274703747047470574706747077470874709747107471174712747137471474715747167471774718747197472074721747227472374724747257472674727747287472974730747317473274733747347473574736747377473874739747407474174742747437474474745747467474774748747497475074751747527475374754747557475674757747587475974760747617476274763747647476574766747677476874769747707477174772747737477474775747767477774778747797478074781747827478374784747857478674787747887478974790747917479274793747947479574796747977479874799748007480174802748037480474805748067480774808748097481074811748127481374814748157481674817748187481974820748217482274823748247482574826748277482874829748307483174832748337483474835748367483774838748397484074841748427484374844748457484674847748487484974850748517485274853748547485574856748577485874859748607486174862748637486474865748667486774868748697487074871748727487374874748757487674877748787487974880748817488274883748847488574886748877488874889748907489174892748937489474895748967489774898748997490074901749027490374904749057490674907749087490974910749117491274913749147491574916749177491874919749207492174922749237492474925749267492774928749297493074931749327493374934749357493674937749387493974940749417494274943749447494574946749477494874949749507495174952749537495474955749567495774958749597496074961749627496374964749657496674967749687496974970749717497274973749747497574976749777497874979749807498174982749837498474985749867498774988749897499074991749927499374994749957499674997749987499975000750017500275003750047500575006750077500875009750107501175012750137501475015750167501775018750197502075021750227502375024750257502675027750287502975030750317503275033750347503575036750377503875039750407504175042750437504475045750467504775048750497505075051750527505375054750557505675057750587505975060750617506275063750647506575066750677506875069750707507175072750737507475075750767507775078750797508075081750827508375084750857508675087750887508975090750917509275093750947509575096750977509875099751007510175102751037510475105751067510775108751097511075111751127511375114751157511675117751187511975120751217512275123751247512575126751277512875129751307513175132751337513475135751367513775138751397514075141751427514375144751457514675147751487514975150751517515275153751547515575156751577515875159751607516175162751637516475165751667516775168751697517075171751727517375174751757517675177751787517975180751817518275183751847518575186751877518875189751907519175192751937519475195751967519775198751997520075201752027520375204752057520675207752087520975210752117521275213752147521575216752177521875219752207522175222752237522475225752267522775228752297523075231752327523375234752357523675237752387523975240752417524275243752447524575246752477524875249752507525175252752537525475255752567525775258752597526075261752627526375264752657526675267752687526975270752717527275273752747527575276752777527875279752807528175282752837528475285752867528775288752897529075291752927529375294752957529675297752987529975300753017530275303753047530575306753077530875309753107531175312753137531475315753167531775318753197532075321753227532375324753257532675327753287532975330753317533275333753347533575336753377533875339753407534175342753437534475345753467534775348753497535075351753527535375354753557535675357753587535975360753617536275363753647536575366753677536875369753707537175372753737537475375753767537775378753797538075381753827538375384753857538675387753887538975390753917539275393753947539575396753977539875399754007540175402754037540475405754067540775408754097541075411754127541375414754157541675417754187541975420754217542275423754247542575426754277542875429754307543175432754337543475435754367543775438754397544075441754427544375444754457544675447754487544975450754517545275453754547545575456754577545875459754607546175462754637546475465754667546775468754697547075471754727547375474754757547675477754787547975480754817548275483754847548575486754877548875489754907549175492754937549475495754967549775498754997550075501755027550375504755057550675507755087550975510755117551275513755147551575516755177551875519755207552175522755237552475525755267552775528755297553075531755327553375534755357553675537755387553975540755417554275543755447554575546755477554875549755507555175552755537555475555755567555775558755597556075561755627556375564755657556675567755687556975570755717557275573755747557575576755777557875579755807558175582755837558475585755867558775588755897559075591755927559375594755957559675597755987559975600756017560275603756047560575606756077560875609756107561175612756137561475615756167561775618756197562075621756227562375624756257562675627756287562975630756317563275633756347563575636756377563875639756407564175642756437564475645756467564775648756497565075651756527565375654756557565675657756587565975660756617566275663756647566575666756677566875669756707567175672756737567475675756767567775678756797568075681756827568375684756857568675687756887568975690756917569275693756947569575696756977569875699757007570175702757037570475705757067570775708757097571075711757127571375714757157571675717757187571975720757217572275723757247572575726757277572875729757307573175732757337573475735757367573775738757397574075741757427574375744757457574675747757487574975750757517575275753757547575575756757577575875759757607576175762757637576475765757667576775768757697577075771757727577375774757757577675777757787577975780757817578275783757847578575786757877578875789757907579175792757937579475795757967579775798757997580075801758027580375804758057580675807758087580975810758117581275813758147581575816758177581875819758207582175822758237582475825758267582775828758297583075831758327583375834758357583675837758387583975840758417584275843758447584575846758477584875849758507585175852758537585475855758567585775858758597586075861758627586375864758657586675867758687586975870758717587275873758747587575876758777587875879758807588175882758837588475885758867588775888758897589075891758927589375894758957589675897758987589975900759017590275903759047590575906759077590875909759107591175912759137591475915759167591775918759197592075921759227592375924759257592675927759287592975930759317593275933759347593575936759377593875939759407594175942759437594475945759467594775948759497595075951759527595375954759557595675957759587595975960759617596275963759647596575966759677596875969759707597175972759737597475975759767597775978759797598075981759827598375984759857598675987759887598975990759917599275993759947599575996759977599875999760007600176002760037600476005760067600776008760097601076011760127601376014760157601676017760187601976020760217602276023760247602576026760277602876029760307603176032760337603476035760367603776038760397604076041760427604376044760457604676047760487604976050760517605276053760547605576056760577605876059760607606176062760637606476065760667606776068760697607076071760727607376074760757607676077760787607976080760817608276083760847608576086760877608876089760907609176092760937609476095760967609776098760997610076101761027610376104761057610676107761087610976110761117611276113761147611576116761177611876119761207612176122761237612476125761267612776128761297613076131761327613376134761357613676137761387613976140761417614276143761447614576146761477614876149761507615176152761537615476155761567615776158761597616076161761627616376164761657616676167761687616976170761717617276173761747617576176761777617876179761807618176182761837618476185761867618776188761897619076191761927619376194761957619676197761987619976200762017620276203762047620576206762077620876209762107621176212762137621476215762167621776218762197622076221762227622376224762257622676227762287622976230762317623276233762347623576236762377623876239762407624176242762437624476245762467624776248762497625076251762527625376254762557625676257762587625976260762617626276263762647626576266762677626876269762707627176272762737627476275762767627776278762797628076281762827628376284762857628676287762887628976290762917629276293762947629576296762977629876299763007630176302763037630476305763067630776308763097631076311763127631376314763157631676317763187631976320763217632276323763247632576326763277632876329763307633176332763337633476335763367633776338763397634076341763427634376344763457634676347763487634976350763517635276353763547635576356763577635876359763607636176362763637636476365763667636776368763697637076371763727637376374763757637676377763787637976380763817638276383763847638576386763877638876389763907639176392763937639476395763967639776398763997640076401764027640376404764057640676407764087640976410764117641276413764147641576416764177641876419764207642176422764237642476425764267642776428764297643076431764327643376434764357643676437764387643976440764417644276443764447644576446764477644876449764507645176452764537645476455764567645776458764597646076461764627646376464764657646676467764687646976470764717647276473764747647576476764777647876479764807648176482764837648476485764867648776488764897649076491764927649376494764957649676497764987649976500765017650276503765047650576506765077650876509765107651176512765137651476515765167651776518765197652076521765227652376524765257652676527765287652976530765317653276533765347653576536765377653876539765407654176542765437654476545765467654776548765497655076551765527655376554765557655676557765587655976560765617656276563765647656576566765677656876569765707657176572765737657476575765767657776578765797658076581765827658376584765857658676587765887658976590765917659276593765947659576596765977659876599766007660176602766037660476605766067660776608766097661076611766127661376614766157661676617766187661976620766217662276623766247662576626766277662876629766307663176632766337663476635766367663776638766397664076641766427664376644766457664676647766487664976650766517665276653766547665576656766577665876659766607666176662766637666476665766667666776668766697667076671766727667376674766757667676677766787667976680766817668276683766847668576686766877668876689766907669176692766937669476695766967669776698766997670076701767027670376704767057670676707767087670976710767117671276713767147671576716767177671876719767207672176722767237672476725767267672776728767297673076731767327673376734767357673676737767387673976740767417674276743767447674576746767477674876749767507675176752767537675476755767567675776758767597676076761767627676376764767657676676767767687676976770767717677276773767747677576776767777677876779767807678176782767837678476785767867678776788767897679076791767927679376794767957679676797767987679976800768017680276803768047680576806768077680876809768107681176812768137681476815768167681776818768197682076821768227682376824768257682676827768287682976830768317683276833768347683576836768377683876839768407684176842768437684476845768467684776848768497685076851768527685376854768557685676857768587685976860768617686276863768647686576866768677686876869768707687176872768737687476875768767687776878768797688076881768827688376884768857688676887768887688976890768917689276893768947689576896768977689876899769007690176902769037690476905769067690776908769097691076911769127691376914769157691676917769187691976920769217692276923769247692576926769277692876929769307693176932769337693476935769367693776938769397694076941769427694376944769457694676947769487694976950769517695276953769547695576956769577695876959769607696176962769637696476965769667696776968769697697076971769727697376974769757697676977769787697976980769817698276983769847698576986769877698876989769907699176992769937699476995769967699776998769997700077001770027700377004770057700677007770087700977010770117701277013770147701577016770177701877019770207702177022770237702477025770267702777028770297703077031770327703377034770357703677037770387703977040770417704277043770447704577046770477704877049770507705177052770537705477055770567705777058770597706077061770627706377064770657706677067770687706977070770717707277073770747707577076770777707877079770807708177082770837708477085770867708777088770897709077091770927709377094770957709677097770987709977100771017710277103771047710577106771077710877109771107711177112771137711477115771167711777118771197712077121771227712377124771257712677127771287712977130771317713277133771347713577136771377713877139771407714177142771437714477145771467714777148771497715077151771527715377154771557715677157771587715977160771617716277163771647716577166771677716877169771707717177172771737717477175771767717777178771797718077181771827718377184771857718677187771887718977190771917719277193771947719577196771977719877199772007720177202772037720477205772067720777208772097721077211772127721377214772157721677217772187721977220772217722277223772247722577226772277722877229772307723177232772337723477235772367723777238772397724077241772427724377244772457724677247772487724977250772517725277253772547725577256772577725877259772607726177262772637726477265772667726777268772697727077271772727727377274772757727677277772787727977280772817728277283772847728577286772877728877289772907729177292772937729477295772967729777298772997730077301773027730377304773057730677307773087730977310773117731277313773147731577316773177731877319773207732177322773237732477325773267732777328773297733077331773327733377334773357733677337773387733977340773417734277343773447734577346773477734877349773507735177352773537735477355773567735777358773597736077361773627736377364773657736677367773687736977370773717737277373773747737577376773777737877379773807738177382773837738477385773867738777388773897739077391773927739377394773957739677397773987739977400774017740277403774047740577406774077740877409774107741177412774137741477415774167741777418774197742077421774227742377424774257742677427774287742977430774317743277433774347743577436774377743877439774407744177442774437744477445774467744777448774497745077451774527745377454774557745677457774587745977460774617746277463774647746577466774677746877469774707747177472774737747477475774767747777478774797748077481774827748377484774857748677487774887748977490774917749277493774947749577496774977749877499775007750177502775037750477505775067750777508775097751077511775127751377514775157751677517775187751977520775217752277523775247752577526775277752877529775307753177532775337753477535775367753777538775397754077541775427754377544775457754677547775487754977550775517755277553775547755577556775577755877559775607756177562775637756477565775667756777568775697757077571775727757377574775757757677577775787757977580775817758277583775847758577586775877758877589775907759177592775937759477595775967759777598775997760077601776027760377604776057760677607776087760977610776117761277613776147761577616776177761877619776207762177622776237762477625776267762777628776297763077631776327763377634776357763677637776387763977640776417764277643776447764577646776477764877649776507765177652776537765477655776567765777658776597766077661776627766377664776657766677667776687766977670776717767277673776747767577676776777767877679776807768177682776837768477685776867768777688776897769077691776927769377694776957769677697776987769977700777017770277703777047770577706777077770877709777107771177712777137771477715777167771777718777197772077721777227772377724777257772677727777287772977730777317773277733777347773577736777377773877739777407774177742777437774477745777467774777748777497775077751777527775377754777557775677757777587775977760777617776277763777647776577766777677776877769777707777177772777737777477775777767777777778777797778077781777827778377784777857778677787777887778977790777917779277793777947779577796777977779877799778007780177802778037780477805778067780777808778097781077811778127781377814778157781677817778187781977820778217782277823778247782577826778277782877829778307783177832778337783477835778367783777838778397784077841778427784377844778457784677847778487784977850778517785277853778547785577856778577785877859778607786177862778637786477865778667786777868778697787077871778727787377874778757787677877778787787977880778817788277883778847788577886778877788877889778907789177892778937789477895778967789777898778997790077901779027790377904779057790677907779087790977910779117791277913779147791577916779177791877919779207792177922779237792477925779267792777928779297793077931779327793377934779357793677937779387793977940779417794277943779447794577946779477794877949779507795177952779537795477955779567795777958779597796077961779627796377964779657796677967779687796977970779717797277973779747797577976779777797877979779807798177982779837798477985779867798777988779897799077991779927799377994779957799677997779987799978000780017800278003780047800578006780077800878009780107801178012780137801478015780167801778018780197802078021780227802378024780257802678027780287802978030780317803278033780347803578036780377803878039780407804178042780437804478045780467804778048780497805078051780527805378054780557805678057780587805978060780617806278063780647806578066780677806878069780707807178072780737807478075780767807778078780797808078081780827808378084780857808678087780887808978090780917809278093780947809578096780977809878099781007810178102781037810478105781067810778108781097811078111781127811378114781157811678117781187811978120781217812278123781247812578126781277812878129781307813178132781337813478135781367813778138781397814078141781427814378144781457814678147781487814978150781517815278153781547815578156781577815878159781607816178162781637816478165781667816778168781697817078171781727817378174781757817678177781787817978180781817818278183781847818578186781877818878189781907819178192781937819478195781967819778198781997820078201782027820378204782057820678207782087820978210782117821278213782147821578216782177821878219782207822178222782237822478225782267822778228782297823078231782327823378234782357823678237782387823978240782417824278243782447824578246782477824878249782507825178252782537825478255782567825778258782597826078261782627826378264782657826678267782687826978270782717827278273782747827578276782777827878279782807828178282782837828478285782867828778288782897829078291782927829378294782957829678297782987829978300783017830278303783047830578306783077830878309783107831178312783137831478315783167831778318783197832078321783227832378324783257832678327783287832978330783317833278333783347833578336783377833878339783407834178342783437834478345783467834778348783497835078351783527835378354783557835678357783587835978360783617836278363783647836578366783677836878369783707837178372783737837478375783767837778378783797838078381783827838378384783857838678387783887838978390783917839278393783947839578396783977839878399784007840178402784037840478405784067840778408784097841078411784127841378414784157841678417784187841978420784217842278423784247842578426784277842878429784307843178432784337843478435784367843778438784397844078441784427844378444784457844678447784487844978450784517845278453784547845578456784577845878459784607846178462784637846478465784667846778468784697847078471784727847378474784757847678477784787847978480784817848278483784847848578486784877848878489784907849178492784937849478495784967849778498784997850078501785027850378504785057850678507785087850978510785117851278513785147851578516785177851878519785207852178522785237852478525785267852778528785297853078531785327853378534785357853678537785387853978540785417854278543785447854578546785477854878549785507855178552785537855478555785567855778558785597856078561785627856378564785657856678567785687856978570785717857278573785747857578576785777857878579785807858178582785837858478585785867858778588785897859078591785927859378594785957859678597785987859978600786017860278603786047860578606786077860878609786107861178612786137861478615786167861778618786197862078621786227862378624786257862678627786287862978630786317863278633786347863578636786377863878639786407864178642786437864478645786467864778648786497865078651786527865378654786557865678657786587865978660786617866278663786647866578666786677866878669786707867178672786737867478675786767867778678786797868078681786827868378684786857868678687786887868978690786917869278693786947869578696786977869878699787007870178702787037870478705787067870778708787097871078711787127871378714787157871678717787187871978720787217872278723787247872578726787277872878729787307873178732787337873478735787367873778738787397874078741787427874378744787457874678747787487874978750787517875278753787547875578756787577875878759787607876178762787637876478765787667876778768787697877078771787727877378774787757877678777787787877978780787817878278783787847878578786787877878878789787907879178792787937879478795787967879778798787997880078801788027880378804788057880678807788087880978810788117881278813788147881578816788177881878819788207882178822788237882478825788267882778828788297883078831788327883378834788357883678837788387883978840788417884278843788447884578846788477884878849788507885178852788537885478855788567885778858788597886078861788627886378864788657886678867788687886978870788717887278873788747887578876788777887878879788807888178882788837888478885788867888778888788897889078891788927889378894788957889678897788987889978900789017890278903789047890578906789077890878909789107891178912789137891478915789167891778918789197892078921789227892378924789257892678927789287892978930789317893278933789347893578936789377893878939789407894178942789437894478945789467894778948789497895078951789527895378954789557895678957789587895978960789617896278963789647896578966789677896878969789707897178972789737897478975789767897778978789797898078981789827898378984789857898678987789887898978990789917899278993789947899578996789977899878999790007900179002790037900479005790067900779008790097901079011790127901379014790157901679017790187901979020790217902279023790247902579026790277902879029790307903179032790337903479035790367903779038790397904079041790427904379044790457904679047790487904979050790517905279053790547905579056790577905879059790607906179062790637906479065790667906779068790697907079071790727907379074790757907679077790787907979080790817908279083790847908579086790877908879089790907909179092790937909479095790967909779098790997910079101791027910379104791057910679107791087910979110791117911279113791147911579116791177911879119791207912179122791237912479125791267912779128791297913079131791327913379134791357913679137791387913979140791417914279143791447914579146791477914879149791507915179152791537915479155791567915779158791597916079161791627916379164791657916679167791687916979170791717917279173791747917579176791777917879179791807918179182791837918479185791867918779188791897919079191791927919379194791957919679197791987919979200792017920279203792047920579206792077920879209792107921179212792137921479215792167921779218792197922079221792227922379224792257922679227792287922979230792317923279233792347923579236792377923879239792407924179242792437924479245792467924779248792497925079251792527925379254792557925679257792587925979260792617926279263792647926579266792677926879269792707927179272792737927479275792767927779278792797928079281792827928379284792857928679287792887928979290792917929279293792947929579296792977929879299793007930179302793037930479305793067930779308793097931079311793127931379314793157931679317793187931979320793217932279323793247932579326793277932879329793307933179332793337933479335793367933779338793397934079341793427934379344793457934679347793487934979350793517935279353793547935579356793577935879359793607936179362793637936479365793667936779368793697937079371793727937379374793757937679377793787937979380793817938279383793847938579386793877938879389793907939179392793937939479395793967939779398793997940079401794027940379404794057940679407794087940979410794117941279413794147941579416794177941879419794207942179422794237942479425794267942779428794297943079431794327943379434794357943679437794387943979440794417944279443794447944579446794477944879449794507945179452794537945479455794567945779458794597946079461794627946379464794657946679467794687946979470794717947279473794747947579476794777947879479794807948179482794837948479485794867948779488794897949079491794927949379494794957949679497794987949979500795017950279503795047950579506795077950879509795107951179512795137951479515795167951779518795197952079521795227952379524795257952679527795287952979530795317953279533795347953579536795377953879539795407954179542795437954479545795467954779548795497955079551795527955379554795557955679557795587955979560795617956279563795647956579566795677956879569795707957179572795737957479575795767957779578795797958079581795827958379584795857958679587795887958979590795917959279593795947959579596795977959879599796007960179602796037960479605796067960779608796097961079611796127961379614796157961679617796187961979620796217962279623796247962579626796277962879629796307963179632796337963479635796367963779638796397964079641796427964379644796457964679647796487964979650796517965279653796547965579656796577965879659796607966179662796637966479665796667966779668796697967079671796727967379674796757967679677796787967979680796817968279683796847968579686796877968879689796907969179692796937969479695796967969779698796997970079701797027970379704797057970679707797087970979710797117971279713797147971579716797177971879719797207972179722797237972479725797267972779728797297973079731797327973379734797357973679737797387973979740797417974279743797447974579746797477974879749797507975179752797537975479755797567975779758797597976079761797627976379764797657976679767797687976979770797717977279773797747977579776797777977879779797807978179782797837978479785797867978779788797897979079791797927979379794797957979679797797987979979800798017980279803798047980579806798077980879809798107981179812798137981479815798167981779818798197982079821798227982379824798257982679827798287982979830798317983279833798347983579836798377983879839798407984179842798437984479845798467984779848798497985079851798527985379854798557985679857798587985979860798617986279863798647986579866798677986879869798707987179872798737987479875798767987779878798797988079881798827988379884798857988679887798887988979890798917989279893798947989579896798977989879899799007990179902799037990479905799067990779908799097991079911799127991379914799157991679917799187991979920799217992279923799247992579926799277992879929799307993179932799337993479935799367993779938799397994079941799427994379944799457994679947799487994979950799517995279953799547995579956799577995879959799607996179962799637996479965799667996779968799697997079971799727997379974799757997679977799787997979980799817998279983799847998579986799877998879989799907999179992799937999479995799967999779998799998000080001800028000380004800058000680007800088000980010800118001280013800148001580016800178001880019800208002180022800238002480025800268002780028800298003080031800328003380034800358003680037800388003980040800418004280043800448004580046800478004880049800508005180052800538005480055800568005780058800598006080061800628006380064800658006680067800688006980070800718007280073800748007580076800778007880079800808008180082800838008480085800868008780088800898009080091800928009380094800958009680097800988009980100801018010280103801048010580106801078010880109801108011180112801138011480115801168011780118801198012080121801228012380124801258012680127801288012980130801318013280133801348013580136801378013880139801408014180142801438014480145801468014780148801498015080151801528015380154801558015680157801588015980160801618016280163801648016580166801678016880169801708017180172801738017480175801768017780178801798018080181801828018380184801858018680187801888018980190801918019280193801948019580196801978019880199802008020180202802038020480205802068020780208802098021080211802128021380214802158021680217802188021980220802218022280223802248022580226802278022880229802308023180232802338023480235802368023780238802398024080241802428024380244802458024680247802488024980250802518025280253802548025580256802578025880259802608026180262802638026480265802668026780268802698027080271802728027380274802758027680277802788027980280802818028280283802848028580286802878028880289802908029180292802938029480295802968029780298802998030080301803028030380304803058030680307803088030980310803118031280313803148031580316803178031880319803208032180322803238032480325803268032780328803298033080331803328033380334803358033680337803388033980340803418034280343803448034580346803478034880349803508035180352803538035480355803568035780358803598036080361803628036380364803658036680367803688036980370803718037280373803748037580376803778037880379803808038180382803838038480385803868038780388803898039080391803928039380394803958039680397803988039980400804018040280403804048040580406804078040880409804108041180412804138041480415804168041780418804198042080421804228042380424804258042680427804288042980430804318043280433804348043580436804378043880439804408044180442804438044480445804468044780448804498045080451804528045380454804558045680457804588045980460804618046280463804648046580466804678046880469804708047180472804738047480475804768047780478804798048080481804828048380484804858048680487804888048980490804918049280493804948049580496804978049880499805008050180502805038050480505805068050780508805098051080511805128051380514805158051680517805188051980520805218052280523805248052580526805278052880529805308053180532805338053480535805368053780538805398054080541805428054380544805458054680547805488054980550805518055280553805548055580556805578055880559805608056180562805638056480565805668056780568805698057080571805728057380574805758057680577805788057980580805818058280583805848058580586805878058880589805908059180592805938059480595805968059780598805998060080601806028060380604806058060680607806088060980610806118061280613806148061580616806178061880619806208062180622806238062480625806268062780628806298063080631806328063380634806358063680637806388063980640806418064280643806448064580646806478064880649806508065180652806538065480655806568065780658806598066080661806628066380664806658066680667806688066980670806718067280673806748067580676806778067880679806808068180682806838068480685806868068780688806898069080691806928069380694806958069680697806988069980700807018070280703807048070580706807078070880709807108071180712807138071480715807168071780718807198072080721807228072380724807258072680727807288072980730807318073280733807348073580736807378073880739807408074180742807438074480745807468074780748807498075080751807528075380754807558075680757807588075980760807618076280763807648076580766807678076880769807708077180772807738077480775807768077780778807798078080781807828078380784807858078680787807888078980790807918079280793807948079580796807978079880799808008080180802808038080480805808068080780808808098081080811808128081380814808158081680817808188081980820808218082280823808248082580826808278082880829808308083180832808338083480835808368083780838808398084080841808428084380844808458084680847808488084980850808518085280853808548085580856808578085880859808608086180862808638086480865808668086780868808698087080871808728087380874808758087680877808788087980880808818088280883808848088580886808878088880889808908089180892808938089480895808968089780898808998090080901809028090380904809058090680907809088090980910809118091280913809148091580916809178091880919809208092180922809238092480925809268092780928809298093080931809328093380934809358093680937809388093980940809418094280943809448094580946809478094880949809508095180952809538095480955809568095780958809598096080961809628096380964809658096680967809688096980970809718097280973809748097580976809778097880979809808098180982809838098480985809868098780988809898099080991809928099380994809958099680997809988099981000810018100281003810048100581006810078100881009810108101181012810138101481015810168101781018810198102081021810228102381024810258102681027810288102981030810318103281033810348103581036810378103881039810408104181042810438104481045810468104781048810498105081051810528105381054810558105681057810588105981060810618106281063810648106581066810678106881069810708107181072810738107481075810768107781078810798108081081810828108381084810858108681087810888108981090810918109281093810948109581096810978109881099811008110181102811038110481105811068110781108811098111081111811128111381114811158111681117811188111981120811218112281123811248112581126811278112881129811308113181132811338113481135811368113781138811398114081141811428114381144811458114681147811488114981150811518115281153811548115581156811578115881159811608116181162811638116481165811668116781168811698117081171811728117381174811758117681177811788117981180811818118281183811848118581186811878118881189811908119181192811938119481195811968119781198811998120081201812028120381204812058120681207812088120981210812118121281213812148121581216812178121881219812208122181222812238122481225812268122781228812298123081231812328123381234812358123681237812388123981240812418124281243812448124581246812478124881249812508125181252812538125481255812568125781258812598126081261812628126381264812658126681267812688126981270812718127281273812748127581276812778127881279812808128181282812838128481285812868128781288812898129081291812928129381294812958129681297812988129981300813018130281303813048130581306813078130881309813108131181312813138131481315813168131781318813198132081321813228132381324813258132681327813288132981330813318133281333813348133581336813378133881339813408134181342813438134481345813468134781348813498135081351813528135381354813558135681357813588135981360813618136281363813648136581366813678136881369813708137181372813738137481375813768137781378813798138081381813828138381384813858138681387813888138981390813918139281393813948139581396813978139881399814008140181402814038140481405814068140781408814098141081411814128141381414814158141681417814188141981420814218142281423814248142581426814278142881429814308143181432814338143481435814368143781438814398144081441814428144381444814458144681447814488144981450814518145281453814548145581456814578145881459814608146181462814638146481465814668146781468814698147081471814728147381474814758147681477814788147981480814818148281483814848148581486814878148881489814908149181492814938149481495814968149781498814998150081501815028150381504815058150681507815088150981510815118151281513815148151581516815178151881519815208152181522815238152481525815268152781528815298153081531815328153381534815358153681537815388153981540815418154281543815448154581546815478154881549815508155181552815538155481555815568155781558815598156081561815628156381564815658156681567815688156981570815718157281573815748157581576815778157881579815808158181582815838158481585815868158781588815898159081591815928159381594815958159681597815988159981600816018160281603816048160581606816078160881609816108161181612816138161481615816168161781618816198162081621816228162381624816258162681627816288162981630816318163281633816348163581636816378163881639816408164181642816438164481645816468164781648816498165081651816528165381654816558165681657816588165981660816618166281663816648166581666816678166881669816708167181672816738167481675816768167781678816798168081681816828168381684816858168681687816888168981690816918169281693816948169581696816978169881699817008170181702817038170481705817068170781708817098171081711817128171381714817158171681717817188171981720817218172281723817248172581726817278172881729817308173181732817338173481735817368173781738817398174081741817428174381744817458174681747817488174981750817518175281753817548175581756817578175881759817608176181762817638176481765817668176781768817698177081771817728177381774817758177681777817788177981780817818178281783817848178581786817878178881789817908179181792817938179481795817968179781798817998180081801818028180381804818058180681807818088180981810818118181281813818148181581816818178181881819818208182181822818238182481825818268182781828818298183081831818328183381834818358183681837818388183981840818418184281843818448184581846818478184881849818508185181852818538185481855818568185781858818598186081861818628186381864818658186681867818688186981870818718187281873818748187581876818778187881879818808188181882818838188481885818868188781888818898189081891818928189381894818958189681897818988189981900819018190281903819048190581906819078190881909819108191181912819138191481915819168191781918819198192081921819228192381924819258192681927819288192981930819318193281933819348193581936819378193881939819408194181942819438194481945819468194781948819498195081951819528195381954819558195681957819588195981960819618196281963819648196581966819678196881969819708197181972819738197481975819768197781978819798198081981819828198381984819858198681987819888198981990819918199281993819948199581996819978199881999820008200182002820038200482005820068200782008820098201082011820128201382014820158201682017820188201982020820218202282023820248202582026820278202882029820308203182032820338203482035820368203782038820398204082041820428204382044820458204682047820488204982050820518205282053820548205582056820578205882059820608206182062820638206482065820668206782068820698207082071820728207382074820758207682077820788207982080820818208282083820848208582086820878208882089820908209182092820938209482095820968209782098820998210082101821028210382104821058210682107821088210982110821118211282113821148211582116821178211882119821208212182122821238212482125821268212782128821298213082131821328213382134821358213682137821388213982140821418214282143821448214582146821478214882149821508215182152821538215482155821568215782158821598216082161821628216382164821658216682167821688216982170821718217282173821748217582176821778217882179821808218182182821838218482185821868218782188821898219082191821928219382194821958219682197821988219982200822018220282203822048220582206822078220882209822108221182212822138221482215822168221782218822198222082221822228222382224822258222682227822288222982230822318223282233822348223582236822378223882239822408224182242822438224482245822468224782248822498225082251822528225382254822558225682257822588225982260822618226282263822648226582266822678226882269822708227182272822738227482275822768227782278822798228082281822828228382284822858228682287822888228982290822918229282293822948229582296822978229882299823008230182302823038230482305823068230782308823098231082311823128231382314823158231682317823188231982320823218232282323823248232582326823278232882329823308233182332823338233482335823368233782338823398234082341823428234382344823458234682347823488234982350823518235282353823548235582356823578235882359823608236182362823638236482365823668236782368823698237082371823728237382374823758237682377823788237982380823818238282383823848238582386823878238882389823908239182392823938239482395823968239782398823998240082401824028240382404824058240682407824088240982410824118241282413824148241582416824178241882419824208242182422824238242482425824268242782428824298243082431824328243382434824358243682437824388243982440824418244282443824448244582446824478244882449824508245182452824538245482455824568245782458824598246082461824628246382464824658246682467824688246982470824718247282473824748247582476824778247882479824808248182482824838248482485824868248782488824898249082491824928249382494824958249682497824988249982500825018250282503825048250582506825078250882509825108251182512825138251482515825168251782518825198252082521825228252382524825258252682527825288252982530825318253282533825348253582536825378253882539825408254182542825438254482545825468254782548825498255082551825528255382554825558255682557825588255982560825618256282563825648256582566825678256882569825708257182572825738257482575825768257782578825798258082581825828258382584825858258682587825888258982590825918259282593825948259582596825978259882599826008260182602826038260482605826068260782608826098261082611826128261382614826158261682617826188261982620826218262282623826248262582626826278262882629826308263182632826338263482635826368263782638826398264082641826428264382644826458264682647826488264982650826518265282653826548265582656826578265882659826608266182662826638266482665826668266782668826698267082671826728267382674826758267682677826788267982680826818268282683826848268582686826878268882689826908269182692826938269482695826968269782698826998270082701827028270382704827058270682707827088270982710827118271282713827148271582716827178271882719827208272182722827238272482725827268272782728827298273082731827328273382734827358273682737827388273982740827418274282743827448274582746827478274882749827508275182752827538275482755827568275782758827598276082761827628276382764827658276682767827688276982770827718277282773827748277582776827778277882779827808278182782827838278482785827868278782788827898279082791827928279382794827958279682797827988279982800828018280282803828048280582806828078280882809828108281182812828138281482815828168281782818828198282082821828228282382824828258282682827828288282982830828318283282833828348283582836828378283882839828408284182842828438284482845828468284782848828498285082851828528285382854828558285682857828588285982860828618286282863828648286582866828678286882869828708287182872828738287482875828768287782878828798288082881828828288382884828858288682887828888288982890828918289282893828948289582896828978289882899829008290182902829038290482905829068290782908829098291082911829128291382914829158291682917829188291982920829218292282923829248292582926829278292882929829308293182932829338293482935829368293782938829398294082941829428294382944829458294682947829488294982950829518295282953829548295582956829578295882959829608296182962829638296482965829668296782968829698297082971829728297382974829758297682977829788297982980829818298282983829848298582986829878298882989829908299182992829938299482995829968299782998829998300083001830028300383004830058300683007830088300983010830118301283013830148301583016830178301883019830208302183022830238302483025830268302783028830298303083031830328303383034830358303683037830388303983040830418304283043830448304583046830478304883049830508305183052830538305483055830568305783058830598306083061830628306383064830658306683067830688306983070830718307283073830748307583076830778307883079830808308183082830838308483085830868308783088830898309083091830928309383094830958309683097830988309983100831018310283103831048310583106831078310883109831108311183112831138311483115831168311783118831198312083121831228312383124831258312683127831288312983130831318313283133831348313583136831378313883139831408314183142831438314483145831468314783148831498315083151831528315383154831558315683157831588315983160831618316283163831648316583166831678316883169831708317183172831738317483175831768317783178831798318083181831828318383184831858318683187831888318983190831918319283193831948319583196831978319883199832008320183202832038320483205832068320783208832098321083211832128321383214832158321683217832188321983220832218322283223832248322583226832278322883229832308323183232832338323483235832368323783238832398324083241832428324383244832458324683247832488324983250832518325283253832548325583256832578325883259832608326183262832638326483265832668326783268832698327083271832728327383274832758327683277832788327983280832818328283283832848328583286832878328883289832908329183292832938329483295832968329783298832998330083301833028330383304833058330683307833088330983310833118331283313833148331583316833178331883319833208332183322833238332483325833268332783328833298333083331833328333383334833358333683337833388333983340833418334283343833448334583346833478334883349833508335183352833538335483355833568335783358833598336083361833628336383364833658336683367833688336983370833718337283373833748337583376833778337883379833808338183382833838338483385833868338783388833898339083391833928339383394833958339683397833988339983400834018340283403834048340583406834078340883409834108341183412834138341483415834168341783418834198342083421834228342383424834258342683427834288342983430834318343283433834348343583436834378343883439834408344183442834438344483445834468344783448834498345083451834528345383454834558345683457834588345983460834618346283463834648346583466834678346883469834708347183472834738347483475834768347783478834798348083481834828348383484834858348683487834888348983490834918349283493834948349583496834978349883499835008350183502835038350483505835068350783508835098351083511835128351383514835158351683517835188351983520835218352283523835248352583526835278352883529835308353183532835338353483535835368353783538835398354083541835428354383544835458354683547835488354983550835518355283553835548355583556835578355883559835608356183562835638356483565835668356783568835698357083571835728357383574835758357683577835788357983580835818358283583835848358583586835878358883589835908359183592835938359483595835968359783598835998360083601836028360383604836058360683607836088360983610836118361283613836148361583616836178361883619836208362183622836238362483625836268362783628836298363083631836328363383634836358363683637836388363983640836418364283643836448364583646836478364883649836508365183652836538365483655836568365783658836598366083661836628366383664836658366683667836688366983670836718367283673836748367583676836778367883679836808368183682836838368483685836868368783688836898369083691836928369383694836958369683697836988369983700837018370283703837048370583706837078370883709837108371183712837138371483715837168371783718837198372083721837228372383724837258372683727837288372983730837318373283733837348373583736837378373883739837408374183742837438374483745837468374783748837498375083751837528375383754837558375683757837588375983760837618376283763837648376583766837678376883769837708377183772837738377483775837768377783778837798378083781837828378383784837858378683787837888378983790837918379283793837948379583796837978379883799838008380183802838038380483805838068380783808838098381083811838128381383814838158381683817838188381983820838218382283823838248382583826838278382883829838308383183832838338383483835838368383783838838398384083841838428384383844838458384683847838488384983850838518385283853838548385583856838578385883859838608386183862838638386483865838668386783868838698387083871838728387383874838758387683877838788387983880838818388283883838848388583886838878388883889838908389183892838938389483895838968389783898838998390083901839028390383904839058390683907839088390983910839118391283913839148391583916839178391883919839208392183922839238392483925839268392783928839298393083931839328393383934839358393683937839388393983940839418394283943839448394583946839478394883949839508395183952839538395483955839568395783958839598396083961839628396383964839658396683967839688396983970839718397283973839748397583976839778397883979839808398183982839838398483985839868398783988839898399083991839928399383994839958399683997839988399984000840018400284003840048400584006840078400884009840108401184012840138401484015840168401784018840198402084021840228402384024840258402684027840288402984030840318403284033840348403584036840378403884039840408404184042840438404484045840468404784048840498405084051840528405384054840558405684057840588405984060840618406284063840648406584066840678406884069840708407184072840738407484075840768407784078840798408084081840828408384084840858408684087840888408984090840918409284093840948409584096840978409884099841008410184102841038410484105841068410784108841098411084111841128411384114841158411684117841188411984120841218412284123841248412584126841278412884129841308413184132841338413484135841368413784138841398414084141841428414384144841458414684147841488414984150841518415284153841548415584156841578415884159841608416184162841638416484165841668416784168841698417084171841728417384174841758417684177841788417984180841818418284183841848418584186841878418884189841908419184192841938419484195841968419784198841998420084201842028420384204842058420684207842088420984210842118421284213842148421584216842178421884219842208422184222842238422484225842268422784228842298423084231842328423384234842358423684237842388423984240842418424284243842448424584246842478424884249842508425184252842538425484255842568425784258842598426084261842628426384264842658426684267842688426984270842718427284273842748427584276842778427884279842808428184282842838428484285842868428784288842898429084291842928429384294842958429684297842988429984300843018430284303843048430584306843078430884309843108431184312843138431484315843168431784318843198432084321843228432384324843258432684327843288432984330843318433284333843348433584336843378433884339843408434184342843438434484345843468434784348843498435084351843528435384354843558435684357843588435984360843618436284363843648436584366843678436884369843708437184372843738437484375843768437784378843798438084381843828438384384843858438684387843888438984390843918439284393843948439584396843978439884399844008440184402844038440484405844068440784408844098441084411844128441384414844158441684417844188441984420844218442284423844248442584426844278442884429844308443184432844338443484435844368443784438844398444084441844428444384444844458444684447844488444984450844518445284453844548445584456844578445884459844608446184462844638446484465844668446784468844698447084471844728447384474844758447684477844788447984480844818448284483844848448584486844878448884489844908449184492844938449484495844968449784498844998450084501845028450384504845058450684507845088450984510845118451284513845148451584516845178451884519845208452184522845238452484525845268452784528845298453084531845328453384534845358453684537845388453984540845418454284543845448454584546845478454884549845508455184552845538455484555845568455784558845598456084561845628456384564845658456684567845688456984570845718457284573845748457584576845778457884579845808458184582845838458484585845868458784588845898459084591845928459384594845958459684597845988459984600846018460284603846048460584606846078460884609846108461184612846138461484615846168461784618846198462084621846228462384624846258462684627846288462984630846318463284633846348463584636846378463884639846408464184642846438464484645846468464784648846498465084651846528465384654846558465684657846588465984660846618466284663846648466584666846678466884669846708467184672846738467484675846768467784678846798468084681846828468384684846858468684687846888468984690846918469284693846948469584696846978469884699847008470184702847038470484705847068470784708847098471084711847128471384714847158471684717847188471984720847218472284723847248472584726847278472884729847308473184732847338473484735847368473784738847398474084741847428474384744847458474684747847488474984750847518475284753847548475584756847578475884759847608476184762847638476484765847668476784768847698477084771847728477384774847758477684777847788477984780847818478284783847848478584786847878478884789847908479184792847938479484795847968479784798847998480084801848028480384804848058480684807848088480984810848118481284813848148481584816848178481884819848208482184822848238482484825848268482784828848298483084831848328483384834848358483684837848388483984840848418484284843848448484584846848478484884849848508485184852848538485484855848568485784858848598486084861848628486384864848658486684867848688486984870848718487284873848748487584876848778487884879848808488184882848838488484885848868488784888848898489084891848928489384894848958489684897848988489984900849018490284903849048490584906849078490884909849108491184912849138491484915849168491784918849198492084921849228492384924849258492684927849288492984930849318493284933849348493584936849378493884939849408494184942849438494484945849468494784948849498495084951849528495384954849558495684957849588495984960849618496284963849648496584966849678496884969849708497184972849738497484975849768497784978849798498084981849828498384984849858498684987849888498984990849918499284993849948499584996849978499884999850008500185002850038500485005850068500785008850098501085011850128501385014850158501685017850188501985020850218502285023850248502585026850278502885029850308503185032850338503485035850368503785038850398504085041850428504385044850458504685047850488504985050850518505285053850548505585056850578505885059850608506185062850638506485065850668506785068850698507085071850728507385074850758507685077850788507985080850818508285083850848508585086850878508885089850908509185092850938509485095850968509785098850998510085101851028510385104851058510685107851088510985110851118511285113851148511585116851178511885119851208512185122851238512485125851268512785128851298513085131851328513385134851358513685137851388513985140851418514285143851448514585146851478514885149851508515185152851538515485155851568515785158851598516085161851628516385164851658516685167851688516985170851718517285173851748517585176851778517885179851808518185182851838518485185851868518785188851898519085191851928519385194851958519685197851988519985200852018520285203852048520585206852078520885209852108521185212852138521485215852168521785218852198522085221852228522385224852258522685227852288522985230852318523285233852348523585236852378523885239852408524185242852438524485245852468524785248852498525085251852528525385254852558525685257852588525985260852618526285263852648526585266852678526885269852708527185272852738527485275852768527785278852798528085281852828528385284852858528685287852888528985290852918529285293852948529585296852978529885299853008530185302853038530485305853068530785308853098531085311853128531385314853158531685317853188531985320853218532285323853248532585326853278532885329853308533185332853338533485335853368533785338853398534085341853428534385344853458534685347853488534985350853518535285353853548535585356853578535885359853608536185362853638536485365853668536785368853698537085371853728537385374853758537685377853788537985380853818538285383853848538585386853878538885389853908539185392853938539485395853968539785398853998540085401854028540385404854058540685407854088540985410854118541285413854148541585416854178541885419854208542185422854238542485425854268542785428854298543085431854328543385434854358543685437854388543985440854418544285443854448544585446854478544885449854508545185452854538545485455854568545785458854598546085461854628546385464854658546685467854688546985470854718547285473854748547585476854778547885479854808548185482854838548485485854868548785488854898549085491854928549385494854958549685497854988549985500855018550285503855048550585506855078550885509855108551185512855138551485515855168551785518855198552085521855228552385524855258552685527855288552985530855318553285533855348553585536855378553885539855408554185542855438554485545855468554785548855498555085551855528555385554855558555685557855588555985560855618556285563855648556585566855678556885569855708557185572855738557485575855768557785578855798558085581855828558385584855858558685587855888558985590855918559285593855948559585596855978559885599856008560185602856038560485605856068560785608856098561085611856128561385614856158561685617856188561985620856218562285623856248562585626856278562885629856308563185632856338563485635856368563785638856398564085641856428564385644856458564685647856488564985650856518565285653856548565585656856578565885659856608566185662856638566485665856668566785668856698567085671856728567385674856758567685677856788567985680856818568285683856848568585686856878568885689856908569185692856938569485695856968569785698856998570085701857028570385704857058570685707857088570985710857118571285713857148571585716857178571885719857208572185722857238572485725857268572785728857298573085731857328573385734857358573685737857388573985740857418574285743857448574585746857478574885749857508575185752857538575485755857568575785758857598576085761857628576385764857658576685767857688576985770857718577285773857748577585776857778577885779857808578185782857838578485785857868578785788857898579085791857928579385794857958579685797857988579985800858018580285803858048580585806858078580885809858108581185812858138581485815858168581785818858198582085821858228582385824858258582685827858288582985830858318583285833858348583585836858378583885839858408584185842858438584485845858468584785848858498585085851858528585385854858558585685857858588585985860858618586285863858648586585866858678586885869858708587185872858738587485875858768587785878858798588085881858828588385884858858588685887858888588985890858918589285893858948589585896858978589885899859008590185902859038590485905859068590785908859098591085911859128591385914859158591685917859188591985920859218592285923859248592585926859278592885929859308593185932859338593485935859368593785938859398594085941859428594385944859458594685947859488594985950859518595285953859548595585956859578595885959859608596185962859638596485965859668596785968859698597085971859728597385974859758597685977859788597985980859818598285983859848598585986859878598885989859908599185992859938599485995859968599785998859998600086001860028600386004860058600686007860088600986010860118601286013860148601586016860178601886019860208602186022860238602486025860268602786028860298603086031860328603386034860358603686037860388603986040860418604286043860448604586046860478604886049860508605186052860538605486055860568605786058860598606086061860628606386064860658606686067860688606986070860718607286073860748607586076860778607886079860808608186082860838608486085860868608786088860898609086091860928609386094860958609686097860988609986100861018610286103861048610586106861078610886109861108611186112861138611486115861168611786118861198612086121861228612386124861258612686127861288612986130861318613286133861348613586136861378613886139861408614186142861438614486145861468614786148861498615086151861528615386154861558615686157861588615986160861618616286163861648616586166861678616886169861708617186172861738617486175861768617786178861798618086181861828618386184861858618686187861888618986190861918619286193861948619586196861978619886199862008620186202862038620486205862068620786208862098621086211862128621386214862158621686217862188621986220862218622286223862248622586226862278622886229862308623186232862338623486235862368623786238862398624086241862428624386244862458624686247862488624986250862518625286253862548625586256862578625886259862608626186262862638626486265862668626786268862698627086271862728627386274862758627686277862788627986280862818628286283862848628586286862878628886289862908629186292862938629486295862968629786298862998630086301863028630386304863058630686307863088630986310863118631286313863148631586316863178631886319863208632186322863238632486325863268632786328863298633086331863328633386334863358633686337863388633986340863418634286343863448634586346863478634886349863508635186352863538635486355863568635786358863598636086361863628636386364863658636686367863688636986370863718637286373863748637586376863778637886379863808638186382863838638486385863868638786388863898639086391863928639386394863958639686397863988639986400864018640286403864048640586406864078640886409864108641186412864138641486415864168641786418864198642086421864228642386424864258642686427864288642986430864318643286433864348643586436864378643886439864408644186442864438644486445864468644786448864498645086451864528645386454864558645686457864588645986460864618646286463864648646586466864678646886469864708647186472864738647486475864768647786478864798648086481864828648386484864858648686487864888648986490864918649286493864948649586496864978649886499865008650186502865038650486505865068650786508865098651086511865128651386514865158651686517865188651986520865218652286523865248652586526865278652886529865308653186532865338653486535865368653786538865398654086541865428654386544865458654686547865488654986550865518655286553865548655586556865578655886559865608656186562865638656486565865668656786568865698657086571865728657386574865758657686577865788657986580865818658286583865848658586586865878658886589865908659186592865938659486595865968659786598865998660086601866028660386604866058660686607866088660986610866118661286613866148661586616866178661886619866208662186622866238662486625866268662786628866298663086631866328663386634866358663686637866388663986640866418664286643866448664586646866478664886649866508665186652866538665486655866568665786658866598666086661866628666386664866658666686667866688666986670866718667286673866748667586676866778667886679866808668186682866838668486685866868668786688866898669086691866928669386694866958669686697866988669986700867018670286703867048670586706867078670886709867108671186712867138671486715867168671786718867198672086721867228672386724867258672686727867288672986730867318673286733867348673586736867378673886739867408674186742867438674486745867468674786748867498675086751867528675386754867558675686757867588675986760867618676286763867648676586766867678676886769867708677186772867738677486775867768677786778867798678086781867828678386784867858678686787867888678986790867918679286793867948679586796867978679886799868008680186802868038680486805868068680786808868098681086811868128681386814868158681686817868188681986820868218682286823868248682586826868278682886829868308683186832868338683486835868368683786838868398684086841868428684386844868458684686847868488684986850868518685286853868548685586856868578685886859868608686186862868638686486865868668686786868868698687086871868728687386874868758687686877868788687986880868818688286883868848688586886868878688886889868908689186892868938689486895868968689786898868998690086901869028690386904869058690686907869088690986910869118691286913869148691586916869178691886919869208692186922869238692486925869268692786928869298693086931869328693386934869358693686937869388693986940869418694286943869448694586946869478694886949869508695186952869538695486955869568695786958869598696086961869628696386964869658696686967869688696986970869718697286973869748697586976869778697886979869808698186982869838698486985869868698786988869898699086991869928699386994869958699686997869988699987000870018700287003870048700587006870078700887009870108701187012870138701487015870168701787018870198702087021870228702387024870258702687027870288702987030870318703287033870348703587036870378703887039870408704187042870438704487045870468704787048870498705087051870528705387054870558705687057870588705987060870618706287063870648706587066870678706887069870708707187072870738707487075870768707787078870798708087081870828708387084870858708687087870888708987090870918709287093870948709587096870978709887099871008710187102871038710487105871068710787108871098711087111871128711387114871158711687117871188711987120871218712287123871248712587126871278712887129871308713187132871338713487135871368713787138871398714087141871428714387144871458714687147871488714987150871518715287153871548715587156871578715887159871608716187162871638716487165871668716787168871698717087171871728717387174871758717687177871788717987180871818718287183871848718587186871878718887189871908719187192871938719487195871968719787198871998720087201872028720387204872058720687207872088720987210872118721287213872148721587216872178721887219872208722187222872238722487225872268722787228872298723087231872328723387234872358723687237872388723987240872418724287243872448724587246872478724887249872508725187252872538725487255872568725787258872598726087261872628726387264872658726687267872688726987270872718727287273872748727587276872778727887279872808728187282872838728487285872868728787288872898729087291872928729387294872958729687297872988729987300873018730287303873048730587306873078730887309873108731187312873138731487315873168731787318873198732087321873228732387324873258732687327873288732987330873318733287333873348733587336873378733887339873408734187342873438734487345873468734787348873498735087351873528735387354873558735687357873588735987360873618736287363873648736587366873678736887369873708737187372873738737487375873768737787378873798738087381873828738387384873858738687387873888738987390873918739287393873948739587396873978739887399874008740187402874038740487405874068740787408874098741087411874128741387414874158741687417874188741987420874218742287423874248742587426874278742887429874308743187432874338743487435874368743787438874398744087441874428744387444874458744687447874488744987450874518745287453874548745587456874578745887459874608746187462874638746487465874668746787468874698747087471874728747387474874758747687477874788747987480874818748287483874848748587486874878748887489874908749187492874938749487495874968749787498874998750087501875028750387504875058750687507875088750987510875118751287513875148751587516875178751887519875208752187522875238752487525875268752787528875298753087531875328753387534875358753687537875388753987540875418754287543875448754587546875478754887549875508755187552875538755487555875568755787558875598756087561875628756387564875658756687567875688756987570875718757287573875748757587576875778757887579875808758187582875838758487585875868758787588875898759087591875928759387594875958759687597875988759987600876018760287603876048760587606876078760887609876108761187612876138761487615876168761787618876198762087621876228762387624876258762687627876288762987630876318763287633876348763587636876378763887639876408764187642876438764487645876468764787648876498765087651876528765387654876558765687657876588765987660876618766287663876648766587666876678766887669876708767187672876738767487675876768767787678876798768087681876828768387684876858768687687876888768987690876918769287693876948769587696876978769887699877008770187702877038770487705877068770787708877098771087711877128771387714877158771687717877188771987720877218772287723877248772587726877278772887729877308773187732877338773487735877368773787738877398774087741877428774387744877458774687747877488774987750877518775287753877548775587756877578775887759877608776187762877638776487765877668776787768877698777087771877728777387774877758777687777877788777987780877818778287783877848778587786877878778887789877908779187792877938779487795877968779787798877998780087801878028780387804878058780687807878088780987810878118781287813878148781587816878178781887819878208782187822878238782487825878268782787828878298783087831878328783387834878358783687837878388783987840878418784287843878448784587846878478784887849878508785187852878538785487855878568785787858878598786087861878628786387864878658786687867878688786987870878718787287873878748787587876878778787887879878808788187882878838788487885878868788787888878898789087891878928789387894878958789687897878988789987900879018790287903879048790587906879078790887909879108791187912879138791487915879168791787918879198792087921879228792387924879258792687927879288792987930879318793287933879348793587936879378793887939879408794187942879438794487945879468794787948879498795087951879528795387954879558795687957879588795987960879618796287963879648796587966879678796887969879708797187972879738797487975879768797787978879798798087981879828798387984879858798687987879888798987990879918799287993879948799587996879978799887999880008800188002880038800488005880068800788008880098801088011880128801388014880158801688017880188801988020880218802288023880248802588026880278802888029880308803188032880338803488035880368803788038880398804088041880428804388044880458804688047880488804988050880518805288053880548805588056880578805888059880608806188062880638806488065880668806788068880698807088071880728807388074880758807688077880788807988080880818808288083880848808588086880878808888089880908809188092880938809488095880968809788098880998810088101881028810388104881058810688107881088810988110881118811288113881148811588116881178811888119881208812188122881238812488125881268812788128881298813088131881328813388134881358813688137881388813988140881418814288143881448814588146881478814888149881508815188152881538815488155881568815788158881598816088161881628816388164881658816688167881688816988170881718817288173881748817588176881778817888179881808818188182881838818488185881868818788188881898819088191881928819388194881958819688197881988819988200882018820288203882048820588206882078820888209882108821188212882138821488215882168821788218882198822088221882228822388224882258822688227882288822988230882318823288233882348823588236882378823888239882408824188242882438824488245882468824788248882498825088251882528825388254882558825688257882588825988260882618826288263882648826588266882678826888269882708827188272882738827488275882768827788278882798828088281882828828388284882858828688287882888828988290882918829288293882948829588296882978829888299883008830188302883038830488305883068830788308883098831088311883128831388314883158831688317883188831988320883218832288323883248832588326883278832888329883308833188332883338833488335883368833788338883398834088341883428834388344883458834688347883488834988350883518835288353883548835588356883578835888359883608836188362883638836488365883668836788368883698837088371883728837388374883758837688377883788837988380883818838288383883848838588386883878838888389883908839188392883938839488395883968839788398883998840088401884028840388404884058840688407884088840988410884118841288413884148841588416884178841888419884208842188422884238842488425884268842788428884298843088431884328843388434884358843688437884388843988440884418844288443884448844588446884478844888449884508845188452884538845488455884568845788458884598846088461884628846388464884658846688467884688846988470884718847288473884748847588476884778847888479884808848188482884838848488485884868848788488884898849088491884928849388494884958849688497884988849988500885018850288503885048850588506885078850888509885108851188512885138851488515885168851788518885198852088521885228852388524885258852688527885288852988530885318853288533885348853588536885378853888539885408854188542885438854488545885468854788548885498855088551885528855388554885558855688557885588855988560885618856288563885648856588566885678856888569885708857188572885738857488575885768857788578885798858088581885828858388584885858858688587885888858988590885918859288593885948859588596885978859888599886008860188602886038860488605886068860788608886098861088611886128861388614886158861688617886188861988620886218862288623886248862588626886278862888629886308863188632886338863488635886368863788638886398864088641886428864388644886458864688647886488864988650886518865288653886548865588656886578865888659886608866188662886638866488665886668866788668886698867088671886728867388674886758867688677886788867988680886818868288683886848868588686886878868888689886908869188692886938869488695886968869788698886998870088701887028870388704887058870688707887088870988710887118871288713887148871588716887178871888719887208872188722887238872488725887268872788728887298873088731887328873388734887358873688737887388873988740887418874288743887448874588746887478874888749887508875188752887538875488755887568875788758887598876088761887628876388764887658876688767887688876988770887718877288773887748877588776887778877888779887808878188782887838878488785887868878788788887898879088791887928879388794887958879688797887988879988800888018880288803888048880588806888078880888809888108881188812888138881488815888168881788818888198882088821888228882388824888258882688827888288882988830888318883288833888348883588836888378883888839888408884188842888438884488845888468884788848888498885088851888528885388854888558885688857888588885988860888618886288863888648886588866888678886888869888708887188872888738887488875888768887788878888798888088881888828888388884888858888688887888888888988890888918889288893888948889588896888978889888899889008890188902889038890488905889068890788908889098891088911889128891388914889158891688917889188891988920889218892288923889248892588926889278892888929889308893188932889338893488935889368893788938889398894088941889428894388944889458894688947889488894988950889518895288953889548895588956889578895888959889608896188962889638896488965889668896788968889698897088971889728897388974889758897688977889788897988980889818898288983889848898588986889878898888989889908899188992889938899488995889968899788998889998900089001890028900389004890058900689007890088900989010890118901289013890148901589016890178901889019890208902189022890238902489025890268902789028890298903089031890328903389034890358903689037890388903989040890418904289043890448904589046890478904889049890508905189052890538905489055890568905789058890598906089061890628906389064890658906689067890688906989070890718907289073890748907589076890778907889079890808908189082890838908489085890868908789088890898909089091890928909389094890958909689097890988909989100891018910289103891048910589106891078910889109891108911189112891138911489115891168911789118891198912089121891228912389124891258912689127891288912989130891318913289133891348913589136891378913889139891408914189142891438914489145891468914789148891498915089151891528915389154891558915689157891588915989160891618916289163891648916589166891678916889169891708917189172891738917489175891768917789178891798918089181891828918389184891858918689187891888918989190891918919289193891948919589196891978919889199892008920189202892038920489205892068920789208892098921089211892128921389214892158921689217892188921989220892218922289223892248922589226892278922889229892308923189232892338923489235892368923789238892398924089241892428924389244892458924689247892488924989250892518925289253892548925589256892578925889259892608926189262892638926489265892668926789268892698927089271892728927389274892758927689277892788927989280892818928289283892848928589286892878928889289892908929189292892938929489295892968929789298892998930089301893028930389304893058930689307893088930989310893118931289313893148931589316893178931889319893208932189322893238932489325893268932789328893298933089331893328933389334893358933689337893388933989340893418934289343893448934589346893478934889349893508935189352893538935489355893568935789358893598936089361893628936389364893658936689367893688936989370893718937289373893748937589376893778937889379893808938189382893838938489385893868938789388893898939089391893928939389394893958939689397893988939989400894018940289403894048940589406894078940889409894108941189412894138941489415894168941789418894198942089421894228942389424894258942689427894288942989430894318943289433894348943589436894378943889439894408944189442894438944489445894468944789448894498945089451894528945389454894558945689457894588945989460894618946289463894648946589466894678946889469894708947189472894738947489475894768947789478894798948089481894828948389484894858948689487894888948989490894918949289493894948949589496894978949889499895008950189502895038950489505895068950789508895098951089511895128951389514895158951689517895188951989520895218952289523895248952589526895278952889529895308953189532895338953489535895368953789538895398954089541895428954389544895458954689547895488954989550895518955289553895548955589556895578955889559895608956189562895638956489565895668956789568895698957089571895728957389574895758957689577895788957989580895818958289583895848958589586895878958889589895908959189592895938959489595895968959789598895998960089601896028960389604896058960689607896088960989610896118961289613896148961589616896178961889619896208962189622896238962489625896268962789628896298963089631896328963389634896358963689637896388963989640896418964289643896448964589646896478964889649896508965189652896538965489655896568965789658896598966089661896628966389664896658966689667896688966989670896718967289673896748967589676896778967889679896808968189682896838968489685896868968789688896898969089691896928969389694896958969689697896988969989700897018970289703897048970589706897078970889709897108971189712897138971489715897168971789718897198972089721897228972389724897258972689727897288972989730897318973289733897348973589736897378973889739897408974189742897438974489745897468974789748897498975089751897528975389754897558975689757897588975989760897618976289763897648976589766897678976889769897708977189772897738977489775897768977789778897798978089781897828978389784897858978689787897888978989790897918979289793897948979589796897978979889799898008980189802898038980489805898068980789808898098981089811898128981389814898158981689817898188981989820898218982289823898248982589826898278982889829898308983189832898338983489835898368983789838898398984089841898428984389844898458984689847898488984989850898518985289853898548985589856898578985889859898608986189862898638986489865898668986789868898698987089871898728987389874898758987689877898788987989880898818988289883898848988589886898878988889889898908989189892898938989489895898968989789898898998990089901899028990389904899058990689907899088990989910899118991289913899148991589916899178991889919899208992189922899238992489925899268992789928899298993089931899328993389934899358993689937899388993989940899418994289943899448994589946899478994889949899508995189952899538995489955899568995789958899598996089961899628996389964899658996689967899688996989970899718997289973899748997589976899778997889979899808998189982899838998489985899868998789988899898999089991899928999389994899958999689997899988999990000900019000290003900049000590006900079000890009900109001190012900139001490015900169001790018900199002090021900229002390024900259002690027900289002990030900319003290033900349003590036900379003890039900409004190042900439004490045900469004790048900499005090051900529005390054900559005690057900589005990060900619006290063900649006590066900679006890069900709007190072900739007490075900769007790078900799008090081900829008390084900859008690087900889008990090900919009290093900949009590096900979009890099901009010190102901039010490105901069010790108901099011090111901129011390114901159011690117901189011990120901219012290123901249012590126901279012890129901309013190132901339013490135901369013790138901399014090141901429014390144901459014690147901489014990150901519015290153901549015590156901579015890159901609016190162901639016490165901669016790168901699017090171901729017390174901759017690177901789017990180901819018290183901849018590186901879018890189901909019190192901939019490195901969019790198901999020090201902029020390204902059020690207902089020990210902119021290213902149021590216902179021890219902209022190222902239022490225902269022790228902299023090231902329023390234902359023690237902389023990240902419024290243902449024590246902479024890249902509025190252902539025490255902569025790258902599026090261902629026390264902659026690267902689026990270902719027290273902749027590276902779027890279902809028190282902839028490285902869028790288902899029090291902929029390294902959029690297902989029990300903019030290303903049030590306903079030890309903109031190312903139031490315903169031790318903199032090321903229032390324903259032690327903289032990330903319033290333903349033590336903379033890339903409034190342903439034490345903469034790348903499035090351903529035390354903559035690357903589035990360903619036290363903649036590366903679036890369903709037190372903739037490375903769037790378903799038090381903829038390384903859038690387903889038990390903919039290393903949039590396903979039890399904009040190402904039040490405904069040790408904099041090411904129041390414904159041690417904189041990420904219042290423904249042590426904279042890429904309043190432904339043490435904369043790438904399044090441904429044390444904459044690447904489044990450904519045290453904549045590456904579045890459904609046190462904639046490465904669046790468904699047090471904729047390474904759047690477904789047990480904819048290483904849048590486904879048890489904909049190492904939049490495904969049790498904999050090501905029050390504905059050690507905089050990510905119051290513905149051590516905179051890519905209052190522905239052490525905269052790528905299053090531905329053390534905359053690537905389053990540905419054290543905449054590546905479054890549905509055190552905539055490555905569055790558905599056090561905629056390564905659056690567905689056990570905719057290573905749057590576905779057890579905809058190582905839058490585905869058790588905899059090591905929059390594905959059690597905989059990600906019060290603906049060590606906079060890609906109061190612906139061490615906169061790618906199062090621906229062390624906259062690627906289062990630906319063290633906349063590636906379063890639906409064190642906439064490645906469064790648906499065090651906529065390654906559065690657906589065990660906619066290663906649066590666906679066890669906709067190672906739067490675906769067790678906799068090681906829068390684906859068690687906889068990690906919069290693906949069590696906979069890699907009070190702907039070490705907069070790708907099071090711907129071390714907159071690717907189071990720907219072290723907249072590726907279072890729907309073190732907339073490735907369073790738907399074090741907429074390744907459074690747907489074990750907519075290753907549075590756907579075890759907609076190762907639076490765907669076790768907699077090771907729077390774907759077690777907789077990780907819078290783907849078590786907879078890789907909079190792907939079490795907969079790798907999080090801908029080390804908059080690807908089080990810908119081290813908149081590816908179081890819908209082190822908239082490825908269082790828908299083090831908329083390834908359083690837908389083990840908419084290843908449084590846908479084890849908509085190852908539085490855908569085790858908599086090861908629086390864908659086690867908689086990870908719087290873908749087590876908779087890879908809088190882908839088490885908869088790888908899089090891908929089390894908959089690897908989089990900909019090290903909049090590906909079090890909909109091190912909139091490915909169091790918909199092090921909229092390924909259092690927909289092990930909319093290933909349093590936909379093890939909409094190942909439094490945909469094790948909499095090951909529095390954909559095690957909589095990960909619096290963909649096590966909679096890969909709097190972909739097490975909769097790978909799098090981909829098390984909859098690987909889098990990909919099290993909949099590996909979099890999910009100191002910039100491005910069100791008910099101091011910129101391014910159101691017910189101991020910219102291023910249102591026910279102891029910309103191032910339103491035910369103791038910399104091041910429104391044910459104691047910489104991050910519105291053910549105591056910579105891059910609106191062910639106491065910669106791068910699107091071910729107391074910759107691077910789107991080910819108291083910849108591086910879108891089910909109191092910939109491095910969109791098910999110091101911029110391104911059110691107911089110991110911119111291113911149111591116911179111891119911209112191122911239112491125911269112791128911299113091131911329113391134911359113691137911389113991140911419114291143911449114591146911479114891149911509115191152911539115491155911569115791158911599116091161911629116391164911659116691167911689116991170911719117291173911749117591176911779117891179911809118191182911839118491185911869118791188911899119091191911929119391194911959119691197911989119991200912019120291203912049120591206912079120891209912109121191212912139121491215912169121791218912199122091221912229122391224912259122691227912289122991230912319123291233912349123591236912379123891239912409124191242912439124491245912469124791248912499125091251912529125391254912559125691257912589125991260912619126291263912649126591266912679126891269912709127191272912739127491275912769127791278912799128091281912829128391284912859128691287912889128991290912919129291293912949129591296912979129891299913009130191302913039130491305913069130791308913099131091311913129131391314913159131691317913189131991320913219132291323913249132591326913279132891329913309133191332913339133491335913369133791338913399134091341913429134391344913459134691347913489134991350913519135291353913549135591356913579135891359913609136191362913639136491365913669136791368913699137091371913729137391374913759137691377913789137991380913819138291383913849138591386913879138891389913909139191392913939139491395913969139791398913999140091401914029140391404914059140691407914089140991410914119141291413914149141591416914179141891419914209142191422914239142491425914269142791428914299143091431914329143391434914359143691437914389143991440914419144291443914449144591446914479144891449914509145191452914539145491455914569145791458914599146091461914629146391464914659146691467914689146991470914719147291473914749147591476914779147891479914809148191482914839148491485914869148791488914899149091491914929149391494914959149691497914989149991500915019150291503915049150591506915079150891509915109151191512915139151491515915169151791518915199152091521915229152391524915259152691527915289152991530915319153291533915349153591536915379153891539915409154191542915439154491545915469154791548915499155091551915529155391554915559155691557915589155991560915619156291563915649156591566915679156891569915709157191572915739157491575915769157791578915799158091581915829158391584915859158691587915889158991590915919159291593915949159591596915979159891599916009160191602916039160491605916069160791608916099161091611916129161391614916159161691617916189161991620916219162291623916249162591626916279162891629916309163191632916339163491635916369163791638916399164091641916429164391644916459164691647916489164991650916519165291653916549165591656916579165891659916609166191662916639166491665916669166791668916699167091671916729167391674916759167691677916789167991680916819168291683916849168591686916879168891689916909169191692916939169491695916969169791698916999170091701917029170391704917059170691707917089170991710917119171291713917149171591716917179171891719917209172191722917239172491725917269172791728917299173091731917329173391734917359173691737917389173991740917419174291743917449174591746917479174891749917509175191752917539175491755917569175791758917599176091761917629176391764917659176691767917689176991770917719177291773917749177591776917779177891779917809178191782917839178491785917869178791788917899179091791917929179391794917959179691797917989179991800918019180291803918049180591806918079180891809918109181191812918139181491815918169181791818918199182091821918229182391824918259182691827918289182991830918319183291833918349183591836918379183891839918409184191842918439184491845918469184791848918499185091851918529185391854918559185691857918589185991860918619186291863918649186591866918679186891869918709187191872918739187491875918769187791878918799188091881918829188391884918859188691887918889188991890918919189291893918949189591896918979189891899919009190191902919039190491905919069190791908919099191091911919129191391914919159191691917919189191991920919219192291923919249192591926919279192891929919309193191932919339193491935919369193791938919399194091941919429194391944919459194691947919489194991950919519195291953919549195591956919579195891959919609196191962919639196491965919669196791968919699197091971919729197391974919759197691977919789197991980919819198291983919849198591986919879198891989919909199191992919939199491995919969199791998919999200092001920029200392004920059200692007920089200992010920119201292013920149201592016920179201892019920209202192022920239202492025920269202792028920299203092031920329203392034920359203692037920389203992040920419204292043920449204592046920479204892049920509205192052920539205492055920569205792058920599206092061920629206392064920659206692067920689206992070920719207292073920749207592076920779207892079920809208192082920839208492085920869208792088920899209092091920929209392094920959209692097920989209992100921019210292103921049210592106921079210892109921109211192112921139211492115921169211792118921199212092121921229212392124921259212692127921289212992130921319213292133921349213592136921379213892139921409214192142921439214492145921469214792148921499215092151921529215392154921559215692157921589215992160921619216292163921649216592166921679216892169921709217192172921739217492175921769217792178921799218092181921829218392184921859218692187921889218992190921919219292193921949219592196921979219892199922009220192202922039220492205922069220792208922099221092211922129221392214922159221692217922189221992220922219222292223922249222592226922279222892229922309223192232922339223492235922369223792238922399224092241922429224392244922459224692247922489224992250922519225292253922549225592256922579225892259922609226192262922639226492265922669226792268922699227092271922729227392274922759227692277922789227992280922819228292283922849228592286922879228892289922909229192292922939229492295922969229792298922999230092301923029230392304923059230692307923089230992310923119231292313923149231592316923179231892319923209232192322923239232492325923269232792328923299233092331923329233392334923359233692337923389233992340923419234292343923449234592346923479234892349923509235192352923539235492355923569235792358923599236092361923629236392364923659236692367923689236992370923719237292373923749237592376923779237892379923809238192382923839238492385923869238792388923899239092391923929239392394923959239692397923989239992400924019240292403924049240592406924079240892409924109241192412924139241492415924169241792418924199242092421924229242392424924259242692427924289242992430924319243292433924349243592436924379243892439924409244192442924439244492445924469244792448924499245092451924529245392454924559245692457924589245992460924619246292463924649246592466924679246892469924709247192472924739247492475924769247792478924799248092481924829248392484924859248692487924889248992490924919249292493924949249592496924979249892499925009250192502925039250492505925069250792508925099251092511925129251392514925159251692517925189251992520925219252292523925249252592526925279252892529925309253192532925339253492535925369253792538925399254092541925429254392544925459254692547925489254992550925519255292553925549255592556925579255892559925609256192562925639256492565925669256792568925699257092571925729257392574925759257692577925789257992580925819258292583925849258592586925879258892589925909259192592925939259492595925969259792598925999260092601926029260392604926059260692607926089260992610926119261292613926149261592616926179261892619926209262192622926239262492625926269262792628926299263092631926329263392634926359263692637926389263992640926419264292643926449264592646926479264892649926509265192652926539265492655926569265792658926599266092661926629266392664926659266692667926689266992670926719267292673926749267592676926779267892679926809268192682926839268492685926869268792688926899269092691926929269392694926959269692697926989269992700927019270292703927049270592706927079270892709927109271192712927139271492715927169271792718927199272092721927229272392724927259272692727927289272992730927319273292733927349273592736927379273892739927409274192742927439274492745927469274792748927499275092751927529275392754927559275692757927589275992760927619276292763927649276592766927679276892769927709277192772927739277492775927769277792778927799278092781927829278392784927859278692787927889278992790927919279292793927949279592796927979279892799928009280192802928039280492805928069280792808928099281092811928129281392814928159281692817928189281992820928219282292823928249282592826928279282892829928309283192832928339283492835928369283792838928399284092841928429284392844928459284692847928489284992850928519285292853928549285592856928579285892859928609286192862928639286492865928669286792868928699287092871928729287392874928759287692877928789287992880928819288292883928849288592886928879288892889928909289192892928939289492895928969289792898928999290092901929029290392904929059290692907929089290992910929119291292913929149291592916929179291892919929209292192922929239292492925929269292792928929299293092931929329293392934929359293692937929389293992940929419294292943929449294592946929479294892949929509295192952929539295492955929569295792958929599296092961929629296392964929659296692967929689296992970929719297292973929749297592976929779297892979929809298192982929839298492985929869298792988929899299092991929929299392994929959299692997929989299993000930019300293003930049300593006930079300893009930109301193012930139301493015930169301793018930199302093021930229302393024930259302693027930289302993030930319303293033930349303593036930379303893039930409304193042930439304493045930469304793048930499305093051930529305393054930559305693057930589305993060930619306293063930649306593066930679306893069930709307193072930739307493075930769307793078930799308093081930829308393084930859308693087930889308993090930919309293093930949309593096930979309893099931009310193102931039310493105931069310793108931099311093111931129311393114931159311693117931189311993120931219312293123931249312593126931279312893129931309313193132931339313493135931369313793138931399314093141931429314393144931459314693147931489314993150931519315293153931549315593156931579315893159931609316193162931639316493165931669316793168931699317093171931729317393174931759317693177931789317993180931819318293183931849318593186931879318893189931909319193192931939319493195931969319793198931999320093201932029320393204932059320693207932089320993210932119321293213932149321593216932179321893219932209322193222932239322493225932269322793228932299323093231932329323393234932359323693237932389323993240932419324293243932449324593246932479324893249932509325193252932539325493255932569325793258932599326093261932629326393264932659326693267932689326993270932719327293273932749327593276932779327893279932809328193282932839328493285932869328793288932899329093291932929329393294932959329693297932989329993300933019330293303933049330593306933079330893309933109331193312933139331493315933169331793318933199332093321933229332393324933259332693327933289332993330933319333293333933349333593336933379333893339933409334193342933439334493345933469334793348933499335093351933529335393354933559335693357933589335993360933619336293363933649336593366933679336893369933709337193372933739337493375933769337793378933799338093381933829338393384933859338693387933889338993390933919339293393933949339593396933979339893399934009340193402934039340493405934069340793408934099341093411934129341393414934159341693417934189341993420934219342293423934249342593426934279342893429934309343193432934339343493435934369343793438934399344093441934429344393444934459344693447934489344993450934519345293453934549345593456934579345893459934609346193462934639346493465934669346793468934699347093471934729347393474934759347693477934789347993480934819348293483934849348593486934879348893489934909349193492934939349493495934969349793498934999350093501935029350393504935059350693507935089350993510935119351293513935149351593516935179351893519935209352193522935239352493525935269352793528935299353093531935329353393534935359353693537935389353993540935419354293543935449354593546935479354893549935509355193552935539355493555935569355793558935599356093561935629356393564935659356693567935689356993570935719357293573935749357593576935779357893579935809358193582935839358493585935869358793588935899359093591935929359393594935959359693597935989359993600936019360293603936049360593606936079360893609936109361193612936139361493615936169361793618936199362093621936229362393624936259362693627936289362993630936319363293633936349363593636936379363893639936409364193642936439364493645936469364793648936499365093651936529365393654936559365693657936589365993660936619366293663936649366593666936679366893669936709367193672936739367493675936769367793678936799368093681936829368393684936859368693687936889368993690936919369293693936949369593696936979369893699937009370193702937039370493705937069370793708937099371093711937129371393714937159371693717937189371993720937219372293723937249372593726937279372893729937309373193732937339373493735937369373793738937399374093741937429374393744937459374693747937489374993750937519375293753937549375593756937579375893759937609376193762937639376493765937669376793768937699377093771937729377393774937759377693777937789377993780937819378293783937849378593786937879378893789937909379193792937939379493795937969379793798937999380093801938029380393804938059380693807938089380993810938119381293813938149381593816938179381893819938209382193822938239382493825938269382793828938299383093831938329383393834938359383693837938389383993840938419384293843938449384593846938479384893849938509385193852938539385493855938569385793858938599386093861938629386393864938659386693867938689386993870938719387293873938749387593876938779387893879938809388193882938839388493885938869388793888938899389093891938929389393894938959389693897938989389993900939019390293903939049390593906939079390893909939109391193912939139391493915939169391793918939199392093921939229392393924939259392693927939289392993930939319393293933939349393593936939379393893939939409394193942939439394493945939469394793948939499395093951939529395393954939559395693957939589395993960939619396293963939649396593966939679396893969939709397193972939739397493975939769397793978939799398093981939829398393984939859398693987939889398993990939919399293993939949399593996939979399893999940009400194002940039400494005940069400794008940099401094011940129401394014940159401694017940189401994020940219402294023940249402594026940279402894029940309403194032940339403494035940369403794038940399404094041940429404394044940459404694047940489404994050940519405294053940549405594056940579405894059940609406194062940639406494065940669406794068940699407094071940729407394074940759407694077940789407994080940819408294083940849408594086940879408894089940909409194092940939409494095940969409794098940999410094101941029410394104941059410694107941089410994110941119411294113941149411594116941179411894119941209412194122941239412494125941269412794128941299413094131941329413394134941359413694137941389413994140941419414294143941449414594146941479414894149941509415194152941539415494155941569415794158941599416094161941629416394164941659416694167941689416994170941719417294173941749417594176941779417894179941809418194182941839418494185941869418794188941899419094191941929419394194941959419694197941989419994200942019420294203942049420594206942079420894209942109421194212942139421494215942169421794218942199422094221942229422394224942259422694227942289422994230942319423294233942349423594236942379423894239942409424194242942439424494245942469424794248942499425094251942529425394254942559425694257942589425994260942619426294263942649426594266942679426894269942709427194272942739427494275942769427794278942799428094281942829428394284942859428694287942889428994290942919429294293942949429594296942979429894299943009430194302943039430494305943069430794308943099431094311943129431394314943159431694317943189431994320943219432294323943249432594326943279432894329943309433194332943339433494335943369433794338943399434094341943429434394344943459434694347943489434994350943519435294353943549435594356943579435894359943609436194362943639436494365943669436794368943699437094371943729437394374943759437694377943789437994380943819438294383943849438594386943879438894389943909439194392943939439494395943969439794398943999440094401944029440394404944059440694407944089440994410944119441294413944149441594416944179441894419944209442194422944239442494425944269442794428944299443094431944329443394434944359443694437944389443994440944419444294443944449444594446944479444894449944509445194452944539445494455944569445794458944599446094461944629446394464944659446694467944689446994470944719447294473944749447594476944779447894479944809448194482944839448494485944869448794488944899449094491944929449394494944959449694497944989449994500945019450294503945049450594506945079450894509945109451194512945139451494515945169451794518945199452094521945229452394524945259452694527945289452994530945319453294533945349453594536945379453894539945409454194542945439454494545945469454794548945499455094551945529455394554945559455694557945589455994560945619456294563945649456594566945679456894569945709457194572945739457494575945769457794578945799458094581945829458394584945859458694587945889458994590945919459294593945949459594596945979459894599946009460194602946039460494605946069460794608946099461094611946129461394614946159461694617946189461994620946219462294623946249462594626946279462894629946309463194632946339463494635946369463794638946399464094641946429464394644946459464694647946489464994650946519465294653946549465594656946579465894659946609466194662946639466494665946669466794668946699467094671946729467394674946759467694677946789467994680946819468294683946849468594686946879468894689946909469194692946939469494695946969469794698946999470094701947029470394704947059470694707947089470994710947119471294713947149471594716947179471894719947209472194722947239472494725947269472794728947299473094731947329473394734947359473694737947389473994740947419474294743947449474594746947479474894749947509475194752947539475494755947569475794758947599476094761947629476394764947659476694767947689476994770947719477294773947749477594776947779477894779947809478194782947839478494785947869478794788947899479094791947929479394794947959479694797947989479994800948019480294803948049480594806948079480894809948109481194812948139481494815948169481794818948199482094821948229482394824948259482694827948289482994830948319483294833948349483594836948379483894839948409484194842948439484494845948469484794848948499485094851948529485394854948559485694857948589485994860948619486294863948649486594866948679486894869948709487194872948739487494875948769487794878948799488094881948829488394884948859488694887948889488994890948919489294893948949489594896948979489894899949009490194902949039490494905949069490794908949099491094911949129491394914949159491694917949189491994920949219492294923949249492594926949279492894929949309493194932949339493494935949369493794938949399494094941949429494394944949459494694947949489494994950949519495294953949549495594956949579495894959949609496194962949639496494965949669496794968949699497094971949729497394974949759497694977949789497994980949819498294983949849498594986949879498894989949909499194992949939499494995949969499794998949999500095001950029500395004950059500695007950089500995010950119501295013950149501595016950179501895019950209502195022950239502495025950269502795028950299503095031950329503395034950359503695037950389503995040950419504295043950449504595046950479504895049950509505195052950539505495055950569505795058950599506095061950629506395064950659506695067950689506995070950719507295073950749507595076950779507895079950809508195082950839508495085950869508795088950899509095091950929509395094950959509695097950989509995100951019510295103951049510595106951079510895109951109511195112951139511495115951169511795118951199512095121951229512395124951259512695127951289512995130951319513295133951349513595136951379513895139951409514195142951439514495145951469514795148951499515095151951529515395154951559515695157951589515995160951619516295163951649516595166951679516895169951709517195172951739517495175951769517795178951799518095181951829518395184951859518695187951889518995190951919519295193951949519595196951979519895199952009520195202952039520495205952069520795208952099521095211952129521395214952159521695217952189521995220952219522295223952249522595226952279522895229952309523195232952339523495235952369523795238952399524095241952429524395244952459524695247952489524995250952519525295253952549525595256952579525895259952609526195262952639526495265952669526795268952699527095271952729527395274952759527695277952789527995280952819528295283952849528595286952879528895289952909529195292952939529495295952969529795298952999530095301953029530395304953059530695307953089530995310953119531295313953149531595316953179531895319953209532195322953239532495325953269532795328953299533095331953329533395334953359533695337953389533995340953419534295343953449534595346953479534895349953509535195352953539535495355953569535795358953599536095361953629536395364953659536695367953689536995370953719537295373953749537595376953779537895379953809538195382953839538495385953869538795388953899539095391953929539395394953959539695397953989539995400954019540295403954049540595406954079540895409954109541195412954139541495415954169541795418954199542095421954229542395424954259542695427954289542995430954319543295433954349543595436954379543895439954409544195442954439544495445954469544795448954499545095451954529545395454954559545695457954589545995460954619546295463954649546595466954679546895469954709547195472954739547495475954769547795478954799548095481954829548395484954859548695487954889548995490954919549295493954949549595496954979549895499955009550195502955039550495505955069550795508955099551095511955129551395514955159551695517955189551995520955219552295523955249552595526955279552895529955309553195532955339553495535955369553795538955399554095541955429554395544955459554695547955489554995550955519555295553955549555595556955579555895559955609556195562955639556495565955669556795568955699557095571955729557395574955759557695577955789557995580955819558295583955849558595586955879558895589955909559195592955939559495595955969559795598955999560095601956029560395604956059560695607956089560995610956119561295613956149561595616956179561895619956209562195622956239562495625956269562795628956299563095631956329563395634956359563695637956389563995640956419564295643956449564595646956479564895649956509565195652956539565495655956569565795658956599566095661956629566395664956659566695667956689566995670956719567295673956749567595676956779567895679956809568195682956839568495685956869568795688956899569095691956929569395694956959569695697956989569995700957019570295703957049570595706957079570895709957109571195712957139571495715957169571795718957199572095721957229572395724957259572695727957289572995730957319573295733957349573595736957379573895739957409574195742957439574495745957469574795748957499575095751957529575395754957559575695757957589575995760957619576295763957649576595766957679576895769957709577195772957739577495775957769577795778957799578095781957829578395784957859578695787957889578995790957919579295793957949579595796957979579895799958009580195802958039580495805958069580795808958099581095811958129581395814958159581695817958189581995820958219582295823958249582595826958279582895829958309583195832958339583495835958369583795838958399584095841958429584395844958459584695847958489584995850958519585295853958549585595856958579585895859958609586195862958639586495865958669586795868958699587095871958729587395874958759587695877958789587995880958819588295883958849588595886958879588895889958909589195892958939589495895958969589795898958999590095901959029590395904959059590695907959089590995910959119591295913959149591595916959179591895919959209592195922959239592495925959269592795928959299593095931959329593395934959359593695937959389593995940959419594295943959449594595946959479594895949959509595195952959539595495955959569595795958959599596095961959629596395964959659596695967959689596995970959719597295973959749597595976959779597895979959809598195982959839598495985959869598795988959899599095991959929599395994959959599695997959989599996000960019600296003960049600596006960079600896009960109601196012960139601496015960169601796018960199602096021960229602396024960259602696027960289602996030960319603296033960349603596036960379603896039960409604196042960439604496045960469604796048960499605096051960529605396054960559605696057960589605996060960619606296063960649606596066960679606896069960709607196072960739607496075960769607796078960799608096081960829608396084960859608696087960889608996090960919609296093960949609596096960979609896099961009610196102961039610496105961069610796108961099611096111961129611396114961159611696117961189611996120961219612296123961249612596126961279612896129961309613196132961339613496135961369613796138961399614096141961429614396144961459614696147961489614996150961519615296153961549615596156961579615896159961609616196162961639616496165961669616796168961699617096171961729617396174961759617696177961789617996180961819618296183961849618596186961879618896189961909619196192961939619496195961969619796198961999620096201962029620396204962059620696207962089620996210962119621296213962149621596216962179621896219962209622196222962239622496225962269622796228962299623096231962329623396234962359623696237962389623996240962419624296243962449624596246962479624896249962509625196252962539625496255962569625796258962599626096261962629626396264962659626696267962689626996270962719627296273962749627596276962779627896279962809628196282962839628496285962869628796288962899629096291962929629396294962959629696297962989629996300963019630296303963049630596306963079630896309963109631196312963139631496315963169631796318963199632096321963229632396324963259632696327963289632996330963319633296333963349633596336963379633896339963409634196342963439634496345963469634796348963499635096351963529635396354963559635696357963589635996360963619636296363963649636596366963679636896369963709637196372963739637496375963769637796378963799638096381963829638396384963859638696387963889638996390963919639296393963949639596396963979639896399964009640196402964039640496405964069640796408964099641096411964129641396414964159641696417964189641996420964219642296423964249642596426964279642896429964309643196432964339643496435964369643796438964399644096441964429644396444964459644696447964489644996450964519645296453964549645596456964579645896459964609646196462964639646496465964669646796468964699647096471964729647396474964759647696477964789647996480964819648296483964849648596486964879648896489964909649196492964939649496495964969649796498964999650096501965029650396504965059650696507965089650996510965119651296513965149651596516965179651896519965209652196522965239652496525965269652796528965299653096531965329653396534965359653696537965389653996540965419654296543965449654596546965479654896549965509655196552965539655496555965569655796558965599656096561965629656396564965659656696567965689656996570965719657296573965749657596576965779657896579965809658196582965839658496585965869658796588965899659096591965929659396594965959659696597965989659996600966019660296603966049660596606966079660896609966109661196612966139661496615966169661796618966199662096621966229662396624966259662696627966289662996630966319663296633966349663596636966379663896639966409664196642966439664496645966469664796648966499665096651966529665396654966559665696657966589665996660966619666296663966649666596666966679666896669966709667196672966739667496675966769667796678966799668096681966829668396684966859668696687966889668996690966919669296693966949669596696966979669896699967009670196702967039670496705967069670796708967099671096711967129671396714967159671696717967189671996720967219672296723967249672596726967279672896729967309673196732967339673496735967369673796738967399674096741967429674396744967459674696747967489674996750967519675296753967549675596756967579675896759967609676196762967639676496765967669676796768967699677096771967729677396774967759677696777967789677996780967819678296783967849678596786967879678896789967909679196792967939679496795967969679796798967999680096801968029680396804968059680696807968089680996810968119681296813968149681596816968179681896819968209682196822968239682496825968269682796828968299683096831968329683396834968359683696837968389683996840968419684296843968449684596846968479684896849968509685196852968539685496855968569685796858968599686096861968629686396864968659686696867968689686996870968719687296873968749687596876968779687896879968809688196882968839688496885968869688796888968899689096891968929689396894968959689696897968989689996900969019690296903969049690596906969079690896909969109691196912969139691496915969169691796918969199692096921969229692396924969259692696927969289692996930969319693296933969349693596936969379693896939969409694196942969439694496945969469694796948969499695096951969529695396954969559695696957969589695996960969619696296963969649696596966969679696896969969709697196972969739697496975969769697796978969799698096981969829698396984969859698696987969889698996990969919699296993969949699596996969979699896999970009700197002970039700497005970069700797008970099701097011970129701397014970159701697017970189701997020970219702297023970249702597026970279702897029970309703197032970339703497035970369703797038970399704097041970429704397044970459704697047970489704997050970519705297053970549705597056970579705897059970609706197062970639706497065970669706797068970699707097071970729707397074970759707697077970789707997080970819708297083970849708597086970879708897089970909709197092970939709497095970969709797098970999710097101971029710397104971059710697107971089710997110971119711297113971149711597116971179711897119971209712197122971239712497125971269712797128971299713097131971329713397134971359713697137971389713997140971419714297143971449714597146971479714897149971509715197152971539715497155971569715797158971599716097161971629716397164971659716697167971689716997170971719717297173971749717597176971779717897179971809718197182971839718497185971869718797188971899719097191971929719397194971959719697197971989719997200972019720297203972049720597206972079720897209972109721197212972139721497215972169721797218972199722097221972229722397224972259722697227972289722997230972319723297233972349723597236972379723897239972409724197242972439724497245972469724797248972499725097251972529725397254972559725697257972589725997260972619726297263972649726597266972679726897269972709727197272972739727497275972769727797278972799728097281972829728397284972859728697287972889728997290972919729297293972949729597296972979729897299973009730197302973039730497305973069730797308973099731097311973129731397314973159731697317973189731997320973219732297323973249732597326973279732897329973309733197332973339733497335973369733797338973399734097341973429734397344973459734697347973489734997350973519735297353973549735597356973579735897359973609736197362973639736497365973669736797368973699737097371973729737397374973759737697377973789737997380973819738297383973849738597386973879738897389973909739197392973939739497395973969739797398973999740097401974029740397404974059740697407974089740997410974119741297413974149741597416974179741897419974209742197422974239742497425974269742797428974299743097431974329743397434974359743697437974389743997440974419744297443974449744597446974479744897449974509745197452974539745497455974569745797458974599746097461974629746397464974659746697467974689746997470974719747297473974749747597476974779747897479974809748197482974839748497485974869748797488974899749097491974929749397494974959749697497974989749997500975019750297503975049750597506975079750897509975109751197512975139751497515975169751797518975199752097521975229752397524975259752697527975289752997530975319753297533975349753597536975379753897539975409754197542975439754497545975469754797548975499755097551975529755397554975559755697557975589755997560975619756297563975649756597566975679756897569975709757197572975739757497575975769757797578975799758097581975829758397584975859758697587975889758997590975919759297593975949759597596975979759897599976009760197602976039760497605976069760797608976099761097611976129761397614976159761697617976189761997620976219762297623976249762597626976279762897629976309763197632976339763497635976369763797638976399764097641976429764397644976459764697647976489764997650976519765297653976549765597656976579765897659976609766197662976639766497665976669766797668976699767097671976729767397674976759767697677976789767997680976819768297683976849768597686976879768897689976909769197692976939769497695976969769797698976999770097701977029770397704977059770697707977089770997710977119771297713977149771597716977179771897719977209772197722977239772497725977269772797728977299773097731977329773397734977359773697737977389773997740977419774297743977449774597746977479774897749977509775197752977539775497755977569775797758977599776097761977629776397764977659776697767977689776997770977719777297773977749777597776977779777897779977809778197782977839778497785977869778797788977899779097791977929779397794977959779697797977989779997800978019780297803978049780597806978079780897809978109781197812978139781497815978169781797818978199782097821978229782397824978259782697827978289782997830978319783297833978349783597836978379783897839978409784197842978439784497845978469784797848978499785097851978529785397854978559785697857978589785997860978619786297863978649786597866978679786897869978709787197872978739787497875978769787797878978799788097881978829788397884978859788697887978889788997890978919789297893978949789597896978979789897899979009790197902979039790497905979069790797908979099791097911979129791397914979159791697917979189791997920979219792297923979249792597926979279792897929979309793197932979339793497935979369793797938979399794097941979429794397944979459794697947979489794997950979519795297953979549795597956979579795897959979609796197962979639796497965979669796797968979699797097971979729797397974979759797697977979789797997980979819798297983979849798597986979879798897989979909799197992979939799497995979969799797998979999800098001980029800398004980059800698007980089800998010980119801298013980149801598016980179801898019980209802198022980239802498025980269802798028980299803098031980329803398034980359803698037980389803998040980419804298043980449804598046980479804898049980509805198052980539805498055980569805798058980599806098061980629806398064980659806698067980689806998070980719807298073980749807598076980779807898079980809808198082980839808498085980869808798088980899809098091980929809398094980959809698097980989809998100981019810298103981049810598106981079810898109981109811198112981139811498115981169811798118981199812098121981229812398124981259812698127981289812998130981319813298133981349813598136981379813898139981409814198142981439814498145981469814798148981499815098151981529815398154981559815698157981589815998160981619816298163981649816598166981679816898169981709817198172981739817498175981769817798178981799818098181981829818398184981859818698187981889818998190981919819298193981949819598196981979819898199982009820198202982039820498205982069820798208982099821098211982129821398214982159821698217982189821998220982219822298223982249822598226982279822898229982309823198232982339823498235982369823798238982399824098241982429824398244982459824698247982489824998250982519825298253982549825598256982579825898259982609826198262982639826498265982669826798268982699827098271982729827398274982759827698277982789827998280982819828298283982849828598286982879828898289982909829198292982939829498295982969829798298982999830098301983029830398304983059830698307983089830998310983119831298313983149831598316983179831898319983209832198322983239832498325983269832798328983299833098331983329833398334983359833698337983389833998340983419834298343983449834598346983479834898349983509835198352983539835498355983569835798358983599836098361983629836398364983659836698367983689836998370983719837298373983749837598376983779837898379983809838198382983839838498385983869838798388983899839098391983929839398394983959839698397983989839998400984019840298403984049840598406984079840898409984109841198412984139841498415984169841798418984199842098421984229842398424984259842698427984289842998430984319843298433984349843598436984379843898439984409844198442984439844498445984469844798448984499845098451984529845398454984559845698457984589845998460984619846298463984649846598466984679846898469984709847198472984739847498475984769847798478984799848098481984829848398484984859848698487984889848998490984919849298493984949849598496984979849898499985009850198502985039850498505985069850798508985099851098511985129851398514985159851698517985189851998520985219852298523985249852598526985279852898529985309853198532985339853498535985369853798538985399854098541985429854398544985459854698547985489854998550985519855298553985549855598556985579855898559985609856198562985639856498565985669856798568985699857098571985729857398574985759857698577985789857998580985819858298583985849858598586985879858898589985909859198592985939859498595985969859798598985999860098601986029860398604986059860698607986089860998610986119861298613986149861598616986179861898619986209862198622986239862498625986269862798628986299863098631986329863398634986359863698637986389863998640986419864298643986449864598646986479864898649986509865198652986539865498655986569865798658986599866098661986629866398664986659866698667986689866998670986719867298673986749867598676986779867898679986809868198682986839868498685986869868798688986899869098691986929869398694986959869698697986989869998700987019870298703987049870598706987079870898709987109871198712987139871498715987169871798718987199872098721987229872398724987259872698727987289872998730987319873298733987349873598736987379873898739987409874198742987439874498745987469874798748987499875098751987529875398754987559875698757987589875998760987619876298763987649876598766987679876898769987709877198772987739877498775987769877798778987799878098781987829878398784987859878698787987889878998790987919879298793987949879598796987979879898799988009880198802988039880498805988069880798808988099881098811988129881398814988159881698817988189881998820988219882298823988249882598826988279882898829988309883198832988339883498835988369883798838988399884098841988429884398844988459884698847988489884998850988519885298853988549885598856988579885898859988609886198862988639886498865988669886798868988699887098871988729887398874988759887698877988789887998880988819888298883988849888598886988879888898889988909889198892988939889498895988969889798898988999890098901989029890398904989059890698907989089890998910989119891298913989149891598916989179891898919989209892198922989239892498925989269892798928989299893098931989329893398934989359893698937989389893998940989419894298943989449894598946989479894898949989509895198952989539895498955989569895798958989599896098961989629896398964989659896698967989689896998970989719897298973989749897598976989779897898979989809898198982989839898498985989869898798988989899899098991989929899398994989959899698997989989899999000990019900299003990049900599006990079900899009990109901199012990139901499015990169901799018990199902099021990229902399024990259902699027990289902999030990319903299033990349903599036990379903899039990409904199042990439904499045990469904799048990499905099051990529905399054990559905699057990589905999060990619906299063990649906599066990679906899069990709907199072990739907499075990769907799078990799908099081990829908399084990859908699087990889908999090990919909299093990949909599096990979909899099991009910199102991039910499105991069910799108991099911099111991129911399114991159911699117991189911999120991219912299123991249912599126991279912899129991309913199132991339913499135991369913799138991399914099141991429914399144991459914699147991489914999150991519915299153991549915599156991579915899159991609916199162991639916499165991669916799168991699917099171991729917399174991759917699177991789917999180991819918299183991849918599186991879918899189991909919199192991939919499195991969919799198991999920099201992029920399204992059920699207992089920999210992119921299213992149921599216992179921899219992209922199222992239922499225992269922799228992299923099231992329923399234992359923699237992389923999240992419924299243992449924599246992479924899249992509925199252992539925499255992569925799258992599926099261992629926399264992659926699267992689926999270992719927299273992749927599276992779927899279992809928199282992839928499285992869928799288992899929099291992929929399294992959929699297992989929999300993019930299303993049930599306993079930899309993109931199312993139931499315993169931799318993199932099321993229932399324993259932699327993289932999330993319933299333993349933599336993379933899339993409934199342993439934499345993469934799348993499935099351993529935399354993559935699357993589935999360993619936299363993649936599366993679936899369993709937199372993739937499375993769937799378993799938099381993829938399384993859938699387993889938999390993919939299393993949939599396993979939899399994009940199402994039940499405994069940799408994099941099411994129941399414994159941699417994189941999420994219942299423994249942599426994279942899429994309943199432994339943499435994369943799438994399944099441994429944399444994459944699447994489944999450994519945299453994549945599456994579945899459994609946199462994639946499465994669946799468994699947099471994729947399474994759947699477994789947999480994819948299483994849948599486994879948899489994909949199492994939949499495994969949799498994999950099501995029950399504995059950699507995089950999510995119951299513995149951599516995179951899519995209952199522995239952499525995269952799528995299953099531995329953399534995359953699537995389953999540995419954299543995449954599546995479954899549995509955199552995539955499555995569955799558995599956099561995629956399564995659956699567995689956999570995719957299573995749957599576995779957899579995809958199582995839958499585995869958799588995899959099591995929959399594995959959699597995989959999600996019960299603996049960599606996079960899609996109961199612996139961499615996169961799618996199962099621996229962399624996259962699627996289962999630996319963299633996349963599636996379963899639996409964199642996439964499645996469964799648996499965099651996529965399654996559965699657996589965999660996619966299663996649966599666996679966899669996709967199672996739967499675996769967799678996799968099681996829968399684996859968699687996889968999690996919969299693996949969599696996979969899699997009970199702997039970499705997069970799708997099971099711997129971399714997159971699717997189971999720997219972299723997249972599726997279972899729997309973199732997339973499735997369973799738997399974099741997429974399744997459974699747997489974999750997519975299753997549975599756997579975899759997609976199762997639976499765997669976799768997699977099771997729977399774997759977699777997789977999780997819978299783997849978599786997879978899789997909979199792997939979499795997969979799798997999980099801998029980399804998059980699807998089980999810998119981299813998149981599816998179981899819998209982199822998239982499825998269982799828998299983099831998329983399834998359983699837998389983999840998419984299843998449984599846998479984899849998509985199852998539985499855998569985799858998599986099861998629986399864998659986699867998689986999870998719987299873998749987599876998779987899879998809988199882998839988499885998869988799888998899989099891998929989399894998959989699897998989989999900999019990299903999049990599906999079990899909999109991199912999139991499915999169991799918999199992099921999229992399924999259992699927999289992999930999319993299933999349993599936999379993899939999409994199942999439994499945999469994799948999499995099951999529995399954999559995699957999589995999960999619996299963999649996599966999679996899969999709997199972999739997499975999769997799978999799998099981999829998399984999859998699987999889998999990999919999299993999949999599996999979999899999100000100001100002100003100004100005100006100007100008100009100010100011100012100013100014100015100016100017100018100019100020100021100022100023100024100025100026100027100028100029100030100031100032100033100034100035100036100037100038100039100040100041100042100043100044100045100046100047100048100049100050100051100052100053100054100055100056100057100058100059100060100061100062100063100064100065100066100067100068100069100070100071100072100073100074100075100076100077100078100079100080100081100082100083100084100085100086100087100088100089100090100091100092100093100094100095100096100097100098100099100100100101100102100103100104100105100106100107100108100109100110100111100112100113100114100115100116100117100118100119100120100121100122100123100124100125100126100127100128100129100130100131100132100133100134100135100136100137100138100139100140100141100142100143100144100145100146100147100148100149100150100151100152100153100154100155100156100157100158100159100160100161100162100163100164100165100166100167100168100169100170100171100172100173100174100175100176100177100178100179100180100181100182100183100184100185100186100187100188100189100190100191100192100193100194100195100196100197100198100199100200100201100202100203100204100205100206100207100208100209100210100211100212100213100214100215100216100217100218100219100220100221100222100223100224100225100226100227100228100229100230100231100232100233100234100235100236100237100238100239100240100241100242100243100244100245100246100247100248100249100250100251100252100253100254100255100256100257100258100259100260100261100262100263100264100265100266100267100268100269100270100271100272100273100274100275100276100277100278100279100280100281100282100283100284100285100286100287100288100289100290100291100292100293100294100295100296100297100298100299100300100301100302100303100304100305100306100307100308100309100310100311100312100313100314100315100316100317100318100319100320100321100322100323100324100325100326100327100328100329100330100331100332100333100334100335100336100337100338100339100340100341100342100343100344100345100346100347100348100349100350100351100352100353100354100355100356100357100358100359100360100361100362100363100364100365100366100367100368100369100370100371100372100373100374100375100376100377100378100379100380100381100382100383100384100385100386100387100388100389100390100391100392100393100394100395100396100397100398100399100400100401100402100403100404100405100406100407100408100409100410100411100412100413100414100415100416100417100418100419100420100421100422100423100424100425100426100427100428100429100430100431100432100433100434100435100436100437100438100439100440100441100442100443100444100445100446100447100448100449100450100451100452100453100454100455100456100457100458100459100460100461100462100463100464100465100466100467100468100469100470100471100472100473100474100475100476100477100478100479100480100481100482100483100484100485100486100487100488100489100490100491100492100493100494100495100496100497100498100499100500100501100502100503100504100505100506100507100508100509100510100511100512100513100514100515100516100517100518100519100520100521100522100523100524100525100526100527100528100529100530100531100532100533100534100535100536100537100538100539100540100541100542100543100544100545100546100547100548100549100550100551100552100553100554100555100556100557100558100559100560100561100562100563100564100565100566100567100568100569100570100571100572100573100574100575100576100577100578100579100580100581100582100583100584100585100586100587100588100589100590100591100592100593100594100595100596100597100598100599100600100601100602100603100604100605100606100607100608100609100610100611100612100613100614100615100616100617100618100619100620100621100622100623100624100625100626100627100628100629100630100631100632100633100634100635100636100637100638100639100640100641100642100643100644100645100646100647100648100649100650100651100652100653100654100655100656100657100658100659100660100661100662100663100664100665100666100667100668100669100670100671100672100673100674100675100676100677100678100679100680100681100682100683100684100685100686100687100688100689100690100691100692100693100694100695100696100697100698100699100700100701100702100703100704100705100706100707100708100709100710100711100712100713100714100715100716100717100718100719100720100721100722100723100724100725100726100727100728100729100730100731100732100733100734100735100736100737100738100739100740100741100742100743100744100745100746100747100748100749100750100751100752100753100754100755100756100757100758100759100760100761100762100763100764100765100766100767100768100769100770100771100772100773100774100775100776100777100778100779100780100781100782100783100784100785100786100787100788100789100790100791100792100793100794100795100796100797100798100799100800100801100802100803100804100805100806100807100808100809100810100811100812100813100814100815100816100817100818100819100820100821100822100823100824100825100826100827100828100829100830100831100832100833100834100835100836100837100838100839100840100841100842100843100844100845100846100847100848100849100850100851100852100853100854100855100856100857100858100859100860100861100862100863100864100865100866100867100868100869100870100871100872100873100874100875100876100877100878100879100880100881100882100883100884100885100886100887100888100889100890100891100892100893100894100895100896100897100898100899100900100901100902100903100904100905100906100907100908100909100910100911100912100913100914100915100916100917100918100919100920100921100922100923100924100925100926100927100928100929100930100931100932100933100934100935100936100937100938100939100940100941100942100943100944100945100946100947100948100949100950100951100952100953100954100955100956100957100958100959100960100961100962100963100964100965100966100967100968100969100970100971100972100973100974100975100976100977100978100979100980100981100982100983100984100985100986100987100988100989100990100991100992100993100994100995100996100997100998100999101000101001101002101003101004101005101006101007101008101009101010101011101012101013101014101015101016101017101018101019101020101021101022101023101024101025101026101027101028101029101030101031101032101033101034101035101036101037101038101039101040101041101042101043101044101045101046101047101048101049101050101051101052101053101054101055101056101057101058101059101060101061101062101063101064101065101066101067101068101069101070101071101072101073101074101075101076101077101078101079101080101081101082101083101084101085101086101087101088101089101090101091101092101093101094101095101096101097101098101099101100101101101102101103101104101105101106101107101108101109101110101111101112101113101114101115101116101117101118101119101120101121101122101123101124101125101126101127101128101129101130101131101132101133101134101135101136101137101138101139101140101141101142101143101144101145101146101147101148101149101150101151101152101153101154101155101156101157101158101159101160101161101162101163101164101165101166101167101168101169101170101171101172101173101174101175101176101177101178101179101180101181101182101183101184101185101186101187101188101189101190101191101192101193101194101195101196101197101198101199101200101201101202101203101204101205101206101207101208101209101210101211101212101213101214101215101216101217101218101219101220101221101222101223101224101225101226101227101228101229101230101231101232101233101234101235101236101237101238101239101240101241101242101243101244101245101246101247101248101249101250101251101252101253101254101255101256101257101258101259101260101261101262101263101264101265101266101267101268101269101270101271101272101273101274101275101276101277101278101279101280101281101282101283101284101285101286101287101288101289101290101291101292101293101294101295101296101297101298101299101300101301101302101303101304101305101306101307101308101309101310101311101312101313101314101315101316101317101318101319101320101321101322101323101324101325101326101327101328101329101330101331101332101333101334101335101336101337101338101339101340101341101342101343101344101345101346101347101348101349101350101351101352101353101354101355101356101357101358101359101360101361101362101363101364101365101366101367101368101369101370101371101372101373101374101375101376101377101378101379101380101381101382101383101384101385101386101387101388101389101390101391101392101393101394101395101396101397101398101399101400101401101402101403101404101405101406101407101408101409101410101411101412101413101414101415101416101417101418101419101420101421101422101423101424101425101426101427101428101429101430101431101432101433101434101435101436101437101438101439101440101441101442101443101444101445101446101447101448101449101450101451101452101453101454101455101456101457101458101459101460101461101462101463101464101465101466101467101468101469101470101471101472101473101474101475101476101477101478101479101480101481101482101483101484101485101486101487101488101489101490101491101492101493101494101495101496101497101498101499101500101501101502101503101504101505101506101507101508101509101510101511101512101513101514101515101516101517101518101519101520101521101522101523101524101525101526101527101528101529101530101531101532101533101534101535101536101537101538101539101540101541101542101543101544101545101546101547101548101549101550101551101552101553101554101555101556101557101558101559101560101561101562101563101564101565101566101567101568101569101570101571101572101573101574101575101576101577101578101579101580101581101582101583101584101585101586101587101588101589101590101591101592101593101594101595101596101597101598101599101600101601101602101603101604101605101606101607101608101609101610101611101612101613101614101615101616101617101618101619101620101621101622101623101624101625101626101627101628101629101630101631101632101633101634101635101636101637101638101639101640101641101642101643101644101645101646101647101648101649101650101651101652101653101654101655101656101657101658101659101660101661101662101663101664101665101666101667101668101669101670101671101672101673101674101675101676101677101678101679101680101681101682101683101684101685101686101687101688101689101690101691101692101693101694101695101696101697101698101699101700101701101702101703101704101705101706101707101708101709101710101711101712101713101714101715101716101717101718101719101720101721101722101723101724101725101726101727101728101729101730101731101732101733101734101735101736101737101738101739101740101741101742101743101744101745101746101747101748101749101750101751101752101753101754101755101756101757101758101759101760101761101762101763101764101765101766101767101768101769101770101771101772101773101774101775101776101777101778101779101780101781101782101783101784101785101786101787101788101789101790101791101792101793101794101795101796101797101798101799101800101801101802101803101804101805101806101807101808101809101810101811101812101813101814101815101816101817101818101819101820101821101822101823101824101825101826101827101828101829101830101831101832101833101834101835101836101837101838101839101840101841101842101843101844101845101846101847101848101849101850101851101852101853101854101855101856101857101858101859101860101861101862101863101864101865101866101867101868101869101870101871101872101873101874101875101876101877101878101879101880101881101882101883101884101885101886101887101888101889101890101891101892101893101894101895101896101897101898101899101900101901101902101903101904101905101906101907101908101909101910101911101912101913101914101915101916101917101918101919101920101921101922101923101924101925101926101927101928101929101930101931101932101933101934101935101936101937101938101939101940101941101942101943101944101945101946101947101948101949101950101951101952101953101954101955101956101957101958101959101960101961101962101963101964101965101966101967101968101969101970101971101972101973101974101975101976101977101978101979101980101981101982101983101984101985101986101987101988101989101990101991101992101993101994101995101996101997101998101999102000102001102002102003102004102005102006102007102008102009102010102011102012102013102014102015102016102017102018102019102020102021102022102023102024102025102026102027102028102029102030102031102032102033102034102035102036102037102038102039102040102041102042102043102044102045102046102047102048102049102050102051102052102053102054102055102056102057102058102059102060102061102062102063102064102065102066102067102068102069102070102071102072102073102074102075102076102077102078102079102080102081102082102083102084102085102086102087102088102089102090102091102092102093102094102095102096102097102098102099102100102101102102102103102104102105102106102107102108102109102110102111102112102113102114102115102116102117102118102119102120102121102122102123102124102125102126102127102128102129102130102131102132102133102134102135102136102137102138102139102140102141102142102143102144102145102146102147102148102149102150102151102152102153102154102155102156102157102158102159102160102161102162102163102164102165102166102167102168102169102170102171102172102173102174102175102176102177102178102179102180102181102182102183102184102185102186102187102188102189102190102191102192102193102194102195102196102197102198102199102200102201102202102203102204102205102206102207102208102209102210102211102212102213102214102215102216102217102218102219102220102221102222102223102224102225102226102227102228102229102230102231102232102233102234102235102236102237102238102239102240102241102242102243102244102245102246102247102248102249102250102251102252102253102254102255102256102257102258102259102260102261102262102263102264102265102266102267102268102269102270102271102272102273102274102275102276102277102278102279102280102281102282102283102284102285102286102287102288102289102290102291102292102293102294102295102296102297102298102299102300102301102302102303102304102305102306102307102308102309102310102311102312102313102314102315102316102317102318102319102320102321102322102323102324102325102326102327102328102329102330102331102332102333102334102335102336102337102338102339102340102341102342102343102344102345102346102347102348102349102350102351102352102353102354102355102356102357102358102359102360102361102362102363102364102365102366102367102368102369102370102371102372102373102374102375102376102377102378102379102380102381102382102383102384102385102386102387102388102389102390102391102392102393102394102395102396102397102398102399102400102401102402102403102404102405102406102407102408102409102410102411102412102413102414102415102416102417102418102419102420102421102422102423102424102425102426102427102428102429102430102431102432102433102434102435102436102437102438102439102440102441102442102443102444102445102446102447102448102449102450102451102452102453102454102455102456102457102458102459102460102461102462102463102464102465102466102467102468102469102470102471102472102473102474102475102476102477102478102479102480102481102482102483102484102485102486102487102488102489102490102491102492102493102494102495102496102497102498102499102500102501102502102503102504102505102506102507102508102509102510102511102512102513102514102515102516102517102518102519102520102521102522102523102524102525102526102527102528102529102530102531102532102533102534102535102536102537102538102539102540102541102542102543102544102545102546102547102548102549102550102551102552102553102554102555102556102557102558102559102560102561102562102563102564102565102566102567102568102569102570102571102572102573102574102575102576102577102578102579102580102581102582102583102584102585102586102587102588102589102590102591102592102593102594102595102596102597102598102599102600102601102602102603102604102605102606102607102608102609102610102611102612102613102614102615102616102617102618102619102620102621102622102623102624102625102626102627102628102629102630102631102632102633102634102635102636102637102638102639102640102641102642102643102644102645102646102647102648102649102650102651102652102653102654102655102656102657102658102659102660102661102662102663102664102665102666102667102668102669102670102671102672102673102674102675102676102677102678102679102680102681102682102683102684102685102686102687102688102689102690102691102692102693102694102695102696102697102698102699102700102701102702102703102704102705102706102707102708102709102710102711102712102713102714102715102716102717102718102719102720102721102722102723102724102725102726102727102728102729102730102731102732102733102734102735102736102737102738102739102740102741102742102743102744102745102746102747102748102749102750102751102752102753102754102755102756102757102758102759102760102761102762102763102764102765102766102767102768102769102770102771102772102773102774102775102776102777102778102779102780102781102782102783102784102785102786102787102788102789102790102791102792102793102794102795102796102797102798102799102800102801102802102803102804102805102806102807102808102809102810102811102812102813102814102815102816102817102818102819102820102821102822102823102824102825102826102827102828102829102830102831102832102833102834102835102836102837102838102839102840102841102842102843102844102845102846102847102848102849102850102851102852102853102854102855102856102857102858102859102860102861102862102863102864102865102866102867102868102869102870102871102872102873102874102875102876102877102878102879102880102881102882102883102884102885102886102887102888102889102890102891102892102893102894102895102896102897102898102899102900102901102902102903102904102905102906102907102908102909102910102911102912102913102914102915102916102917102918102919102920102921102922102923102924102925102926102927102928102929102930102931102932102933102934102935102936102937102938102939102940102941102942102943102944102945102946102947102948102949102950102951102952102953102954102955102956102957102958102959102960102961102962102963102964102965102966102967102968102969102970102971102972102973102974102975102976102977102978102979102980102981102982102983102984102985102986102987102988102989102990102991102992102993102994102995102996102997102998102999103000103001103002103003103004103005103006103007103008103009103010103011103012103013103014103015103016103017103018103019103020103021103022103023103024103025103026103027103028103029103030103031103032103033103034103035103036103037103038103039103040103041103042103043103044103045103046103047103048103049103050103051103052103053103054103055103056103057103058103059103060103061103062103063103064103065103066103067103068103069103070103071103072103073103074103075103076103077103078103079103080103081103082103083103084103085103086103087103088103089103090103091103092103093103094103095103096103097103098103099103100103101103102103103103104103105103106103107103108103109103110103111103112103113103114103115103116103117103118103119103120103121103122103123103124103125103126103127103128103129103130103131103132103133103134103135103136103137103138103139103140103141103142103143103144103145103146103147103148103149103150103151103152103153103154103155103156103157103158103159103160103161103162103163103164103165103166103167103168103169103170103171103172103173103174103175103176103177103178103179103180103181103182103183103184103185103186103187103188103189103190103191103192103193103194103195103196103197103198103199103200103201103202103203103204103205103206103207103208103209103210103211103212103213103214103215103216103217103218103219103220103221103222103223103224103225103226103227103228103229103230103231103232103233103234103235103236103237103238103239103240103241103242103243103244103245103246103247103248103249103250103251103252103253103254103255103256103257103258103259103260103261103262103263103264103265103266103267103268103269103270103271103272103273103274103275103276103277103278103279103280103281103282103283103284103285103286103287103288103289103290103291103292103293103294103295103296103297103298103299103300103301103302103303103304103305103306103307103308103309103310103311103312103313103314103315103316103317103318103319103320103321103322103323103324103325103326103327103328103329103330103331103332103333103334103335103336103337103338103339103340103341103342103343103344103345103346103347103348103349103350103351103352103353103354103355103356103357103358103359103360103361103362103363103364103365103366103367103368103369103370103371103372103373103374103375103376103377103378103379103380103381103382103383103384103385103386103387103388103389103390103391103392103393103394103395103396103397103398103399103400103401103402103403103404103405103406103407103408103409103410103411103412103413103414103415103416103417103418103419103420103421103422103423103424103425103426103427103428103429103430103431103432103433103434103435103436103437103438103439103440103441103442103443103444103445103446103447103448103449103450103451103452103453103454103455103456103457103458103459103460103461103462103463103464103465103466103467103468103469103470103471103472103473103474103475103476103477103478103479103480103481103482103483103484103485103486103487103488103489103490103491103492103493103494103495103496103497103498103499103500103501103502103503103504103505103506103507103508103509103510103511103512103513103514103515103516103517103518103519103520103521103522103523103524103525103526103527103528103529103530103531103532103533103534103535103536103537103538103539103540103541103542103543103544103545103546103547103548103549103550103551103552103553103554103555103556103557103558103559103560103561103562103563103564103565103566103567103568103569103570103571103572103573103574103575103576103577103578103579103580103581103582103583103584103585103586103587103588103589103590103591103592103593103594103595103596103597103598103599103600103601103602103603103604103605103606103607103608103609103610103611103612103613103614103615103616103617103618103619103620103621103622103623103624103625103626103627103628103629103630103631103632103633103634103635103636103637103638103639103640103641103642103643103644103645103646103647103648103649103650103651103652103653103654103655103656103657103658103659103660103661103662103663103664103665103666103667103668103669103670103671103672103673103674103675103676103677103678103679103680103681103682103683103684103685103686103687103688103689103690103691103692103693103694103695103696103697103698103699103700103701103702103703103704103705103706103707103708103709103710103711103712103713103714103715103716103717103718103719103720103721103722103723103724103725103726103727103728103729103730103731103732103733103734103735103736103737103738103739103740103741103742103743103744103745103746103747103748103749103750103751103752103753103754103755103756103757103758103759103760103761103762103763103764103765103766103767103768103769103770103771103772103773103774103775103776103777103778103779103780103781103782103783103784103785103786103787103788103789103790103791103792103793103794103795103796103797103798103799103800103801103802103803103804103805103806103807103808103809103810103811103812103813103814103815103816103817103818103819103820103821103822103823103824103825103826103827103828103829103830103831103832103833103834103835103836103837103838103839103840103841103842103843103844103845103846103847103848103849103850103851103852103853103854103855103856103857103858103859103860103861103862103863103864103865103866103867103868103869103870103871103872103873103874103875103876103877103878103879103880103881103882103883103884103885103886103887103888103889103890103891103892103893103894103895103896103897103898103899103900103901103902103903103904103905103906103907103908103909103910103911103912103913103914103915103916103917103918103919103920103921103922103923103924103925103926103927103928103929103930103931103932103933103934103935103936103937103938103939103940103941103942103943103944103945103946103947103948103949103950103951103952103953103954103955103956103957103958103959103960103961103962103963103964103965103966103967103968103969103970103971103972103973103974103975103976103977103978103979103980103981103982103983103984103985103986103987103988103989103990103991103992103993103994103995103996103997103998103999104000104001104002104003104004104005104006104007104008104009104010104011104012104013104014104015104016104017104018104019104020104021104022104023104024104025104026104027104028104029104030104031104032104033104034104035104036104037104038104039104040104041104042104043104044104045104046104047104048104049104050104051104052104053104054104055104056104057104058104059104060104061104062104063104064104065104066104067104068104069104070104071104072104073104074104075104076104077104078104079104080104081104082104083104084104085104086104087104088104089104090104091104092104093104094104095104096104097104098104099104100104101104102104103104104104105104106104107104108104109104110104111104112104113104114104115104116104117104118104119104120104121104122104123104124104125104126104127104128104129104130104131104132104133104134104135104136104137104138104139104140104141104142104143104144104145104146104147104148104149104150104151104152104153104154104155104156104157104158104159104160104161104162104163104164104165104166104167104168104169104170104171104172104173104174104175104176104177104178104179104180104181104182104183104184104185104186104187104188104189104190104191104192104193104194104195104196104197104198104199104200104201104202104203104204104205104206104207104208104209104210104211104212104213104214104215104216104217104218104219104220104221104222104223104224104225104226104227104228104229104230104231104232104233104234104235104236104237104238104239104240104241104242104243104244104245104246104247104248104249104250104251104252104253104254104255104256104257104258104259104260104261104262104263104264104265104266104267104268104269104270104271104272104273104274104275104276104277104278104279104280104281104282104283104284104285104286104287104288104289104290104291104292104293104294104295104296104297104298104299104300104301104302104303104304104305104306104307104308104309104310104311104312104313104314104315104316104317104318104319104320104321104322104323104324104325104326104327104328104329104330104331104332104333104334104335104336104337104338104339104340104341104342104343104344104345104346104347104348104349104350104351104352104353104354104355104356104357104358104359104360104361104362104363104364104365104366104367104368104369104370104371104372104373104374104375104376104377104378104379104380104381104382104383104384104385104386104387104388104389104390104391104392104393104394104395104396104397104398104399104400104401104402104403104404104405104406104407104408104409104410104411104412104413104414104415104416104417104418104419104420104421104422104423104424104425104426104427104428104429104430104431104432104433104434104435104436104437104438104439104440104441104442104443104444104445104446104447104448104449104450104451104452104453104454104455104456104457104458104459104460104461104462104463104464104465104466104467104468104469104470104471104472104473104474104475104476104477104478104479104480104481104482104483104484104485104486104487104488104489104490104491104492104493104494104495104496104497104498104499104500104501104502104503104504104505104506104507104508104509104510104511104512104513104514104515104516104517104518104519104520104521104522104523104524104525104526104527104528104529104530104531104532104533104534104535104536104537104538104539104540104541104542104543104544104545104546104547104548104549104550104551104552104553104554104555104556104557104558104559104560104561104562104563104564104565104566104567104568104569104570104571104572104573104574104575104576104577104578104579104580104581104582104583104584104585104586104587104588104589104590104591104592104593104594104595104596104597104598104599104600104601104602104603104604104605104606104607104608104609104610104611104612104613104614104615104616104617104618104619104620104621104622104623104624104625104626104627104628104629104630104631104632104633104634104635104636104637104638104639104640104641104642104643104644104645104646104647104648104649104650104651104652104653104654104655104656104657104658104659104660104661104662104663104664104665104666104667104668104669104670104671104672104673104674104675104676104677104678104679104680104681104682104683104684104685104686104687104688104689104690104691104692104693104694104695104696104697104698104699104700104701104702104703104704104705104706104707104708104709104710104711104712104713104714104715104716104717104718104719104720104721104722104723104724104725104726104727104728104729104730104731104732104733104734104735104736104737104738104739104740104741104742104743104744104745104746104747104748104749104750104751104752104753104754104755104756104757104758104759104760104761104762104763104764104765104766104767104768104769104770104771104772104773104774104775104776104777104778104779104780104781104782104783104784104785104786104787104788104789104790104791104792104793104794104795104796104797104798104799104800104801104802104803104804104805104806104807104808104809104810104811104812104813104814104815104816104817104818104819104820104821104822104823104824104825104826104827104828104829104830104831104832104833104834104835104836104837104838104839104840104841104842104843104844104845104846104847104848104849104850104851104852104853104854104855104856104857104858104859104860104861104862104863104864104865104866104867104868104869104870104871104872104873104874104875104876104877104878104879104880104881104882104883104884104885104886104887104888104889104890104891104892104893104894104895104896104897104898104899104900104901104902104903104904104905104906104907104908104909104910104911104912104913104914104915104916104917104918104919104920104921104922104923104924104925104926104927104928104929104930104931104932104933104934104935104936104937104938104939104940104941104942104943104944104945104946104947104948104949104950104951104952104953104954104955104956104957104958104959104960104961104962104963104964104965104966104967104968104969104970104971104972104973104974104975104976104977104978104979104980104981104982104983104984104985104986104987104988104989104990104991104992104993104994104995104996104997104998104999105000105001105002105003105004105005105006105007105008105009105010105011105012105013105014105015105016105017105018105019105020105021105022105023105024105025105026105027105028105029105030105031105032105033105034105035105036105037105038105039105040105041105042105043105044105045105046105047105048105049105050105051105052105053105054105055105056105057105058105059105060105061105062105063105064105065105066105067105068105069105070105071105072105073105074105075105076105077105078105079105080105081105082105083105084105085105086105087105088105089105090105091105092105093105094105095105096105097105098105099105100105101105102105103105104105105105106105107105108105109105110105111105112105113105114105115105116105117105118105119105120105121105122105123105124105125105126105127105128105129105130105131105132105133105134105135105136105137105138105139105140105141105142105143105144105145105146105147105148105149105150105151105152105153105154105155105156105157105158105159105160105161105162105163105164105165105166105167105168105169105170105171105172105173105174105175105176105177105178105179105180105181105182105183105184105185105186105187105188105189105190105191105192105193105194105195105196105197105198105199105200105201105202105203105204105205105206105207105208105209105210105211105212105213105214105215105216105217105218105219105220105221105222105223105224105225105226105227105228105229105230105231105232105233105234105235105236105237105238105239105240105241105242105243105244105245105246105247105248105249105250105251105252105253105254105255105256105257105258105259105260105261105262105263105264105265105266105267105268105269105270105271105272105273105274105275105276105277105278105279105280105281105282105283105284105285105286105287105288105289105290105291105292105293105294105295105296105297105298105299105300105301105302105303105304105305105306105307105308105309105310105311105312105313105314105315105316105317105318105319105320105321105322105323105324105325105326105327105328105329105330105331105332105333105334105335105336105337105338105339105340105341105342105343105344105345105346105347105348105349105350105351105352105353105354105355105356105357105358105359105360105361105362105363105364105365105366105367105368105369105370105371105372105373105374105375105376105377105378105379105380105381105382105383105384105385105386105387105388105389105390105391105392105393105394105395105396105397105398105399105400105401105402105403105404105405105406105407105408105409105410105411105412105413105414105415105416105417105418105419105420105421105422105423105424105425105426105427105428105429105430105431105432105433105434105435105436105437105438105439105440105441105442105443105444105445105446105447105448105449105450105451105452105453105454105455105456105457105458105459105460105461105462105463105464105465105466105467105468105469105470105471105472105473105474105475105476105477105478105479105480105481105482105483105484105485105486105487105488105489105490105491105492105493105494105495105496105497105498105499105500105501105502105503105504105505105506105507105508105509105510105511105512105513105514105515105516105517105518105519105520105521105522105523105524105525105526105527105528105529105530105531105532105533105534105535105536105537105538105539105540105541105542105543105544105545105546105547105548105549105550105551105552105553105554105555105556105557105558105559105560105561105562105563105564105565105566105567105568105569105570105571105572105573105574105575105576105577105578105579105580105581105582105583105584105585105586105587105588105589105590105591105592105593105594105595105596105597105598105599105600105601105602105603105604105605105606105607105608105609105610105611105612105613105614105615105616105617105618105619105620105621105622105623105624105625105626105627105628105629105630105631105632105633105634105635105636105637105638105639105640105641105642105643105644105645105646105647105648105649105650105651105652105653105654105655105656105657105658105659105660105661105662105663105664105665105666105667105668105669105670105671105672105673105674105675105676105677105678105679105680105681105682105683105684105685105686105687105688105689105690105691105692105693105694105695105696105697105698105699105700105701105702105703105704105705105706105707105708105709105710105711105712105713105714105715105716105717105718105719105720105721105722105723105724105725105726105727105728105729105730105731105732105733105734105735105736105737105738105739105740105741105742105743105744105745105746105747105748105749105750105751105752105753105754105755105756105757105758105759105760105761105762105763105764105765105766105767105768105769105770105771105772105773105774105775105776105777105778105779105780105781105782105783105784105785105786105787105788105789105790105791105792105793105794105795105796105797105798105799105800105801105802105803105804105805105806105807105808105809105810105811105812105813105814105815105816105817105818105819105820105821105822105823105824105825105826105827105828105829105830105831105832105833105834105835105836105837105838105839105840105841105842105843105844105845105846105847105848105849105850105851105852105853105854105855105856105857105858105859105860105861105862105863105864105865105866105867105868105869105870105871105872105873105874105875105876105877105878105879105880105881105882105883105884105885105886105887105888105889105890105891105892105893105894105895105896105897105898105899105900105901105902105903105904105905105906105907105908105909105910105911105912105913105914105915105916105917105918105919105920105921105922105923105924105925105926105927105928105929105930105931105932105933105934105935105936105937105938105939105940105941105942105943105944105945105946105947105948105949105950105951105952105953105954105955105956105957105958105959105960105961105962105963105964105965105966105967105968105969105970105971105972105973105974105975105976105977105978105979105980105981105982105983105984105985105986105987105988105989105990105991105992105993105994105995105996105997105998105999106000106001106002106003106004106005106006106007106008106009106010106011106012106013106014106015106016106017106018106019106020106021106022106023106024106025106026106027106028106029106030106031106032106033106034106035106036106037106038106039106040106041106042106043106044106045106046106047106048106049106050106051106052106053106054106055106056106057106058106059106060106061106062106063106064106065106066106067106068106069106070106071106072106073106074106075106076106077106078106079106080106081106082106083106084106085106086106087106088106089106090106091106092106093106094106095106096106097106098106099106100106101106102106103106104106105106106106107106108106109106110106111106112106113106114106115106116106117106118106119106120106121106122106123106124106125106126106127106128106129106130106131106132106133106134106135106136106137106138106139106140106141106142106143106144106145106146106147106148106149106150106151106152106153106154106155106156106157106158106159106160106161106162106163106164106165106166106167106168106169106170106171106172106173106174106175106176106177106178106179106180106181106182106183106184106185106186106187106188106189106190106191106192106193106194106195106196106197106198106199106200106201106202106203106204106205106206106207106208106209106210106211106212106213106214106215106216106217106218106219106220106221106222106223106224106225106226106227106228106229106230106231106232106233106234106235106236106237106238106239106240106241106242106243106244106245106246106247106248106249106250106251106252106253106254106255106256106257106258106259106260106261106262106263106264106265106266106267106268106269106270106271106272106273106274106275106276106277106278106279106280106281106282106283106284106285106286106287106288106289106290106291106292106293106294106295106296106297106298106299106300106301106302106303106304106305106306106307106308106309106310106311106312106313106314106315106316106317106318106319106320106321106322106323106324106325106326106327106328106329106330106331106332106333106334106335106336106337106338106339106340106341106342106343106344106345106346106347106348106349106350106351106352106353106354106355106356106357106358106359106360106361106362106363106364106365106366106367106368106369106370106371106372106373106374106375106376106377106378106379106380106381106382106383106384106385106386106387106388106389106390106391106392106393106394106395106396106397106398106399106400106401106402106403106404106405106406106407106408106409106410106411106412106413106414106415106416106417106418106419106420106421106422106423106424106425106426106427106428106429106430106431106432106433106434106435106436106437106438106439106440106441106442106443106444106445106446106447106448106449106450106451106452106453106454106455106456106457106458106459106460106461106462106463106464106465106466106467106468106469106470106471106472106473106474106475106476106477106478106479106480106481106482106483106484106485106486106487106488106489106490106491106492106493106494106495106496106497106498106499106500106501106502106503106504106505106506106507106508106509106510106511106512106513106514106515106516106517106518106519106520106521106522106523106524106525106526106527106528106529106530106531106532106533106534106535106536106537106538106539106540106541106542106543106544106545106546106547106548106549106550106551106552106553106554106555106556106557106558106559106560106561106562106563106564106565106566106567106568106569106570106571106572106573106574106575106576106577106578106579106580106581106582106583106584106585106586106587106588106589106590106591106592106593106594106595106596106597106598106599106600106601106602106603106604106605106606106607106608106609106610106611106612106613106614106615106616106617106618106619106620106621106622106623106624106625106626106627106628106629106630106631106632106633106634106635106636106637106638106639106640106641106642106643106644106645106646106647106648106649106650106651106652106653106654106655106656106657106658106659106660106661106662106663106664106665106666106667106668106669106670106671106672106673106674106675106676106677106678106679106680106681106682106683106684106685106686106687106688106689106690106691106692106693106694106695106696106697106698106699106700106701106702106703106704106705106706106707106708106709106710106711106712106713106714106715106716106717106718106719106720106721106722106723106724106725106726106727106728106729106730106731106732106733106734106735106736106737106738106739106740106741106742106743106744106745106746106747106748106749106750106751106752106753106754106755106756106757106758106759106760106761106762106763106764106765106766106767106768106769106770106771106772106773106774106775106776106777106778106779106780106781106782106783106784106785106786106787106788106789106790106791106792106793106794106795106796106797106798106799106800106801106802106803106804106805106806106807106808106809106810106811106812106813106814106815106816106817106818106819106820106821106822106823106824106825106826106827106828106829106830106831106832106833106834106835106836106837106838106839106840106841106842106843106844106845106846106847106848106849106850106851106852106853106854106855106856106857106858106859106860106861106862106863106864106865106866106867106868106869106870106871106872106873106874106875106876106877106878106879106880106881106882106883106884106885106886106887106888106889106890106891106892106893106894106895106896106897106898106899106900106901106902106903106904106905106906106907106908106909106910106911106912106913106914106915106916106917106918106919106920106921106922106923106924106925106926106927106928106929106930106931106932106933106934106935106936106937106938106939106940106941106942106943106944106945106946106947106948106949106950106951106952106953106954106955106956106957106958106959106960106961106962106963106964106965106966106967106968106969106970106971106972106973106974106975106976106977106978106979106980106981106982106983106984106985106986106987106988106989106990106991106992106993106994106995106996106997106998106999107000107001107002107003107004107005107006107007107008107009107010107011107012107013107014107015107016107017107018107019107020107021107022107023107024107025107026107027107028107029107030107031107032107033107034107035107036107037107038107039107040107041107042107043107044107045107046107047107048107049107050107051107052107053107054107055107056107057107058107059107060107061107062107063107064107065107066107067107068107069107070107071107072107073107074107075107076107077107078107079107080107081107082107083107084107085107086107087107088107089107090107091107092107093107094107095107096107097107098107099107100107101107102107103107104107105107106107107107108107109107110107111107112107113107114107115107116107117107118107119107120107121107122107123107124107125107126107127107128107129107130107131107132107133107134107135107136107137107138107139107140107141107142107143107144107145107146107147107148107149107150107151107152107153107154107155107156107157107158107159107160107161107162107163107164107165107166107167107168107169107170107171107172107173107174107175107176107177107178107179107180107181107182107183107184107185107186107187107188107189107190107191107192107193107194107195107196107197107198107199107200107201107202107203107204107205107206107207107208107209107210107211107212107213107214107215107216107217107218107219107220107221107222107223107224107225107226107227107228107229107230107231107232107233107234107235107236107237107238107239107240107241107242107243107244107245107246107247107248107249107250107251107252107253107254107255107256107257107258107259107260107261107262107263107264107265107266107267107268107269107270107271107272107273107274107275107276107277107278107279107280107281107282107283107284107285107286107287107288107289107290107291107292107293107294107295107296107297107298107299107300107301107302107303107304107305107306107307107308107309107310107311107312107313107314107315107316107317107318107319107320107321107322107323107324107325107326107327107328107329107330107331107332107333107334107335107336107337107338107339107340107341107342107343107344107345107346107347107348107349107350107351107352107353107354107355107356107357107358107359107360107361107362107363107364107365107366107367107368107369107370107371107372107373107374107375107376107377107378107379107380107381107382107383107384107385107386107387107388107389107390107391107392107393107394107395107396107397107398107399107400107401107402107403107404107405107406107407107408107409107410107411107412107413107414107415107416107417107418107419107420107421107422107423107424107425107426107427107428107429107430107431107432107433107434107435107436107437107438107439107440107441107442107443107444107445107446107447107448107449107450107451107452107453107454107455107456107457107458107459107460107461107462107463107464107465107466107467107468107469107470107471107472107473107474107475107476107477107478107479107480107481107482107483107484107485107486107487107488107489107490107491107492107493107494107495107496107497107498107499107500107501107502107503107504107505107506107507107508107509107510107511107512107513107514107515107516107517107518107519107520107521107522107523107524107525107526107527107528107529107530107531107532107533107534107535107536107537107538107539107540107541107542107543107544107545107546107547107548107549107550107551107552107553107554107555107556107557107558107559107560107561107562107563107564107565107566107567107568107569107570107571107572107573107574107575107576107577107578107579107580107581107582107583107584107585107586107587107588107589107590107591107592107593107594107595107596107597107598107599107600107601107602107603107604107605107606107607107608107609107610107611107612107613107614107615107616107617107618107619107620107621107622107623107624107625107626107627107628107629107630107631107632107633107634107635107636107637107638107639107640107641107642107643107644107645107646107647107648107649107650107651107652107653107654107655107656107657107658107659107660107661107662107663107664107665107666107667107668107669107670107671107672107673107674107675107676107677107678107679107680107681107682107683107684107685107686107687107688107689107690107691107692107693107694107695107696107697107698107699107700107701107702107703107704107705107706107707107708107709107710107711107712107713107714107715107716107717107718107719107720107721107722107723107724107725107726107727107728107729107730107731107732107733107734107735107736107737107738107739107740107741107742107743107744107745107746107747107748107749107750107751107752107753107754107755107756107757107758107759107760107761107762107763107764107765107766107767107768107769107770107771107772107773107774107775107776107777107778107779107780107781107782107783107784107785107786107787107788107789107790107791107792107793107794107795107796107797107798107799107800107801107802107803107804107805107806107807107808107809107810107811107812107813107814107815107816107817107818107819107820107821107822107823107824107825107826107827107828107829107830107831107832107833107834107835107836107837107838107839107840107841107842107843107844107845107846107847107848107849107850107851107852107853107854107855107856107857107858107859107860107861107862107863107864107865107866107867107868107869107870107871107872107873107874107875107876107877107878107879107880107881107882107883107884107885107886107887107888107889107890107891107892107893107894107895107896107897107898107899107900107901107902107903107904107905107906107907107908107909107910107911107912107913107914107915107916107917107918107919107920107921107922107923107924107925107926107927107928107929107930107931107932107933107934107935107936107937107938107939107940107941107942107943107944107945107946107947107948107949107950107951107952107953107954107955107956107957107958107959107960107961107962107963107964107965107966107967107968107969107970107971107972107973107974107975107976107977107978107979107980107981107982107983107984107985107986107987107988107989107990107991107992107993107994107995107996107997107998107999108000108001108002108003108004108005108006108007108008108009108010108011108012108013108014108015108016108017108018108019108020108021108022108023108024108025108026108027108028108029108030108031108032108033108034108035108036108037108038108039108040108041108042108043108044108045108046108047108048108049108050108051108052108053108054108055108056108057108058108059108060108061108062108063108064108065108066108067108068108069108070108071108072108073108074108075108076108077108078108079108080108081108082108083108084108085108086108087108088108089108090108091108092108093108094108095108096108097108098108099108100108101108102108103108104108105108106108107108108108109108110108111108112108113108114108115108116108117108118108119108120108121108122108123108124108125108126108127108128108129108130108131108132108133108134108135108136108137108138108139108140108141108142108143108144108145108146108147108148108149108150108151108152108153108154108155108156108157108158108159108160108161108162108163108164108165108166108167108168108169108170108171108172108173108174108175108176108177108178108179108180108181108182108183108184108185108186108187108188108189108190108191108192108193108194108195108196108197108198108199108200108201108202108203108204108205108206108207108208108209108210108211108212108213108214108215108216108217108218108219108220108221108222108223108224108225108226108227108228108229108230108231108232108233108234108235108236108237108238108239108240108241108242108243108244108245108246108247108248108249108250108251108252108253108254108255108256108257108258108259108260108261108262108263108264108265108266108267108268108269108270108271108272108273108274108275108276108277108278108279108280108281108282108283108284108285108286108287108288108289108290108291108292108293108294108295108296108297108298108299108300108301108302108303108304108305108306108307108308108309108310108311108312108313108314108315108316108317108318108319108320108321108322108323108324108325108326108327108328108329108330108331108332108333108334108335108336108337108338108339108340108341108342108343108344108345108346108347108348108349108350108351108352108353108354108355108356108357108358108359108360108361108362108363108364108365108366108367108368108369108370108371108372108373108374108375108376108377108378108379108380108381108382108383108384108385108386108387108388108389108390108391108392108393108394108395108396108397108398108399108400108401108402108403108404108405108406108407108408108409108410108411108412108413108414108415108416108417108418108419108420108421108422108423108424108425108426108427108428108429108430108431108432108433108434108435108436108437108438108439108440108441108442108443108444108445108446108447108448108449108450108451108452108453108454108455108456108457108458108459108460108461108462108463108464108465108466108467108468108469108470108471108472108473108474108475108476108477108478108479108480108481108482108483108484108485108486108487108488108489108490108491108492108493108494108495108496108497108498108499108500108501108502108503108504108505108506108507108508108509108510108511108512108513108514108515108516108517108518108519108520108521108522108523108524108525108526108527108528108529108530108531108532108533108534108535108536108537108538108539108540108541108542108543108544108545108546108547108548108549108550108551108552108553108554108555108556108557108558108559108560108561108562108563108564108565108566108567108568108569108570108571108572108573108574108575108576108577108578108579108580108581108582108583108584108585108586108587108588108589108590108591108592108593108594108595108596108597108598108599108600108601108602108603108604108605108606108607108608108609108610108611108612108613108614108615108616108617108618108619108620108621108622108623108624108625108626108627108628108629108630108631108632108633108634108635108636108637108638108639108640108641108642108643108644108645108646108647108648108649108650108651108652108653108654108655108656108657108658108659108660108661108662108663108664108665108666108667108668108669108670108671108672108673108674108675108676108677108678108679108680108681108682108683108684108685108686108687108688108689108690108691108692108693108694108695108696108697108698108699108700108701108702108703108704108705108706108707108708108709108710108711108712108713108714108715108716108717108718108719108720108721108722108723108724108725108726108727108728108729108730108731108732108733108734108735108736108737108738108739108740108741108742108743108744108745108746108747108748108749108750108751108752108753108754108755108756108757108758108759108760108761108762108763108764108765108766108767108768108769108770108771108772108773108774108775108776108777108778108779108780108781108782108783108784108785108786108787108788108789108790108791108792108793108794108795108796108797108798108799108800108801108802108803108804108805108806108807108808108809108810108811108812108813108814108815108816108817108818108819108820108821108822108823108824108825108826108827108828108829108830108831108832108833108834108835108836108837108838108839108840108841108842108843108844108845108846108847108848108849108850108851108852108853108854108855108856108857108858108859108860108861108862108863108864108865108866108867108868108869108870108871108872108873108874108875108876108877108878108879108880108881108882108883108884108885108886108887108888108889108890108891108892108893108894108895108896108897108898108899108900108901108902108903108904108905108906108907108908108909108910108911108912108913108914108915108916108917108918108919108920108921108922108923108924108925108926108927108928108929108930108931108932108933108934108935108936108937108938108939108940108941108942108943108944108945108946108947108948108949108950108951108952108953108954108955108956108957108958108959108960108961108962108963108964108965108966108967108968108969108970108971108972108973108974108975108976108977108978108979108980108981108982108983108984108985108986108987108988108989108990108991108992108993108994108995108996108997108998108999109000109001109002109003109004109005109006109007109008109009109010109011109012109013109014109015109016109017109018109019109020109021109022109023109024109025109026109027109028109029109030109031109032109033109034109035109036109037109038109039109040109041109042109043109044109045109046109047109048109049109050109051109052109053109054109055109056109057109058109059109060109061109062109063109064109065109066109067109068109069109070109071109072109073109074109075109076109077109078109079109080109081109082109083109084109085109086109087109088109089109090109091109092109093109094109095109096109097109098109099109100109101109102109103109104109105109106109107109108109109109110109111109112109113109114109115109116109117109118109119109120109121109122109123109124109125109126109127109128109129109130109131109132109133109134109135109136109137109138109139109140109141109142109143109144109145109146109147109148109149109150109151109152109153109154109155109156109157109158109159109160109161109162109163109164109165109166109167109168109169109170109171109172109173109174109175109176109177109178109179109180109181109182109183109184109185109186109187109188109189109190109191109192109193109194109195109196109197109198109199109200109201109202109203109204109205109206109207109208109209109210109211109212109213109214109215109216109217109218109219109220109221109222109223109224109225109226109227109228109229109230109231109232109233109234109235109236109237109238109239109240109241109242109243109244109245109246109247109248109249109250109251109252109253109254109255109256109257109258109259109260109261109262109263109264109265109266109267109268109269109270109271109272109273109274109275109276109277109278109279109280109281109282109283109284109285109286109287109288109289109290109291109292109293109294109295109296109297109298109299109300109301109302109303109304109305109306109307109308109309109310109311109312109313109314109315109316109317109318109319109320109321109322109323109324109325109326109327109328109329109330109331109332109333109334109335109336109337109338109339109340109341109342109343109344109345109346109347109348109349109350109351109352109353109354109355109356109357109358109359109360109361109362109363109364109365109366109367109368109369109370109371109372109373109374109375109376109377109378109379109380109381109382109383109384109385109386109387109388109389109390109391109392109393109394109395109396109397109398109399109400109401109402109403109404109405109406109407109408109409109410109411109412109413109414109415109416109417109418109419109420109421109422109423109424109425109426109427109428109429109430109431109432109433109434109435109436109437109438109439109440109441109442109443109444109445109446109447109448109449109450109451109452109453109454109455109456109457109458109459109460109461109462109463109464109465109466109467109468109469109470109471109472109473109474109475109476109477109478109479109480109481109482109483109484109485109486109487109488109489109490109491109492109493109494109495109496109497109498109499109500109501109502109503109504109505109506109507109508109509109510109511109512109513109514109515109516109517109518109519109520109521109522109523109524109525109526109527109528109529109530109531109532109533109534109535109536109537109538109539109540109541109542109543109544109545109546109547109548109549109550109551109552109553109554109555109556109557109558109559109560109561109562109563109564109565109566109567109568109569109570109571109572109573109574109575109576109577109578109579109580109581109582109583109584109585109586109587109588109589109590109591109592109593109594109595109596109597109598109599109600109601109602109603109604109605109606109607109608109609109610109611109612109613109614109615109616109617109618109619109620109621109622109623109624109625109626109627109628109629109630109631109632109633109634109635109636109637109638109639109640109641109642109643109644109645109646109647109648109649109650109651109652109653109654109655109656109657109658109659109660109661109662109663109664109665109666109667109668109669109670109671109672109673109674109675109676109677109678109679109680109681109682109683109684109685109686109687109688109689109690109691109692109693109694109695109696109697109698109699109700109701109702109703109704109705109706109707109708109709109710109711109712109713109714109715109716109717109718109719109720109721109722109723109724109725109726109727109728109729109730109731109732109733109734109735109736109737109738109739109740109741109742109743109744109745109746109747109748109749109750109751109752109753109754109755109756109757109758109759109760109761109762109763109764109765109766109767109768109769109770109771109772109773109774109775109776109777109778109779109780109781109782109783109784109785109786109787109788109789109790109791109792109793109794109795109796109797109798109799109800109801109802109803109804109805109806109807109808109809109810109811109812109813109814109815109816109817109818109819109820109821109822109823109824109825109826109827109828109829109830109831109832109833109834109835109836109837109838109839109840109841109842109843109844109845109846109847109848109849109850109851109852109853109854109855109856109857109858109859109860109861109862109863109864109865109866109867109868109869109870109871109872109873109874109875109876109877109878109879109880109881109882109883109884109885109886109887109888109889109890109891109892109893109894109895109896109897109898109899109900109901109902109903109904109905109906109907109908109909109910109911109912109913109914109915109916109917109918109919109920109921109922109923109924109925109926109927109928109929109930109931109932109933109934109935109936109937109938109939109940109941109942109943109944109945109946109947109948109949109950109951109952109953109954109955109956109957109958109959109960109961109962109963109964109965109966109967109968109969109970109971109972109973109974109975109976109977109978109979109980109981109982109983109984109985109986109987109988109989109990109991109992109993109994109995109996109997109998109999110000110001110002110003110004110005110006110007110008110009110010110011110012110013110014110015110016110017110018110019110020110021110022110023110024110025110026110027110028110029110030110031110032110033110034110035110036110037110038110039110040110041110042110043110044110045110046110047110048110049110050110051110052110053110054110055110056110057110058110059110060110061110062110063110064110065110066110067110068110069110070110071110072110073110074110075110076110077110078110079110080110081110082110083110084110085110086110087110088110089110090110091110092110093110094110095110096110097110098110099110100110101110102110103110104110105110106110107110108110109110110110111110112110113110114110115110116110117110118110119110120110121110122110123110124110125110126110127110128110129110130110131110132110133110134110135110136110137110138110139110140110141110142110143110144110145110146110147110148110149110150110151110152110153110154110155110156110157110158110159110160110161110162110163110164110165110166110167110168110169110170110171110172110173110174110175110176110177110178110179110180110181110182110183110184110185110186110187110188110189110190110191110192110193110194110195110196110197110198110199110200110201110202110203110204110205110206110207110208110209110210110211110212110213110214110215110216110217110218110219110220110221110222110223110224110225110226110227110228110229110230110231110232110233110234110235110236110237110238110239110240110241110242110243110244110245110246110247110248110249110250110251110252110253110254110255110256110257110258110259110260110261110262110263110264110265110266110267110268110269110270110271110272110273110274110275110276110277110278110279110280110281110282110283110284110285110286110287110288110289110290110291110292110293110294110295110296110297110298110299110300110301110302110303110304110305110306110307110308110309110310110311110312110313110314110315110316110317110318110319110320110321110322110323110324110325110326110327110328110329110330110331110332110333110334110335110336110337110338110339110340110341110342110343110344110345110346110347110348110349110350110351110352110353110354110355110356110357110358110359110360110361110362110363110364110365110366110367110368110369110370110371110372110373110374110375110376110377110378110379110380110381110382110383110384110385110386110387110388110389110390110391110392110393110394110395110396110397110398110399110400110401110402110403110404110405110406110407110408110409110410110411110412110413110414110415110416110417110418110419110420110421110422110423110424110425110426110427110428110429110430110431110432110433110434110435110436110437110438110439110440110441110442110443110444110445110446110447110448110449110450110451110452110453110454110455110456110457110458110459110460110461110462110463110464110465110466110467110468110469110470110471110472110473110474110475110476110477110478110479110480110481110482110483110484110485110486110487110488110489110490110491110492110493110494110495110496110497110498110499110500110501110502110503110504110505110506110507110508110509110510110511110512110513110514110515110516110517110518110519110520110521110522110523110524110525110526110527110528110529110530110531110532110533110534110535110536110537110538110539110540110541110542110543110544110545110546110547110548110549110550110551110552110553110554110555110556110557110558110559110560110561110562110563110564110565110566110567110568110569110570110571110572110573110574110575110576110577110578110579110580110581110582110583110584110585110586110587110588110589110590110591110592110593110594110595110596110597110598110599110600110601110602110603110604110605110606110607110608110609110610110611110612110613110614110615110616110617110618110619110620110621110622110623110624110625110626110627110628110629110630110631110632110633110634110635110636110637110638110639110640110641110642110643110644110645110646110647110648110649110650110651110652110653110654110655110656110657110658110659110660110661110662110663110664110665110666110667110668110669110670110671110672110673110674110675110676110677110678110679110680110681110682110683110684110685110686110687110688110689110690110691110692110693110694110695110696110697110698110699110700110701110702110703110704110705110706110707110708110709110710110711110712110713110714110715110716110717110718110719110720110721110722110723110724110725110726110727110728110729110730110731110732110733110734110735110736110737110738110739110740110741110742110743110744110745110746110747110748110749110750110751110752110753110754110755110756110757110758110759110760110761110762110763110764110765110766110767110768110769110770110771110772110773110774110775110776110777110778110779110780110781110782110783110784110785110786110787110788110789110790110791110792110793110794110795110796110797110798110799110800110801110802110803110804110805110806110807110808110809110810110811110812110813110814110815110816110817110818110819110820110821110822110823110824110825110826110827110828110829110830110831110832110833110834110835110836110837110838110839110840110841110842110843110844110845110846110847110848110849110850110851110852110853110854110855110856110857110858110859110860110861110862110863110864110865110866110867110868110869110870110871110872110873110874110875110876110877110878110879110880110881110882110883110884110885110886110887110888110889110890110891110892110893110894110895110896110897110898110899110900110901110902110903110904110905110906110907110908110909110910110911110912110913110914110915110916110917110918110919110920110921110922110923110924110925110926110927110928110929110930110931110932110933110934110935110936110937110938110939110940110941110942110943110944110945110946110947110948110949110950110951110952110953110954110955110956110957110958110959110960110961110962110963110964110965110966110967110968110969110970110971110972110973110974110975110976110977110978110979110980110981110982110983110984110985110986110987110988110989110990110991110992110993110994110995110996110997110998110999111000111001111002111003111004111005111006111007111008111009111010111011111012111013111014111015111016111017111018111019111020111021111022111023111024111025111026111027111028111029111030111031111032111033111034111035111036111037111038111039111040111041111042111043111044111045111046111047111048111049111050111051111052111053111054111055111056111057111058111059111060111061111062111063111064111065111066111067111068111069111070111071111072111073111074111075111076111077111078111079111080111081111082111083111084111085111086111087111088111089111090111091111092111093111094111095111096111097111098111099111100111101111102111103111104111105111106111107111108111109111110111111111112111113111114111115111116111117111118111119111120111121111122111123111124111125111126111127111128111129111130111131111132111133111134111135111136111137111138111139111140111141111142111143111144111145111146111147111148111149111150111151111152111153111154111155111156111157111158111159111160111161111162111163111164111165111166111167111168111169111170111171111172111173111174111175111176111177111178111179111180111181111182111183111184111185111186111187111188111189111190111191111192111193111194111195111196111197111198111199111200111201111202111203111204111205111206111207111208111209111210111211111212111213111214111215111216111217111218111219111220111221111222111223111224111225111226111227111228111229111230111231111232111233111234111235111236111237111238111239111240111241111242111243111244111245111246111247111248111249111250111251111252111253111254111255111256111257111258111259111260111261111262111263111264111265111266111267111268111269111270111271111272111273111274111275111276111277111278111279111280111281111282111283111284111285111286111287111288111289111290111291111292111293111294111295111296111297111298111299111300111301111302111303111304111305111306111307111308111309111310111311111312111313111314111315111316111317111318111319111320111321111322111323111324111325111326111327111328111329111330111331111332111333111334111335111336111337111338111339111340111341111342111343111344111345111346111347111348111349111350111351111352111353111354111355111356111357111358111359111360111361111362111363111364111365111366111367111368111369111370111371111372111373111374111375111376111377111378111379111380111381111382111383111384111385111386111387111388111389111390111391111392111393111394111395111396111397111398111399111400111401111402111403111404111405111406111407111408111409111410111411111412111413111414111415111416111417111418111419111420111421111422111423111424111425111426111427111428111429111430111431111432111433111434111435111436111437111438111439111440111441111442111443111444111445111446111447111448111449111450111451111452111453111454111455111456111457111458111459111460111461111462111463111464111465111466111467111468111469111470111471111472111473111474111475111476111477111478111479111480111481111482111483111484111485111486111487111488111489111490111491111492111493111494111495111496111497111498111499111500111501111502111503111504111505111506111507111508111509111510111511111512111513111514111515111516111517111518111519111520111521111522111523111524111525111526111527111528111529111530111531111532111533111534111535111536111537111538111539111540111541111542111543111544111545111546111547111548111549111550111551111552111553111554111555111556111557111558111559111560111561111562111563111564111565111566111567111568111569111570111571111572111573111574111575111576111577111578111579111580111581111582111583111584111585111586111587111588111589111590111591111592111593111594111595111596111597111598111599111600111601111602111603111604111605111606111607111608111609111610111611111612111613111614111615111616111617111618111619111620111621111622111623111624111625111626111627111628111629111630111631111632111633111634111635111636111637111638111639111640111641111642111643111644111645111646111647111648111649111650111651111652111653111654111655111656111657111658111659111660111661111662111663111664111665111666111667111668111669111670111671111672111673111674111675111676111677111678111679111680111681111682111683111684111685111686111687111688111689111690111691111692111693111694111695111696111697111698111699111700111701111702111703111704111705111706111707111708111709111710111711111712111713111714111715111716111717111718111719111720111721111722111723111724111725111726111727111728111729111730111731111732111733111734111735111736111737111738111739111740111741111742111743111744111745111746111747111748111749111750111751111752111753111754111755111756111757111758111759111760111761111762111763111764111765111766111767111768111769111770111771111772111773111774111775111776111777111778111779111780111781111782111783111784111785111786111787111788111789111790111791111792111793111794111795111796111797111798111799111800111801111802111803111804111805111806111807111808111809111810111811111812111813111814111815111816111817111818111819111820111821111822111823111824111825111826111827111828111829111830111831111832111833111834111835111836111837111838111839111840111841111842111843111844111845111846111847111848111849111850111851111852111853111854111855111856111857111858111859111860111861111862111863111864111865111866111867111868111869111870111871111872111873111874111875111876111877111878111879111880111881111882111883111884111885111886111887111888111889111890111891111892111893111894111895111896111897111898111899111900111901111902111903111904111905111906111907111908111909111910111911111912111913111914111915111916111917111918111919111920111921111922111923111924111925111926111927111928111929111930111931111932111933111934111935111936111937111938111939111940111941111942111943111944111945111946111947111948111949111950111951111952111953111954111955111956111957111958111959111960111961111962111963111964111965111966111967111968111969111970111971111972111973111974111975111976111977111978111979111980111981111982111983111984111985111986111987111988111989111990111991111992111993111994111995111996111997111998111999112000112001112002112003112004112005112006112007112008112009112010112011112012112013112014112015112016112017112018112019112020112021112022112023112024112025112026112027112028112029112030112031112032112033112034112035112036112037112038112039112040112041112042112043112044112045112046112047112048112049112050112051112052112053112054112055112056112057112058112059112060112061112062112063112064112065112066112067112068112069112070112071112072112073112074112075112076112077112078112079112080112081112082112083112084112085112086112087112088112089112090112091112092112093112094112095112096112097112098112099112100112101112102112103112104112105112106112107112108112109112110112111112112112113112114112115112116112117112118112119112120112121112122112123112124112125112126112127112128112129112130112131112132112133112134112135112136112137112138112139112140112141112142112143112144112145112146112147112148112149112150112151112152112153112154112155112156112157112158112159112160112161112162112163112164112165112166112167112168112169112170112171112172112173112174112175112176112177112178112179112180112181112182112183112184112185112186112187112188112189112190112191112192112193112194112195112196112197112198112199112200112201112202112203112204112205112206112207112208112209112210112211112212112213112214112215112216112217112218112219112220112221112222112223112224112225112226112227112228112229112230112231112232112233112234112235112236112237112238112239112240112241112242112243112244112245112246112247112248112249112250112251112252112253112254112255112256112257112258112259112260112261112262112263112264112265112266112267112268112269112270112271112272112273112274112275112276112277112278112279112280112281112282112283112284112285112286112287112288112289112290112291112292112293112294112295112296112297112298112299112300112301112302112303112304112305112306112307112308112309112310112311112312112313112314112315112316112317112318112319112320112321112322112323112324112325112326112327112328112329112330112331112332112333112334112335112336112337112338112339112340112341112342112343112344112345112346112347112348112349112350112351112352112353112354112355112356112357112358112359112360112361112362112363112364112365112366112367112368112369112370112371112372112373112374112375112376112377112378112379112380112381112382112383112384112385112386112387112388112389112390112391112392112393112394112395112396112397112398112399112400112401112402112403112404112405112406112407112408112409112410112411112412112413112414112415112416112417112418112419112420112421112422112423112424112425112426112427112428112429112430112431112432112433112434112435112436112437112438112439112440112441112442112443112444112445112446112447112448112449112450112451112452112453112454112455112456112457112458112459112460112461112462112463112464112465112466112467112468112469112470112471112472112473112474112475112476112477112478112479112480112481112482112483112484112485112486112487112488112489112490112491112492112493112494112495112496112497112498112499112500112501112502112503112504112505112506112507112508112509112510112511112512112513112514112515112516112517112518112519112520112521112522112523112524112525112526112527112528112529112530112531112532112533112534112535112536112537112538112539112540112541112542112543112544112545112546112547112548112549112550112551112552112553112554112555112556112557112558112559112560112561112562112563112564112565112566112567112568112569112570112571112572112573112574112575112576112577112578112579112580112581112582112583112584112585112586112587112588112589112590112591112592112593112594112595112596112597112598112599112600112601112602112603112604112605112606112607112608112609112610112611112612112613112614112615112616112617112618112619112620112621112622112623112624112625112626112627112628112629112630112631112632112633112634112635112636112637112638112639112640112641112642112643112644112645112646112647112648112649112650112651112652112653112654112655112656112657112658112659112660112661112662112663112664112665112666112667112668112669112670112671112672112673112674112675112676112677112678112679112680112681112682112683112684112685112686112687112688112689112690112691112692112693112694112695112696112697112698112699112700112701112702112703112704112705112706112707112708112709112710112711112712112713112714112715112716112717112718112719112720112721112722112723112724112725112726112727112728112729112730112731112732112733112734112735112736112737112738112739112740112741112742112743112744112745112746112747112748112749112750112751112752112753112754112755112756112757112758112759112760112761112762112763112764112765112766112767112768112769112770112771112772112773112774112775112776112777112778112779112780112781112782112783112784112785112786112787112788112789112790112791112792112793112794112795112796112797112798112799112800112801112802112803112804112805112806112807112808112809112810112811112812112813112814112815112816112817112818112819112820112821112822112823112824112825112826112827112828112829112830112831112832112833112834112835112836112837112838112839112840112841112842112843112844112845112846112847112848112849112850112851112852112853112854112855112856112857112858112859112860112861112862112863112864112865112866112867112868112869112870112871112872112873112874112875112876112877112878112879112880112881112882112883112884112885112886112887112888112889112890112891112892112893112894112895112896112897112898112899112900112901112902112903112904112905112906112907112908112909112910112911112912112913112914112915112916112917112918112919112920112921112922112923112924112925112926112927112928112929112930112931112932112933112934112935112936112937112938112939112940112941112942112943112944112945112946112947112948112949112950112951112952112953112954112955112956112957112958112959112960112961112962112963112964112965112966112967112968112969112970112971112972112973112974112975112976112977112978112979112980112981112982112983112984112985112986112987112988112989112990112991112992112993112994112995112996112997112998112999113000113001113002113003113004113005113006113007113008113009113010113011113012113013113014113015113016113017113018113019113020113021113022113023113024113025113026113027113028113029113030113031113032113033113034113035113036113037113038113039113040113041113042113043113044113045113046113047113048113049113050113051113052113053113054113055113056113057113058113059113060113061113062113063113064113065113066113067113068113069113070113071113072113073113074113075113076113077113078113079113080113081113082113083113084113085113086113087113088113089113090113091113092113093113094113095113096113097113098113099113100113101113102113103113104113105113106113107113108113109113110113111113112113113113114113115113116113117113118113119113120113121113122113123113124113125113126113127113128113129113130113131113132113133113134113135113136113137113138113139113140113141113142113143113144113145113146113147113148113149113150113151113152
  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. /** @hidden */
  159. this._bonesComputationForcedToCPU = false;
  160. this._uniformBuffersNames = {};
  161. this._isReady = false;
  162. this._compilationError = "";
  163. this.name = baseName;
  164. if (attributesNamesOrOptions.attributes) {
  165. var options = attributesNamesOrOptions;
  166. this._engine = uniformsNamesOrEngine;
  167. this._attributesNames = options.attributes;
  168. this._uniformsNames = options.uniformsNames.concat(options.samplers);
  169. this._samplers = options.samplers.slice();
  170. this.defines = options.defines;
  171. this.onError = options.onError;
  172. this.onCompiled = options.onCompiled;
  173. this._fallbacks = options.fallbacks;
  174. this._indexParameters = options.indexParameters;
  175. this._transformFeedbackVaryings = options.transformFeedbackVaryings;
  176. if (options.uniformBuffersNames) {
  177. for (var i = 0; i < options.uniformBuffersNames.length; i++) {
  178. this._uniformBuffersNames[options.uniformBuffersNames[i]] = i;
  179. }
  180. }
  181. }
  182. else {
  183. this._engine = engine;
  184. this.defines = defines;
  185. this._uniformsNames = uniformsNamesOrEngine.concat(samplers);
  186. this._samplers = samplers ? samplers.slice() : [];
  187. this._attributesNames = attributesNamesOrOptions;
  188. this.onError = onError;
  189. this.onCompiled = onCompiled;
  190. this._indexParameters = indexParameters;
  191. this._fallbacks = fallbacks;
  192. }
  193. this.uniqueId = Effect._uniqueIdSeed++;
  194. var vertexSource;
  195. var fragmentSource;
  196. if (baseName.vertexElement) {
  197. vertexSource = document.getElementById(baseName.vertexElement);
  198. if (!vertexSource) {
  199. vertexSource = baseName.vertexElement;
  200. }
  201. }
  202. else {
  203. vertexSource = baseName.vertex || baseName;
  204. }
  205. if (baseName.fragmentElement) {
  206. fragmentSource = document.getElementById(baseName.fragmentElement);
  207. if (!fragmentSource) {
  208. fragmentSource = baseName.fragmentElement;
  209. }
  210. }
  211. else {
  212. fragmentSource = baseName.fragment || baseName;
  213. }
  214. this._loadVertexShader(vertexSource, function (vertexCode) {
  215. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  216. _this._processShaderConversion(vertexCodeWithIncludes, false, function (migratedVertexCode) {
  217. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  218. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  219. _this._processShaderConversion(fragmentCodeWithIncludes, true, function (migratedFragmentCode) {
  220. if (baseName) {
  221. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  222. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  223. _this._vertexSourceCode = "#define SHADER_NAME vertex:" + vertex + "\n" + migratedVertexCode;
  224. _this._fragmentSourceCode = "#define SHADER_NAME fragment:" + fragment + "\n" + migratedFragmentCode;
  225. }
  226. else {
  227. _this._vertexSourceCode = migratedVertexCode;
  228. _this._fragmentSourceCode = migratedFragmentCode;
  229. }
  230. _this._prepareEffect();
  231. });
  232. });
  233. });
  234. });
  235. });
  236. });
  237. }
  238. Object.defineProperty(Effect.prototype, "onBindObservable", {
  239. /**
  240. * Observable that will be called when effect is bound.
  241. */
  242. get: function () {
  243. if (!this._onBindObservable) {
  244. this._onBindObservable = new BABYLON.Observable();
  245. }
  246. return this._onBindObservable;
  247. },
  248. enumerable: true,
  249. configurable: true
  250. });
  251. Object.defineProperty(Effect.prototype, "key", {
  252. /**
  253. * Unique key for this effect
  254. */
  255. get: function () {
  256. return this._key;
  257. },
  258. enumerable: true,
  259. configurable: true
  260. });
  261. /**
  262. * If the effect has been compiled and prepared.
  263. * @returns if the effect is compiled and prepared.
  264. */
  265. Effect.prototype.isReady = function () {
  266. return this._isReady;
  267. };
  268. /**
  269. * The engine the effect was initialized with.
  270. * @returns the engine.
  271. */
  272. Effect.prototype.getEngine = function () {
  273. return this._engine;
  274. };
  275. /**
  276. * The compiled webGL program for the effect
  277. * @returns the webGL program.
  278. */
  279. Effect.prototype.getProgram = function () {
  280. return this._program;
  281. };
  282. /**
  283. * The set of names of attribute variables for the shader.
  284. * @returns An array of attribute names.
  285. */
  286. Effect.prototype.getAttributesNames = function () {
  287. return this._attributesNames;
  288. };
  289. /**
  290. * Returns the attribute at the given index.
  291. * @param index The index of the attribute.
  292. * @returns The location of the attribute.
  293. */
  294. Effect.prototype.getAttributeLocation = function (index) {
  295. return this._attributes[index];
  296. };
  297. /**
  298. * Returns the attribute based on the name of the variable.
  299. * @param name of the attribute to look up.
  300. * @returns the attribute location.
  301. */
  302. Effect.prototype.getAttributeLocationByName = function (name) {
  303. var index = this._attributesNames.indexOf(name);
  304. return this._attributes[index];
  305. };
  306. /**
  307. * The number of attributes.
  308. * @returns the numnber of attributes.
  309. */
  310. Effect.prototype.getAttributesCount = function () {
  311. return this._attributes.length;
  312. };
  313. /**
  314. * Gets the index of a uniform variable.
  315. * @param uniformName of the uniform to look up.
  316. * @returns the index.
  317. */
  318. Effect.prototype.getUniformIndex = function (uniformName) {
  319. return this._uniformsNames.indexOf(uniformName);
  320. };
  321. /**
  322. * Returns the attribute based on the name of the variable.
  323. * @param uniformName of the uniform to look up.
  324. * @returns the location of the uniform.
  325. */
  326. Effect.prototype.getUniform = function (uniformName) {
  327. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  328. };
  329. /**
  330. * Returns an array of sampler variable names
  331. * @returns The array of sampler variable neames.
  332. */
  333. Effect.prototype.getSamplers = function () {
  334. return this._samplers;
  335. };
  336. /**
  337. * The error from the last compilation.
  338. * @returns the error string.
  339. */
  340. Effect.prototype.getCompilationError = function () {
  341. return this._compilationError;
  342. };
  343. /**
  344. * Adds a callback to the onCompiled observable and call the callback imediatly if already ready.
  345. * @param func The callback to be used.
  346. */
  347. Effect.prototype.executeWhenCompiled = function (func) {
  348. if (this.isReady()) {
  349. func(this);
  350. return;
  351. }
  352. this.onCompileObservable.add(function (effect) {
  353. func(effect);
  354. });
  355. };
  356. /** @hidden */
  357. Effect.prototype._loadVertexShader = function (vertex, callback) {
  358. if (BABYLON.Tools.IsWindowObjectExist()) {
  359. // DOM element ?
  360. if (vertex instanceof HTMLElement) {
  361. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  362. callback(vertexCode);
  363. return;
  364. }
  365. }
  366. // Base64 encoded ?
  367. if (vertex.substr(0, 7) === "base64:") {
  368. var vertexBinary = window.atob(vertex.substr(7));
  369. callback(vertexBinary);
  370. return;
  371. }
  372. // Is in local store ?
  373. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  374. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  375. return;
  376. }
  377. var vertexShaderUrl;
  378. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  379. vertexShaderUrl = vertex;
  380. }
  381. else {
  382. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  383. }
  384. // Vertex shader
  385. this._engine._loadFile(vertexShaderUrl + ".vertex.fx", callback);
  386. };
  387. /** @hidden */
  388. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  389. if (BABYLON.Tools.IsWindowObjectExist()) {
  390. // DOM element ?
  391. if (fragment instanceof HTMLElement) {
  392. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  393. callback(fragmentCode);
  394. return;
  395. }
  396. }
  397. // Base64 encoded ?
  398. if (fragment.substr(0, 7) === "base64:") {
  399. var fragmentBinary = window.atob(fragment.substr(7));
  400. callback(fragmentBinary);
  401. return;
  402. }
  403. // Is in local store ?
  404. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  405. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  406. return;
  407. }
  408. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  409. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  410. return;
  411. }
  412. var fragmentShaderUrl;
  413. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  414. fragmentShaderUrl = fragment;
  415. }
  416. else {
  417. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  418. }
  419. // Fragment shader
  420. this._engine._loadFile(fragmentShaderUrl + ".fragment.fx", callback);
  421. };
  422. /** @hidden */
  423. Effect.prototype._dumpShadersSource = function (vertexCode, fragmentCode, defines) {
  424. // Rebuild shaders source code
  425. var shaderVersion = (this._engine.webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  426. var prefix = shaderVersion + (defines ? defines + "\n" : "");
  427. vertexCode = prefix + vertexCode;
  428. fragmentCode = prefix + fragmentCode;
  429. // Number lines of shaders source code
  430. var i = 2;
  431. var regex = /\n/gm;
  432. var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  433. i = 2;
  434. var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  435. // Dump shaders name and formatted source code
  436. if (this.name.vertexElement) {
  437. BABYLON.Tools.Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode);
  438. BABYLON.Tools.Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode);
  439. }
  440. else if (this.name.vertex) {
  441. BABYLON.Tools.Error("Vertex shader: " + this.name.vertex + formattedVertexCode);
  442. BABYLON.Tools.Error("Fragment shader: " + this.name.fragment + formattedFragmentCode);
  443. }
  444. else {
  445. BABYLON.Tools.Error("Vertex shader: " + this.name + formattedVertexCode);
  446. BABYLON.Tools.Error("Fragment shader: " + this.name + formattedFragmentCode);
  447. }
  448. };
  449. ;
  450. Effect.prototype._processShaderConversion = function (sourceCode, isFragment, callback) {
  451. var preparedSourceCode = this._processPrecision(sourceCode);
  452. if (this._engine.webGLVersion == 1) {
  453. callback(preparedSourceCode);
  454. return;
  455. }
  456. // Already converted
  457. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  458. callback(preparedSourceCode.replace("#version 300 es", ""));
  459. return;
  460. }
  461. var hasDrawBuffersExtension = preparedSourceCode.search(/#extension.+GL_EXT_draw_buffers.+require/) !== -1;
  462. // Remove extensions
  463. // #extension GL_OES_standard_derivatives : enable
  464. // #extension GL_EXT_shader_texture_lod : enable
  465. // #extension GL_EXT_frag_depth : enable
  466. // #extension GL_EXT_draw_buffers : require
  467. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g;
  468. var result = preparedSourceCode.replace(regex, "");
  469. // Migrate to GLSL v300
  470. result = result.replace(/varying(?![\n\r])\s/g, isFragment ? "in " : "out ");
  471. result = result.replace(/attribute[ \t]/g, "in ");
  472. result = result.replace(/[ \t]attribute/g, " in");
  473. if (isFragment) {
  474. result = result.replace(/texture2DLodEXT\s*\(/g, "textureLod(");
  475. result = result.replace(/textureCubeLodEXT\s*\(/g, "textureLod(");
  476. result = result.replace(/texture2D\s*\(/g, "texture(");
  477. result = result.replace(/textureCube\s*\(/g, "texture(");
  478. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  479. result = result.replace(/gl_FragColor/g, "glFragColor");
  480. result = result.replace(/gl_FragData/g, "glFragData");
  481. result = result.replace(/void\s+?main\s*\(/g, (hasDrawBuffersExtension ? "" : "out vec4 glFragColor;\n") + "void main(");
  482. }
  483. callback(result);
  484. };
  485. Effect.prototype._processIncludes = function (sourceCode, callback) {
  486. var _this = this;
  487. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  488. var match = regex.exec(sourceCode);
  489. var returnValue = new String(sourceCode);
  490. while (match != null) {
  491. var includeFile = match[1];
  492. // Uniform declaration
  493. if (includeFile.indexOf("__decl__") !== -1) {
  494. includeFile = includeFile.replace(/__decl__/, "");
  495. if (this._engine.supportsUniformBuffers) {
  496. includeFile = includeFile.replace(/Vertex/, "Ubo");
  497. includeFile = includeFile.replace(/Fragment/, "Ubo");
  498. }
  499. includeFile = includeFile + "Declaration";
  500. }
  501. if (Effect.IncludesShadersStore[includeFile]) {
  502. // Substitution
  503. var includeContent = Effect.IncludesShadersStore[includeFile];
  504. if (match[2]) {
  505. var splits = match[3].split(",");
  506. for (var index = 0; index < splits.length; index += 2) {
  507. var source = new RegExp(splits[index], "g");
  508. var dest = splits[index + 1];
  509. includeContent = includeContent.replace(source, dest);
  510. }
  511. }
  512. if (match[4]) {
  513. var indexString = match[5];
  514. if (indexString.indexOf("..") !== -1) {
  515. var indexSplits = indexString.split("..");
  516. var minIndex = parseInt(indexSplits[0]);
  517. var maxIndex = parseInt(indexSplits[1]);
  518. var sourceIncludeContent = includeContent.slice(0);
  519. includeContent = "";
  520. if (isNaN(maxIndex)) {
  521. maxIndex = this._indexParameters[indexSplits[1]];
  522. }
  523. for (var i = minIndex; i < maxIndex; i++) {
  524. if (!this._engine.supportsUniformBuffers) {
  525. // Ubo replacement
  526. sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  527. return p1 + "{X}";
  528. });
  529. }
  530. includeContent += sourceIncludeContent.replace(/\{X\}/g, i.toString()) + "\n";
  531. }
  532. }
  533. else {
  534. if (!this._engine.supportsUniformBuffers) {
  535. // Ubo replacement
  536. includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  537. return p1 + "{X}";
  538. });
  539. }
  540. includeContent = includeContent.replace(/\{X\}/g, indexString);
  541. }
  542. }
  543. // Replace
  544. returnValue = returnValue.replace(match[0], includeContent);
  545. }
  546. else {
  547. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  548. this._engine._loadFile(includeShaderUrl, function (fileContent) {
  549. Effect.IncludesShadersStore[includeFile] = fileContent;
  550. _this._processIncludes(returnValue, callback);
  551. });
  552. return;
  553. }
  554. match = regex.exec(sourceCode);
  555. }
  556. callback(returnValue);
  557. };
  558. Effect.prototype._processPrecision = function (source) {
  559. if (source.indexOf("precision highp float") === -1) {
  560. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  561. source = "precision mediump float;\n" + source;
  562. }
  563. else {
  564. source = "precision highp float;\n" + source;
  565. }
  566. }
  567. else {
  568. if (!this._engine.getCaps().highPrecisionShaderSupported) { // Moving highp to mediump
  569. source = source.replace("precision highp float", "precision mediump float");
  570. }
  571. }
  572. return source;
  573. };
  574. /**
  575. * Recompiles the webGL program
  576. * @param vertexSourceCode The source code for the vertex shader.
  577. * @param fragmentSourceCode The source code for the fragment shader.
  578. * @param onCompiled Callback called when completed.
  579. * @param onError Callback called on error.
  580. * @hidden
  581. */
  582. Effect.prototype._rebuildProgram = function (vertexSourceCode, fragmentSourceCode, onCompiled, onError) {
  583. var _this = this;
  584. this._isReady = false;
  585. this._vertexSourceCodeOverride = vertexSourceCode;
  586. this._fragmentSourceCodeOverride = fragmentSourceCode;
  587. this.onError = function (effect, error) {
  588. if (onError) {
  589. onError(error);
  590. }
  591. };
  592. this.onCompiled = function () {
  593. var scenes = _this.getEngine().scenes;
  594. for (var i = 0; i < scenes.length; i++) {
  595. scenes[i].markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  596. }
  597. if (onCompiled) {
  598. onCompiled(_this._program);
  599. }
  600. };
  601. this._fallbacks = null;
  602. this._prepareEffect();
  603. };
  604. /**
  605. * Gets the uniform locations of the the specified variable names
  606. * @param names THe names of the variables to lookup.
  607. * @returns Array of locations in the same order as variable names.
  608. */
  609. Effect.prototype.getSpecificUniformLocations = function (names) {
  610. var engine = this._engine;
  611. return engine.getUniforms(this._program, names);
  612. };
  613. /**
  614. * Prepares the effect
  615. * @hidden
  616. */
  617. Effect.prototype._prepareEffect = function () {
  618. var attributesNames = this._attributesNames;
  619. var defines = this.defines;
  620. var fallbacks = this._fallbacks;
  621. this._valueCache = {};
  622. var previousProgram = this._program;
  623. try {
  624. var engine = this._engine;
  625. if (this._vertexSourceCodeOverride && this._fragmentSourceCodeOverride) {
  626. this._program = engine.createRawShaderProgram(this._vertexSourceCodeOverride, this._fragmentSourceCodeOverride, undefined, this._transformFeedbackVaryings);
  627. }
  628. else {
  629. this._program = engine.createShaderProgram(this._vertexSourceCode, this._fragmentSourceCode, defines, undefined, this._transformFeedbackVaryings);
  630. }
  631. this._program.__SPECTOR_rebuildProgram = this._rebuildProgram.bind(this);
  632. if (engine.supportsUniformBuffers) {
  633. for (var name in this._uniformBuffersNames) {
  634. this.bindUniformBlock(name, this._uniformBuffersNames[name]);
  635. }
  636. }
  637. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  638. this._attributes = engine.getAttributes(this._program, attributesNames);
  639. var index;
  640. for (index = 0; index < this._samplers.length; index++) {
  641. var sampler = this.getUniform(this._samplers[index]);
  642. if (sampler == null) {
  643. this._samplers.splice(index, 1);
  644. index--;
  645. }
  646. }
  647. engine.bindSamplers(this);
  648. this._compilationError = "";
  649. this._isReady = true;
  650. if (this.onCompiled) {
  651. this.onCompiled(this);
  652. }
  653. this.onCompileObservable.notifyObservers(this);
  654. this.onCompileObservable.clear();
  655. // Unbind mesh reference in fallbacks
  656. if (this._fallbacks) {
  657. this._fallbacks.unBindMesh();
  658. }
  659. if (previousProgram) {
  660. this.getEngine()._deleteProgram(previousProgram);
  661. }
  662. }
  663. catch (e) {
  664. this._compilationError = e.message;
  665. // Let's go through fallbacks then
  666. BABYLON.Tools.Error("Unable to compile effect:");
  667. BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
  668. return " " + uniform;
  669. }));
  670. BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
  671. return " " + attribute;
  672. }));
  673. BABYLON.Tools.Error("Error: " + this._compilationError);
  674. if (previousProgram) {
  675. this._program = previousProgram;
  676. this._isReady = true;
  677. if (this.onError) {
  678. this.onError(this, this._compilationError);
  679. }
  680. this.onErrorObservable.notifyObservers(this);
  681. }
  682. if (fallbacks && fallbacks.isMoreFallbacks) {
  683. BABYLON.Tools.Error("Trying next fallback.");
  684. this.defines = fallbacks.reduce(this.defines, this);
  685. this._prepareEffect();
  686. }
  687. else { // Sorry we did everything we can
  688. if (this.onError) {
  689. this.onError(this, this._compilationError);
  690. }
  691. this.onErrorObservable.notifyObservers(this);
  692. this.onErrorObservable.clear();
  693. // Unbind mesh reference in fallbacks
  694. if (this._fallbacks) {
  695. this._fallbacks.unBindMesh();
  696. }
  697. }
  698. }
  699. };
  700. Object.defineProperty(Effect.prototype, "isSupported", {
  701. /**
  702. * Checks if the effect is supported. (Must be called after compilation)
  703. */
  704. get: function () {
  705. return this._compilationError === "";
  706. },
  707. enumerable: true,
  708. configurable: true
  709. });
  710. /**
  711. * Binds a texture to the engine to be used as output of the shader.
  712. * @param channel Name of the output variable.
  713. * @param texture Texture to bind.
  714. * @hidden
  715. */
  716. Effect.prototype._bindTexture = function (channel, texture) {
  717. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  718. };
  719. /**
  720. * Sets a texture on the engine to be used in the shader.
  721. * @param channel Name of the sampler variable.
  722. * @param texture Texture to set.
  723. */
  724. Effect.prototype.setTexture = function (channel, texture) {
  725. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  726. };
  727. /**
  728. * Sets a depth stencil texture from a render target on the engine to be used in the shader.
  729. * @param channel Name of the sampler variable.
  730. * @param texture Texture to set.
  731. */
  732. Effect.prototype.setDepthStencilTexture = function (channel, texture) {
  733. this._engine.setDepthStencilTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  734. };
  735. /**
  736. * Sets an array of textures on the engine to be used in the shader.
  737. * @param channel Name of the variable.
  738. * @param textures Textures to set.
  739. */
  740. Effect.prototype.setTextureArray = function (channel, textures) {
  741. if (this._samplers.indexOf(channel + "Ex") === -1) {
  742. var initialPos = this._samplers.indexOf(channel);
  743. for (var index = 1; index < textures.length; index++) {
  744. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  745. }
  746. }
  747. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  748. };
  749. /**
  750. * 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)
  751. * @param channel Name of the sampler variable.
  752. * @param postProcess Post process to get the input texture from.
  753. */
  754. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  755. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  756. };
  757. /**
  758. * (Warning! setTextureFromPostProcessOutput may be desired instead)
  759. * 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)
  760. * @param channel Name of the sampler variable.
  761. * @param postProcess Post process to get the output texture from.
  762. */
  763. Effect.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  764. this._engine.setTextureFromPostProcessOutput(this._samplers.indexOf(channel), postProcess);
  765. };
  766. /** @hidden */
  767. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  768. var cache = this._valueCache[uniformName];
  769. var flag = matrix.updateFlag;
  770. if (cache !== undefined && cache === flag) {
  771. return false;
  772. }
  773. this._valueCache[uniformName] = flag;
  774. return true;
  775. };
  776. /** @hidden */
  777. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  778. var cache = this._valueCache[uniformName];
  779. if (!cache) {
  780. cache = [x, y];
  781. this._valueCache[uniformName] = cache;
  782. return true;
  783. }
  784. var changed = false;
  785. if (cache[0] !== x) {
  786. cache[0] = x;
  787. changed = true;
  788. }
  789. if (cache[1] !== y) {
  790. cache[1] = y;
  791. changed = true;
  792. }
  793. return changed;
  794. };
  795. /** @hidden */
  796. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  797. var cache = this._valueCache[uniformName];
  798. if (!cache) {
  799. cache = [x, y, z];
  800. this._valueCache[uniformName] = cache;
  801. return true;
  802. }
  803. var changed = false;
  804. if (cache[0] !== x) {
  805. cache[0] = x;
  806. changed = true;
  807. }
  808. if (cache[1] !== y) {
  809. cache[1] = y;
  810. changed = true;
  811. }
  812. if (cache[2] !== z) {
  813. cache[2] = z;
  814. changed = true;
  815. }
  816. return changed;
  817. };
  818. /** @hidden */
  819. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  820. var cache = this._valueCache[uniformName];
  821. if (!cache) {
  822. cache = [x, y, z, w];
  823. this._valueCache[uniformName] = cache;
  824. return true;
  825. }
  826. var changed = false;
  827. if (cache[0] !== x) {
  828. cache[0] = x;
  829. changed = true;
  830. }
  831. if (cache[1] !== y) {
  832. cache[1] = y;
  833. changed = true;
  834. }
  835. if (cache[2] !== z) {
  836. cache[2] = z;
  837. changed = true;
  838. }
  839. if (cache[3] !== w) {
  840. cache[3] = w;
  841. changed = true;
  842. }
  843. return changed;
  844. };
  845. /**
  846. * Binds a buffer to a uniform.
  847. * @param buffer Buffer to bind.
  848. * @param name Name of the uniform variable to bind to.
  849. */
  850. Effect.prototype.bindUniformBuffer = function (buffer, name) {
  851. var bufferName = this._uniformBuffersNames[name];
  852. if (bufferName === undefined || Effect._baseCache[bufferName] === buffer) {
  853. return;
  854. }
  855. Effect._baseCache[bufferName] = buffer;
  856. this._engine.bindUniformBufferBase(buffer, bufferName);
  857. };
  858. /**
  859. * Binds block to a uniform.
  860. * @param blockName Name of the block to bind.
  861. * @param index Index to bind.
  862. */
  863. Effect.prototype.bindUniformBlock = function (blockName, index) {
  864. this._engine.bindUniformBlock(this._program, blockName, index);
  865. };
  866. /**
  867. * Sets an interger value on a uniform variable.
  868. * @param uniformName Name of the variable.
  869. * @param value Value to be set.
  870. * @returns this effect.
  871. */
  872. Effect.prototype.setInt = function (uniformName, value) {
  873. var cache = this._valueCache[uniformName];
  874. if (cache !== undefined && cache === value)
  875. return this;
  876. this._valueCache[uniformName] = value;
  877. this._engine.setInt(this.getUniform(uniformName), value);
  878. return this;
  879. };
  880. /**
  881. * Sets an int array on a uniform variable.
  882. * @param uniformName Name of the variable.
  883. * @param array array to be set.
  884. * @returns this effect.
  885. */
  886. Effect.prototype.setIntArray = function (uniformName, array) {
  887. this._valueCache[uniformName] = null;
  888. this._engine.setIntArray(this.getUniform(uniformName), array);
  889. return this;
  890. };
  891. /**
  892. * 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)
  893. * @param uniformName Name of the variable.
  894. * @param array array to be set.
  895. * @returns this effect.
  896. */
  897. Effect.prototype.setIntArray2 = function (uniformName, array) {
  898. this._valueCache[uniformName] = null;
  899. this._engine.setIntArray2(this.getUniform(uniformName), array);
  900. return this;
  901. };
  902. /**
  903. * 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)
  904. * @param uniformName Name of the variable.
  905. * @param array array to be set.
  906. * @returns this effect.
  907. */
  908. Effect.prototype.setIntArray3 = function (uniformName, array) {
  909. this._valueCache[uniformName] = null;
  910. this._engine.setIntArray3(this.getUniform(uniformName), array);
  911. return this;
  912. };
  913. /**
  914. * 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)
  915. * @param uniformName Name of the variable.
  916. * @param array array to be set.
  917. * @returns this effect.
  918. */
  919. Effect.prototype.setIntArray4 = function (uniformName, array) {
  920. this._valueCache[uniformName] = null;
  921. this._engine.setIntArray4(this.getUniform(uniformName), array);
  922. return this;
  923. };
  924. /**
  925. * Sets an float array on a uniform variable.
  926. * @param uniformName Name of the variable.
  927. * @param array array to be set.
  928. * @returns this effect.
  929. */
  930. Effect.prototype.setFloatArray = function (uniformName, array) {
  931. this._valueCache[uniformName] = null;
  932. this._engine.setFloatArray(this.getUniform(uniformName), array);
  933. return this;
  934. };
  935. /**
  936. * 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)
  937. * @param uniformName Name of the variable.
  938. * @param array array to be set.
  939. * @returns this effect.
  940. */
  941. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  942. this._valueCache[uniformName] = null;
  943. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  944. return this;
  945. };
  946. /**
  947. * 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)
  948. * @param uniformName Name of the variable.
  949. * @param array array to be set.
  950. * @returns this effect.
  951. */
  952. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  953. this._valueCache[uniformName] = null;
  954. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  955. return this;
  956. };
  957. /**
  958. * 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)
  959. * @param uniformName Name of the variable.
  960. * @param array array to be set.
  961. * @returns this effect.
  962. */
  963. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  964. this._valueCache[uniformName] = null;
  965. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  966. return this;
  967. };
  968. /**
  969. * Sets an array on a uniform variable.
  970. * @param uniformName Name of the variable.
  971. * @param array array to be set.
  972. * @returns this effect.
  973. */
  974. Effect.prototype.setArray = function (uniformName, array) {
  975. this._valueCache[uniformName] = null;
  976. this._engine.setArray(this.getUniform(uniformName), array);
  977. return this;
  978. };
  979. /**
  980. * 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)
  981. * @param uniformName Name of the variable.
  982. * @param array array to be set.
  983. * @returns this effect.
  984. */
  985. Effect.prototype.setArray2 = function (uniformName, array) {
  986. this._valueCache[uniformName] = null;
  987. this._engine.setArray2(this.getUniform(uniformName), array);
  988. return this;
  989. };
  990. /**
  991. * 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)
  992. * @param uniformName Name of the variable.
  993. * @param array array to be set.
  994. * @returns this effect.
  995. */
  996. Effect.prototype.setArray3 = function (uniformName, array) {
  997. this._valueCache[uniformName] = null;
  998. this._engine.setArray3(this.getUniform(uniformName), array);
  999. return this;
  1000. };
  1001. /**
  1002. * 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)
  1003. * @param uniformName Name of the variable.
  1004. * @param array array to be set.
  1005. * @returns this effect.
  1006. */
  1007. Effect.prototype.setArray4 = function (uniformName, array) {
  1008. this._valueCache[uniformName] = null;
  1009. this._engine.setArray4(this.getUniform(uniformName), array);
  1010. return this;
  1011. };
  1012. /**
  1013. * Sets matrices on a uniform variable.
  1014. * @param uniformName Name of the variable.
  1015. * @param matrices matrices to be set.
  1016. * @returns this effect.
  1017. */
  1018. Effect.prototype.setMatrices = function (uniformName, matrices) {
  1019. if (!matrices) {
  1020. return this;
  1021. }
  1022. this._valueCache[uniformName] = null;
  1023. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  1024. return this;
  1025. };
  1026. /**
  1027. * Sets matrix on a uniform variable.
  1028. * @param uniformName Name of the variable.
  1029. * @param matrix matrix to be set.
  1030. * @returns this effect.
  1031. */
  1032. Effect.prototype.setMatrix = function (uniformName, matrix) {
  1033. if (this._cacheMatrix(uniformName, matrix)) {
  1034. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  1035. }
  1036. return this;
  1037. };
  1038. /**
  1039. * 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)
  1040. * @param uniformName Name of the variable.
  1041. * @param matrix matrix to be set.
  1042. * @returns this effect.
  1043. */
  1044. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  1045. this._valueCache[uniformName] = null;
  1046. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  1047. return this;
  1048. };
  1049. /**
  1050. * Sets a 2x2 matrix on a uniform variable. (Speicified as [1,2,3,4] will result in [1,2][3,4] matrix)
  1051. * @param uniformName Name of the variable.
  1052. * @param matrix matrix to be set.
  1053. * @returns this effect.
  1054. */
  1055. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  1056. this._valueCache[uniformName] = null;
  1057. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  1058. return this;
  1059. };
  1060. /**
  1061. * Sets a float on a uniform variable.
  1062. * @param uniformName Name of the variable.
  1063. * @param value value to be set.
  1064. * @returns this effect.
  1065. */
  1066. Effect.prototype.setFloat = function (uniformName, value) {
  1067. var cache = this._valueCache[uniformName];
  1068. if (cache !== undefined && cache === value)
  1069. return this;
  1070. this._valueCache[uniformName] = value;
  1071. this._engine.setFloat(this.getUniform(uniformName), value);
  1072. return this;
  1073. };
  1074. /**
  1075. * Sets a boolean on a uniform variable.
  1076. * @param uniformName Name of the variable.
  1077. * @param bool value to be set.
  1078. * @returns this effect.
  1079. */
  1080. Effect.prototype.setBool = function (uniformName, bool) {
  1081. var cache = this._valueCache[uniformName];
  1082. if (cache !== undefined && cache === bool)
  1083. return this;
  1084. this._valueCache[uniformName] = bool;
  1085. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  1086. return this;
  1087. };
  1088. /**
  1089. * Sets a Vector2 on a uniform variable.
  1090. * @param uniformName Name of the variable.
  1091. * @param vector2 vector2 to be set.
  1092. * @returns this effect.
  1093. */
  1094. Effect.prototype.setVector2 = function (uniformName, vector2) {
  1095. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  1096. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  1097. }
  1098. return this;
  1099. };
  1100. /**
  1101. * Sets a float2 on a uniform variable.
  1102. * @param uniformName Name of the variable.
  1103. * @param x First float in float2.
  1104. * @param y Second float in float2.
  1105. * @returns this effect.
  1106. */
  1107. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  1108. if (this._cacheFloat2(uniformName, x, y)) {
  1109. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  1110. }
  1111. return this;
  1112. };
  1113. /**
  1114. * Sets a Vector3 on a uniform variable.
  1115. * @param uniformName Name of the variable.
  1116. * @param vector3 Value to be set.
  1117. * @returns this effect.
  1118. */
  1119. Effect.prototype.setVector3 = function (uniformName, vector3) {
  1120. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  1121. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  1122. }
  1123. return this;
  1124. };
  1125. /**
  1126. * Sets a float3 on a uniform variable.
  1127. * @param uniformName Name of the variable.
  1128. * @param x First float in float3.
  1129. * @param y Second float in float3.
  1130. * @param z Third float in float3.
  1131. * @returns this effect.
  1132. */
  1133. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  1134. if (this._cacheFloat3(uniformName, x, y, z)) {
  1135. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  1136. }
  1137. return this;
  1138. };
  1139. /**
  1140. * Sets a Vector4 on a uniform variable.
  1141. * @param uniformName Name of the variable.
  1142. * @param vector4 Value to be set.
  1143. * @returns this effect.
  1144. */
  1145. Effect.prototype.setVector4 = function (uniformName, vector4) {
  1146. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  1147. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  1148. }
  1149. return this;
  1150. };
  1151. /**
  1152. * Sets a float4 on a uniform variable.
  1153. * @param uniformName Name of the variable.
  1154. * @param x First float in float4.
  1155. * @param y Second float in float4.
  1156. * @param z Third float in float4.
  1157. * @param w Fourth float in float4.
  1158. * @returns this effect.
  1159. */
  1160. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  1161. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  1162. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  1163. }
  1164. return this;
  1165. };
  1166. /**
  1167. * Sets a Color3 on a uniform variable.
  1168. * @param uniformName Name of the variable.
  1169. * @param color3 Value to be set.
  1170. * @returns this effect.
  1171. */
  1172. Effect.prototype.setColor3 = function (uniformName, color3) {
  1173. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  1174. this._engine.setColor3(this.getUniform(uniformName), color3);
  1175. }
  1176. return this;
  1177. };
  1178. /**
  1179. * Sets a Color4 on a uniform variable.
  1180. * @param uniformName Name of the variable.
  1181. * @param color3 Value to be set.
  1182. * @param alpha Alpha value to be set.
  1183. * @returns this effect.
  1184. */
  1185. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  1186. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  1187. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  1188. }
  1189. return this;
  1190. };
  1191. /**
  1192. * Sets a Color4 on a uniform variable
  1193. * @param uniformName defines the name of the variable
  1194. * @param color4 defines the value to be set
  1195. * @returns this effect.
  1196. */
  1197. Effect.prototype.setDirectColor4 = function (uniformName, color4) {
  1198. if (this._cacheFloat4(uniformName, color4.r, color4.g, color4.b, color4.a)) {
  1199. this._engine.setDirectColor4(this.getUniform(uniformName), color4);
  1200. }
  1201. return this;
  1202. };
  1203. /**
  1204. * This function will add a new shader to the shader store
  1205. * @param name the name of the shader
  1206. * @param pixelShader optional pixel shader content
  1207. * @param vertexShader optional vertex shader content
  1208. */
  1209. Effect.RegisterShader = function (name, pixelShader, vertexShader) {
  1210. if (pixelShader) {
  1211. Effect.ShadersStore[name + "PixelShader"] = pixelShader;
  1212. }
  1213. if (vertexShader) {
  1214. Effect.ShadersStore[name + "VertexShader"] = vertexShader;
  1215. }
  1216. };
  1217. /**
  1218. * Resets the cache of effects.
  1219. */
  1220. Effect.ResetCache = function () {
  1221. Effect._baseCache = {};
  1222. };
  1223. Effect._uniqueIdSeed = 0;
  1224. Effect._baseCache = {};
  1225. /**
  1226. * Store of each shader (The can be looked up using effect.key)
  1227. */
  1228. Effect.ShadersStore = {};
  1229. /**
  1230. * Store of each included file for a shader (The can be looked up using effect.key)
  1231. */
  1232. Effect.IncludesShadersStore = {};
  1233. return Effect;
  1234. }());
  1235. BABYLON.Effect = Effect;
  1236. })(BABYLON || (BABYLON = {}));
  1237. //# sourceMappingURL=babylon.effect.js.map
  1238. //# sourceMappingURL=babylon.types.js.map
  1239. var BABYLON;
  1240. (function (BABYLON) {
  1241. var KeyboardEventTypes = /** @class */ (function () {
  1242. function KeyboardEventTypes() {
  1243. }
  1244. Object.defineProperty(KeyboardEventTypes, "KEYDOWN", {
  1245. get: function () {
  1246. return KeyboardEventTypes._KEYDOWN;
  1247. },
  1248. enumerable: true,
  1249. configurable: true
  1250. });
  1251. Object.defineProperty(KeyboardEventTypes, "KEYUP", {
  1252. get: function () {
  1253. return KeyboardEventTypes._KEYUP;
  1254. },
  1255. enumerable: true,
  1256. configurable: true
  1257. });
  1258. KeyboardEventTypes._KEYDOWN = 0x01;
  1259. KeyboardEventTypes._KEYUP = 0x02;
  1260. return KeyboardEventTypes;
  1261. }());
  1262. BABYLON.KeyboardEventTypes = KeyboardEventTypes;
  1263. var KeyboardInfo = /** @class */ (function () {
  1264. function KeyboardInfo(type, event) {
  1265. this.type = type;
  1266. this.event = event;
  1267. }
  1268. return KeyboardInfo;
  1269. }());
  1270. BABYLON.KeyboardInfo = KeyboardInfo;
  1271. /**
  1272. * This class is used to store keyboard related info for the onPreKeyboardObservable event.
  1273. * Set the skipOnKeyboardObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onKeyboardObservable
  1274. */
  1275. var KeyboardInfoPre = /** @class */ (function (_super) {
  1276. __extends(KeyboardInfoPre, _super);
  1277. function KeyboardInfoPre(type, event) {
  1278. var _this = _super.call(this, type, event) || this;
  1279. _this.skipOnPointerObservable = false;
  1280. return _this;
  1281. }
  1282. return KeyboardInfoPre;
  1283. }(KeyboardInfo));
  1284. BABYLON.KeyboardInfoPre = KeyboardInfoPre;
  1285. })(BABYLON || (BABYLON = {}));
  1286. //# sourceMappingURL=babylon.keyboardEvents.js.map
  1287. var BABYLON;
  1288. (function (BABYLON) {
  1289. var PointerEventTypes = /** @class */ (function () {
  1290. function PointerEventTypes() {
  1291. }
  1292. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  1293. get: function () {
  1294. return PointerEventTypes._POINTERDOWN;
  1295. },
  1296. enumerable: true,
  1297. configurable: true
  1298. });
  1299. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  1300. get: function () {
  1301. return PointerEventTypes._POINTERUP;
  1302. },
  1303. enumerable: true,
  1304. configurable: true
  1305. });
  1306. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  1307. get: function () {
  1308. return PointerEventTypes._POINTERMOVE;
  1309. },
  1310. enumerable: true,
  1311. configurable: true
  1312. });
  1313. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  1314. get: function () {
  1315. return PointerEventTypes._POINTERWHEEL;
  1316. },
  1317. enumerable: true,
  1318. configurable: true
  1319. });
  1320. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  1321. get: function () {
  1322. return PointerEventTypes._POINTERPICK;
  1323. },
  1324. enumerable: true,
  1325. configurable: true
  1326. });
  1327. Object.defineProperty(PointerEventTypes, "POINTERTAP", {
  1328. get: function () {
  1329. return PointerEventTypes._POINTERTAP;
  1330. },
  1331. enumerable: true,
  1332. configurable: true
  1333. });
  1334. Object.defineProperty(PointerEventTypes, "POINTERDOUBLETAP", {
  1335. get: function () {
  1336. return PointerEventTypes._POINTERDOUBLETAP;
  1337. },
  1338. enumerable: true,
  1339. configurable: true
  1340. });
  1341. PointerEventTypes._POINTERDOWN = 0x01;
  1342. PointerEventTypes._POINTERUP = 0x02;
  1343. PointerEventTypes._POINTERMOVE = 0x04;
  1344. PointerEventTypes._POINTERWHEEL = 0x08;
  1345. PointerEventTypes._POINTERPICK = 0x10;
  1346. PointerEventTypes._POINTERTAP = 0x20;
  1347. PointerEventTypes._POINTERDOUBLETAP = 0x40;
  1348. return PointerEventTypes;
  1349. }());
  1350. BABYLON.PointerEventTypes = PointerEventTypes;
  1351. var PointerInfoBase = /** @class */ (function () {
  1352. function PointerInfoBase(type, event) {
  1353. this.type = type;
  1354. this.event = event;
  1355. }
  1356. return PointerInfoBase;
  1357. }());
  1358. BABYLON.PointerInfoBase = PointerInfoBase;
  1359. /**
  1360. * This class is used to store pointer related info for the onPrePointerObservable event.
  1361. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  1362. */
  1363. var PointerInfoPre = /** @class */ (function (_super) {
  1364. __extends(PointerInfoPre, _super);
  1365. function PointerInfoPre(type, event, localX, localY) {
  1366. var _this = _super.call(this, type, event) || this;
  1367. /**
  1368. * Ray from a pointer if availible (eg. 6dof controller)
  1369. */
  1370. _this.ray = null;
  1371. _this.skipOnPointerObservable = false;
  1372. _this.localPosition = new BABYLON.Vector2(localX, localY);
  1373. return _this;
  1374. }
  1375. return PointerInfoPre;
  1376. }(PointerInfoBase));
  1377. BABYLON.PointerInfoPre = PointerInfoPre;
  1378. /**
  1379. * This type contains all the data related to a pointer event in Babylon.js.
  1380. * 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.
  1381. */
  1382. var PointerInfo = /** @class */ (function (_super) {
  1383. __extends(PointerInfo, _super);
  1384. function PointerInfo(type, event, pickInfo) {
  1385. var _this = _super.call(this, type, event) || this;
  1386. _this.pickInfo = pickInfo;
  1387. return _this;
  1388. }
  1389. return PointerInfo;
  1390. }(PointerInfoBase));
  1391. BABYLON.PointerInfo = PointerInfo;
  1392. })(BABYLON || (BABYLON = {}));
  1393. //# sourceMappingURL=babylon.pointerEvents.js.map
  1394. var BABYLON;
  1395. (function (BABYLON) {
  1396. /**
  1397. * Constant used to convert a value to gamma space
  1398. * @ignorenaming
  1399. */
  1400. BABYLON.ToGammaSpace = 1 / 2.2;
  1401. /**
  1402. * Constant used to convert a value to linear space
  1403. * @ignorenaming
  1404. */
  1405. BABYLON.ToLinearSpace = 2.2;
  1406. /**
  1407. * Constant used to define the minimal number value in Babylon.js
  1408. * @ignorenaming
  1409. */
  1410. BABYLON.Epsilon = 0.001;
  1411. /**
  1412. * Class used to hold a RBG color
  1413. */
  1414. var Color3 = /** @class */ (function () {
  1415. /**
  1416. * Creates a new Color3 object from red, green, blue values, all between 0 and 1
  1417. * @param r defines the red component (between 0 and 1, default is 0)
  1418. * @param g defines the green component (between 0 and 1, default is 0)
  1419. * @param b defines the blue component (between 0 and 1, default is 0)
  1420. */
  1421. function Color3(
  1422. /**
  1423. * Defines the red component (between 0 and 1, default is 0)
  1424. */
  1425. r,
  1426. /**
  1427. * Defines the green component (between 0 and 1, default is 0)
  1428. */
  1429. g,
  1430. /**
  1431. * Defines the blue component (between 0 and 1, default is 0)
  1432. */
  1433. b) {
  1434. if (r === void 0) { r = 0; }
  1435. if (g === void 0) { g = 0; }
  1436. if (b === void 0) { b = 0; }
  1437. this.r = r;
  1438. this.g = g;
  1439. this.b = b;
  1440. }
  1441. /**
  1442. * Creates a string with the Color3 current values
  1443. * @returns the string representation of the Color3 object
  1444. */
  1445. Color3.prototype.toString = function () {
  1446. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  1447. };
  1448. /**
  1449. * Returns the string "Color3"
  1450. * @returns "Color3"
  1451. */
  1452. Color3.prototype.getClassName = function () {
  1453. return "Color3";
  1454. };
  1455. /**
  1456. * Compute the Color3 hash code
  1457. * @returns an unique number that can be used to hash Color3 objects
  1458. */
  1459. Color3.prototype.getHashCode = function () {
  1460. var hash = this.r || 0;
  1461. hash = (hash * 397) ^ (this.g || 0);
  1462. hash = (hash * 397) ^ (this.b || 0);
  1463. return hash;
  1464. };
  1465. // Operators
  1466. /**
  1467. * Stores in the given array from the given starting index the red, green, blue values as successive elements
  1468. * @param array defines the array where to store the r,g,b components
  1469. * @param index defines an optional index in the target array to define where to start storing values
  1470. * @returns the current Color3 object
  1471. */
  1472. Color3.prototype.toArray = function (array, index) {
  1473. if (index === undefined) {
  1474. index = 0;
  1475. }
  1476. array[index] = this.r;
  1477. array[index + 1] = this.g;
  1478. array[index + 2] = this.b;
  1479. return this;
  1480. };
  1481. /**
  1482. * Returns a new {BABYLON.Color4} object from the current Color3 and the given alpha
  1483. * @param alpha defines the alpha component on the new {BABYLON.Color4} object (default is 1)
  1484. * @returns a new {BABYLON.Color4} object
  1485. */
  1486. Color3.prototype.toColor4 = function (alpha) {
  1487. if (alpha === void 0) { alpha = 1; }
  1488. return new Color4(this.r, this.g, this.b, alpha);
  1489. };
  1490. /**
  1491. * Returns a new array populated with 3 numeric elements : red, green and blue values
  1492. * @returns the new array
  1493. */
  1494. Color3.prototype.asArray = function () {
  1495. var result = new Array();
  1496. this.toArray(result, 0);
  1497. return result;
  1498. };
  1499. /**
  1500. * Returns the luminance value
  1501. * @returns a float value
  1502. */
  1503. Color3.prototype.toLuminance = function () {
  1504. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  1505. };
  1506. /**
  1507. * Multiply each Color3 rgb values by the given Color3 rgb values in a new Color3 object
  1508. * @param otherColor defines the second operand
  1509. * @returns the new Color3 object
  1510. */
  1511. Color3.prototype.multiply = function (otherColor) {
  1512. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  1513. };
  1514. /**
  1515. * Multiply the rgb values of the Color3 and the given Color3 and stores the result in the object "result"
  1516. * @param otherColor defines the second operand
  1517. * @param result defines the Color3 object where to store the result
  1518. * @returns the current Color3
  1519. */
  1520. Color3.prototype.multiplyToRef = function (otherColor, result) {
  1521. result.r = this.r * otherColor.r;
  1522. result.g = this.g * otherColor.g;
  1523. result.b = this.b * otherColor.b;
  1524. return this;
  1525. };
  1526. /**
  1527. * Determines equality between Color3 objects
  1528. * @param otherColor defines the second operand
  1529. * @returns true if the rgb values are equal to the given ones
  1530. */
  1531. Color3.prototype.equals = function (otherColor) {
  1532. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  1533. };
  1534. /**
  1535. * Determines equality between the current Color3 object and a set of r,b,g values
  1536. * @param r defines the red component to check
  1537. * @param g defines the green component to check
  1538. * @param b defines the blue component to check
  1539. * @returns true if the rgb values are equal to the given ones
  1540. */
  1541. Color3.prototype.equalsFloats = function (r, g, b) {
  1542. return this.r === r && this.g === g && this.b === b;
  1543. };
  1544. /**
  1545. * Multiplies in place each rgb value by scale
  1546. * @param scale defines the scaling factor
  1547. * @returns the updated Color3
  1548. */
  1549. Color3.prototype.scale = function (scale) {
  1550. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  1551. };
  1552. /**
  1553. * Multiplies the rgb values by scale and stores the result into "result"
  1554. * @param scale defines the scaling factor
  1555. * @param result defines the Color3 object where to store the result
  1556. * @returns the unmodified current Color3
  1557. */
  1558. Color3.prototype.scaleToRef = function (scale, result) {
  1559. result.r = this.r * scale;
  1560. result.g = this.g * scale;
  1561. result.b = this.b * scale;
  1562. return this;
  1563. };
  1564. /**
  1565. * Scale the current Color3 values by a factor and add the result to a given Color3
  1566. * @param scale defines the scale factor
  1567. * @param result defines color to store the result into
  1568. * @returns the unmodified current Color3
  1569. */
  1570. Color3.prototype.scaleAndAddToRef = function (scale, result) {
  1571. result.r += this.r * scale;
  1572. result.g += this.g * scale;
  1573. result.b += this.b * scale;
  1574. return this;
  1575. };
  1576. /**
  1577. * Clamps the rgb values by the min and max values and stores the result into "result"
  1578. * @param min defines minimum clamping value (default is 0)
  1579. * @param max defines maximum clamping value (default is 1)
  1580. * @param result defines color to store the result into
  1581. * @returns the original Color3
  1582. */
  1583. Color3.prototype.clampToRef = function (min, max, result) {
  1584. if (min === void 0) { min = 0; }
  1585. if (max === void 0) { max = 1; }
  1586. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1587. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1588. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1589. return this;
  1590. };
  1591. /**
  1592. * Creates a new Color3 set with the added values of the current Color3 and of the given one
  1593. * @param otherColor defines the second operand
  1594. * @returns the new Color3
  1595. */
  1596. Color3.prototype.add = function (otherColor) {
  1597. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  1598. };
  1599. /**
  1600. * Stores the result of the addition of the current Color3 and given one rgb values into "result"
  1601. * @param otherColor defines the second operand
  1602. * @param result defines Color3 object to store the result into
  1603. * @returns the unmodified current Color3
  1604. */
  1605. Color3.prototype.addToRef = function (otherColor, result) {
  1606. result.r = this.r + otherColor.r;
  1607. result.g = this.g + otherColor.g;
  1608. result.b = this.b + otherColor.b;
  1609. return this;
  1610. };
  1611. /**
  1612. * Returns a new Color3 set with the subtracted values of the given one from the current Color3
  1613. * @param otherColor defines the second operand
  1614. * @returns the new Color3
  1615. */
  1616. Color3.prototype.subtract = function (otherColor) {
  1617. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  1618. };
  1619. /**
  1620. * Stores the result of the subtraction of given one from the current Color3 rgb values into "result"
  1621. * @param otherColor defines the second operand
  1622. * @param result defines Color3 object to store the result into
  1623. * @returns the unmodified current Color3
  1624. */
  1625. Color3.prototype.subtractToRef = function (otherColor, result) {
  1626. result.r = this.r - otherColor.r;
  1627. result.g = this.g - otherColor.g;
  1628. result.b = this.b - otherColor.b;
  1629. return this;
  1630. };
  1631. /**
  1632. * Copy the current object
  1633. * @returns a new Color3 copied the current one
  1634. */
  1635. Color3.prototype.clone = function () {
  1636. return new Color3(this.r, this.g, this.b);
  1637. };
  1638. /**
  1639. * Copies the rgb values from the source in the current Color3
  1640. * @param source defines the source Color3 object
  1641. * @returns the updated Color3 object
  1642. */
  1643. Color3.prototype.copyFrom = function (source) {
  1644. this.r = source.r;
  1645. this.g = source.g;
  1646. this.b = source.b;
  1647. return this;
  1648. };
  1649. /**
  1650. * Updates the Color3 rgb values from the given floats
  1651. * @param r defines the red component to read from
  1652. * @param g defines the green component to read from
  1653. * @param b defines the blue component to read from
  1654. * @returns the current Color3 object
  1655. */
  1656. Color3.prototype.copyFromFloats = function (r, g, b) {
  1657. this.r = r;
  1658. this.g = g;
  1659. this.b = b;
  1660. return this;
  1661. };
  1662. /**
  1663. * Updates the Color3 rgb values from the given floats
  1664. * @param r defines the red component to read from
  1665. * @param g defines the green component to read from
  1666. * @param b defines the blue component to read from
  1667. * @returns the current Color3 object
  1668. */
  1669. Color3.prototype.set = function (r, g, b) {
  1670. return this.copyFromFloats(r, g, b);
  1671. };
  1672. /**
  1673. * Compute the Color3 hexadecimal code as a string
  1674. * @returns a string containing the hexadecimal representation of the Color3 object
  1675. */
  1676. Color3.prototype.toHexString = function () {
  1677. var intR = (this.r * 255) | 0;
  1678. var intG = (this.g * 255) | 0;
  1679. var intB = (this.b * 255) | 0;
  1680. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB);
  1681. };
  1682. /**
  1683. * Computes a new Color3 converted from the current one to linear space
  1684. * @returns a new Color3 object
  1685. */
  1686. Color3.prototype.toLinearSpace = function () {
  1687. var convertedColor = new Color3();
  1688. this.toLinearSpaceToRef(convertedColor);
  1689. return convertedColor;
  1690. };
  1691. /**
  1692. * Converts the Color3 values to linear space and stores the result in "convertedColor"
  1693. * @param convertedColor defines the Color3 object where to store the linear space version
  1694. * @returns the unmodified Color3
  1695. */
  1696. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  1697. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  1698. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  1699. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  1700. return this;
  1701. };
  1702. /**
  1703. * Computes a new Color3 converted from the current one to gamma space
  1704. * @returns a new Color3 object
  1705. */
  1706. Color3.prototype.toGammaSpace = function () {
  1707. var convertedColor = new Color3();
  1708. this.toGammaSpaceToRef(convertedColor);
  1709. return convertedColor;
  1710. };
  1711. /**
  1712. * Converts the Color3 values to gamma space and stores the result in "convertedColor"
  1713. * @param convertedColor defines the Color3 object where to store the gamma space version
  1714. * @returns the unmodified Color3
  1715. */
  1716. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  1717. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  1718. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  1719. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  1720. return this;
  1721. };
  1722. // Statics
  1723. /**
  1724. * Creates a new Color3 from the string containing valid hexadecimal values
  1725. * @param hex defines a string containing valid hexadecimal values
  1726. * @returns a new Color3 object
  1727. */
  1728. Color3.FromHexString = function (hex) {
  1729. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  1730. return new Color3(0, 0, 0);
  1731. }
  1732. var r = parseInt(hex.substring(1, 3), 16);
  1733. var g = parseInt(hex.substring(3, 5), 16);
  1734. var b = parseInt(hex.substring(5, 7), 16);
  1735. return Color3.FromInts(r, g, b);
  1736. };
  1737. /**
  1738. * Creates a new Vector3 from the starting index of the given array
  1739. * @param array defines the source array
  1740. * @param offset defines an offset in the source array
  1741. * @returns a new Color3 object
  1742. */
  1743. Color3.FromArray = function (array, offset) {
  1744. if (offset === void 0) { offset = 0; }
  1745. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  1746. };
  1747. /**
  1748. * Creates a new Color3 from integer values (< 256)
  1749. * @param r defines the red component to read from (value between 0 and 255)
  1750. * @param g defines the green component to read from (value between 0 and 255)
  1751. * @param b defines the blue component to read from (value between 0 and 255)
  1752. * @returns a new Color3 object
  1753. */
  1754. Color3.FromInts = function (r, g, b) {
  1755. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  1756. };
  1757. /**
  1758. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3
  1759. * @param start defines the start Color3 value
  1760. * @param end defines the end Color3 value
  1761. * @param amount defines the gradient value between start and end
  1762. * @returns a new Color3 object
  1763. */
  1764. Color3.Lerp = function (start, end, amount) {
  1765. var result = new Color3(0.0, 0.0, 0.0);
  1766. Color3.LerpToRef(start, end, amount, result);
  1767. return result;
  1768. };
  1769. /**
  1770. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3
  1771. * @param left defines the start value
  1772. * @param right defines the end value
  1773. * @param amount defines the gradient factor
  1774. * @param result defines the Color3 object where to store the result
  1775. */
  1776. Color3.LerpToRef = function (left, right, amount, result) {
  1777. result.r = left.r + ((right.r - left.r) * amount);
  1778. result.g = left.g + ((right.g - left.g) * amount);
  1779. result.b = left.b + ((right.b - left.b) * amount);
  1780. };
  1781. /**
  1782. * Returns a Color3 value containing a red color
  1783. * @returns a new Color3 object
  1784. */
  1785. Color3.Red = function () { return new Color3(1, 0, 0); };
  1786. /**
  1787. * Returns a Color3 value containing a green color
  1788. * @returns a new Color3 object
  1789. */
  1790. Color3.Green = function () { return new Color3(0, 1, 0); };
  1791. /**
  1792. * Returns a Color3 value containing a blue color
  1793. * @returns a new Color3 object
  1794. */
  1795. Color3.Blue = function () { return new Color3(0, 0, 1); };
  1796. /**
  1797. * Returns a Color3 value containing a black color
  1798. * @returns a new Color3 object
  1799. */
  1800. Color3.Black = function () { return new Color3(0, 0, 0); };
  1801. /**
  1802. * Returns a Color3 value containing a white color
  1803. * @returns a new Color3 object
  1804. */
  1805. Color3.White = function () { return new Color3(1, 1, 1); };
  1806. /**
  1807. * Returns a Color3 value containing a purple color
  1808. * @returns a new Color3 object
  1809. */
  1810. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  1811. /**
  1812. * Returns a Color3 value containing a magenta color
  1813. * @returns a new Color3 object
  1814. */
  1815. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  1816. /**
  1817. * Returns a Color3 value containing a yellow color
  1818. * @returns a new Color3 object
  1819. */
  1820. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  1821. /**
  1822. * Returns a Color3 value containing a gray color
  1823. * @returns a new Color3 object
  1824. */
  1825. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  1826. /**
  1827. * Returns a Color3 value containing a teal color
  1828. * @returns a new Color3 object
  1829. */
  1830. Color3.Teal = function () { return new Color3(0, 1.0, 1.0); };
  1831. /**
  1832. * Returns a Color3 value containing a random color
  1833. * @returns a new Color3 object
  1834. */
  1835. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  1836. return Color3;
  1837. }());
  1838. BABYLON.Color3 = Color3;
  1839. /**
  1840. * Class used to hold a RBGA color
  1841. */
  1842. var Color4 = /** @class */ (function () {
  1843. /**
  1844. * Creates a new Color4 object from red, green, blue values, all between 0 and 1
  1845. * @param r defines the red component (between 0 and 1, default is 0)
  1846. * @param g defines the green component (between 0 and 1, default is 0)
  1847. * @param b defines the blue component (between 0 and 1, default is 0)
  1848. * @param a defines the alpha component (between 0 and 1, default is 1)
  1849. */
  1850. function Color4(
  1851. /**
  1852. * Defines the red component (between 0 and 1, default is 0)
  1853. */
  1854. r,
  1855. /**
  1856. * Defines the green component (between 0 and 1, default is 0)
  1857. */
  1858. g,
  1859. /**
  1860. * Defines the blue component (between 0 and 1, default is 0)
  1861. */
  1862. b,
  1863. /**
  1864. * Defines the alpha component (between 0 and 1, default is 1)
  1865. */
  1866. a) {
  1867. if (r === void 0) { r = 0; }
  1868. if (g === void 0) { g = 0; }
  1869. if (b === void 0) { b = 0; }
  1870. if (a === void 0) { a = 1; }
  1871. this.r = r;
  1872. this.g = g;
  1873. this.b = b;
  1874. this.a = a;
  1875. }
  1876. // Operators
  1877. /**
  1878. * Adds in place the given Color4 values to the current Color4 object
  1879. * @param right defines the second operand
  1880. * @returns the current updated Color4 object
  1881. */
  1882. Color4.prototype.addInPlace = function (right) {
  1883. this.r += right.r;
  1884. this.g += right.g;
  1885. this.b += right.b;
  1886. this.a += right.a;
  1887. return this;
  1888. };
  1889. /**
  1890. * Creates a new array populated with 4 numeric elements : red, green, blue, alpha values
  1891. * @returns the new array
  1892. */
  1893. Color4.prototype.asArray = function () {
  1894. var result = new Array();
  1895. this.toArray(result, 0);
  1896. return result;
  1897. };
  1898. /**
  1899. * Stores from the starting index in the given array the Color4 successive values
  1900. * @param array defines the array where to store the r,g,b components
  1901. * @param index defines an optional index in the target array to define where to start storing values
  1902. * @returns the current Color4 object
  1903. */
  1904. Color4.prototype.toArray = function (array, index) {
  1905. if (index === undefined) {
  1906. index = 0;
  1907. }
  1908. array[index] = this.r;
  1909. array[index + 1] = this.g;
  1910. array[index + 2] = this.b;
  1911. array[index + 3] = this.a;
  1912. return this;
  1913. };
  1914. /**
  1915. * Creates a new Color4 set with the added values of the current Color4 and of the given one
  1916. * @param right defines the second operand
  1917. * @returns a new Color4 object
  1918. */
  1919. Color4.prototype.add = function (right) {
  1920. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  1921. };
  1922. /**
  1923. * Creates a new Color4 set with the subtracted values of the given one from the current Color4
  1924. * @param right defines the second operand
  1925. * @returns a new Color4 object
  1926. */
  1927. Color4.prototype.subtract = function (right) {
  1928. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  1929. };
  1930. /**
  1931. * Subtracts the given ones from the current Color4 values and stores the results in "result"
  1932. * @param right defines the second operand
  1933. * @param result defines the Color4 object where to store the result
  1934. * @returns the current Color4 object
  1935. */
  1936. Color4.prototype.subtractToRef = function (right, result) {
  1937. result.r = this.r - right.r;
  1938. result.g = this.g - right.g;
  1939. result.b = this.b - right.b;
  1940. result.a = this.a - right.a;
  1941. return this;
  1942. };
  1943. /**
  1944. * Creates a new Color4 with the current Color4 values multiplied by scale
  1945. * @param scale defines the scaling factor to apply
  1946. * @returns a new Color4 object
  1947. */
  1948. Color4.prototype.scale = function (scale) {
  1949. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  1950. };
  1951. /**
  1952. * Multiplies the current Color4 values by scale and stores the result in "result"
  1953. * @param scale defines the scaling factor to apply
  1954. * @param result defines the Color4 object where to store the result
  1955. * @returns the current unmodified Color4
  1956. */
  1957. Color4.prototype.scaleToRef = function (scale, result) {
  1958. result.r = this.r * scale;
  1959. result.g = this.g * scale;
  1960. result.b = this.b * scale;
  1961. result.a = this.a * scale;
  1962. return this;
  1963. };
  1964. /**
  1965. * Scale the current Color4 values by a factor and add the result to a given Color4
  1966. * @param scale defines the scale factor
  1967. * @param result defines the Color4 object where to store the result
  1968. * @returns the unmodified current Color4
  1969. */
  1970. Color4.prototype.scaleAndAddToRef = function (scale, result) {
  1971. result.r += this.r * scale;
  1972. result.g += this.g * scale;
  1973. result.b += this.b * scale;
  1974. result.a += this.a * scale;
  1975. return this;
  1976. };
  1977. /**
  1978. * Clamps the rgb values by the min and max values and stores the result into "result"
  1979. * @param min defines minimum clamping value (default is 0)
  1980. * @param max defines maximum clamping value (default is 1)
  1981. * @param result defines color to store the result into.
  1982. * @returns the cuurent Color4
  1983. */
  1984. Color4.prototype.clampToRef = function (min, max, result) {
  1985. if (min === void 0) { min = 0; }
  1986. if (max === void 0) { max = 1; }
  1987. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1988. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1989. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1990. result.a = BABYLON.Scalar.Clamp(this.a, min, max);
  1991. return this;
  1992. };
  1993. /**
  1994. * Multipy an Color4 value by another and return a new Color4 object
  1995. * @param color defines the Color4 value to multiply by
  1996. * @returns a new Color4 object
  1997. */
  1998. Color4.prototype.multiply = function (color) {
  1999. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  2000. };
  2001. /**
  2002. * Multipy a Color4 value by another and push the result in a reference value
  2003. * @param color defines the Color4 value to multiply by
  2004. * @param result defines the Color4 to fill the result in
  2005. * @returns the result Color4
  2006. */
  2007. Color4.prototype.multiplyToRef = function (color, result) {
  2008. result.r = this.r * color.r;
  2009. result.g = this.g * color.g;
  2010. result.b = this.b * color.b;
  2011. result.a = this.a * color.a;
  2012. return result;
  2013. };
  2014. /**
  2015. * Creates a string with the Color4 current values
  2016. * @returns the string representation of the Color4 object
  2017. */
  2018. Color4.prototype.toString = function () {
  2019. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  2020. };
  2021. /**
  2022. * Returns the string "Color4"
  2023. * @returns "Color4"
  2024. */
  2025. Color4.prototype.getClassName = function () {
  2026. return "Color4";
  2027. };
  2028. /**
  2029. * Compute the Color4 hash code
  2030. * @returns an unique number that can be used to hash Color4 objects
  2031. */
  2032. Color4.prototype.getHashCode = function () {
  2033. var hash = this.r || 0;
  2034. hash = (hash * 397) ^ (this.g || 0);
  2035. hash = (hash * 397) ^ (this.b || 0);
  2036. hash = (hash * 397) ^ (this.a || 0);
  2037. return hash;
  2038. };
  2039. /**
  2040. * Creates a new Color4 copied from the current one
  2041. * @returns a new Color4 object
  2042. */
  2043. Color4.prototype.clone = function () {
  2044. return new Color4(this.r, this.g, this.b, this.a);
  2045. };
  2046. /**
  2047. * Copies the given Color4 values into the current one
  2048. * @param source defines the source Color4 object
  2049. * @returns the current updated Color4 object
  2050. */
  2051. Color4.prototype.copyFrom = function (source) {
  2052. this.r = source.r;
  2053. this.g = source.g;
  2054. this.b = source.b;
  2055. this.a = source.a;
  2056. return this;
  2057. };
  2058. /**
  2059. * Copies the given float values into the current one
  2060. * @param r defines the red component to read from
  2061. * @param g defines the green component to read from
  2062. * @param b defines the blue component to read from
  2063. * @param a defines the alpha component to read from
  2064. * @returns the current updated Color4 object
  2065. */
  2066. Color4.prototype.copyFromFloats = function (r, g, b, a) {
  2067. this.r = r;
  2068. this.g = g;
  2069. this.b = b;
  2070. this.a = a;
  2071. return this;
  2072. };
  2073. /**
  2074. * Copies the given float values into the current one
  2075. * @param r defines the red component to read from
  2076. * @param g defines the green component to read from
  2077. * @param b defines the blue component to read from
  2078. * @param a defines the alpha component to read from
  2079. * @returns the current updated Color4 object
  2080. */
  2081. Color4.prototype.set = function (r, g, b, a) {
  2082. return this.copyFromFloats(r, g, b, a);
  2083. };
  2084. /**
  2085. * Compute the Color4 hexadecimal code as a string
  2086. * @returns a string containing the hexadecimal representation of the Color4 object
  2087. */
  2088. Color4.prototype.toHexString = function () {
  2089. var intR = (this.r * 255) | 0;
  2090. var intG = (this.g * 255) | 0;
  2091. var intB = (this.b * 255) | 0;
  2092. var intA = (this.a * 255) | 0;
  2093. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB) + BABYLON.Scalar.ToHex(intA);
  2094. };
  2095. /**
  2096. * Computes a new Color4 converted from the current one to linear space
  2097. * @returns a new Color4 object
  2098. */
  2099. Color4.prototype.toLinearSpace = function () {
  2100. var convertedColor = new Color4();
  2101. this.toLinearSpaceToRef(convertedColor);
  2102. return convertedColor;
  2103. };
  2104. /**
  2105. * Converts the Color4 values to linear space and stores the result in "convertedColor"
  2106. * @param convertedColor defines the Color4 object where to store the linear space version
  2107. * @returns the unmodified Color4
  2108. */
  2109. Color4.prototype.toLinearSpaceToRef = function (convertedColor) {
  2110. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  2111. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  2112. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  2113. convertedColor.a = this.a;
  2114. return this;
  2115. };
  2116. /**
  2117. * Computes a new Color4 converted from the current one to gamma space
  2118. * @returns a new Color4 object
  2119. */
  2120. Color4.prototype.toGammaSpace = function () {
  2121. var convertedColor = new Color4();
  2122. this.toGammaSpaceToRef(convertedColor);
  2123. return convertedColor;
  2124. };
  2125. /**
  2126. * Converts the Color4 values to gamma space and stores the result in "convertedColor"
  2127. * @param convertedColor defines the Color4 object where to store the gamma space version
  2128. * @returns the unmodified Color4
  2129. */
  2130. Color4.prototype.toGammaSpaceToRef = function (convertedColor) {
  2131. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  2132. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  2133. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  2134. convertedColor.a = this.a;
  2135. return this;
  2136. };
  2137. // Statics
  2138. /**
  2139. * Creates a new Color4 from the string containing valid hexadecimal values
  2140. * @param hex defines a string containing valid hexadecimal values
  2141. * @returns a new Color4 object
  2142. */
  2143. Color4.FromHexString = function (hex) {
  2144. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  2145. return new Color4(0.0, 0.0, 0.0, 0.0);
  2146. }
  2147. var r = parseInt(hex.substring(1, 3), 16);
  2148. var g = parseInt(hex.substring(3, 5), 16);
  2149. var b = parseInt(hex.substring(5, 7), 16);
  2150. var a = parseInt(hex.substring(7, 9), 16);
  2151. return Color4.FromInts(r, g, b, a);
  2152. };
  2153. /**
  2154. * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2155. * @param left defines the start value
  2156. * @param right defines the end value
  2157. * @param amount defines the gradient factor
  2158. * @returns a new Color4 object
  2159. */
  2160. Color4.Lerp = function (left, right, amount) {
  2161. var result = new Color4(0.0, 0.0, 0.0, 0.0);
  2162. Color4.LerpToRef(left, right, amount, result);
  2163. return result;
  2164. };
  2165. /**
  2166. * Set the given "result" with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2167. * @param left defines the start value
  2168. * @param right defines the end value
  2169. * @param amount defines the gradient factor
  2170. * @param result defines the Color4 object where to store data
  2171. */
  2172. Color4.LerpToRef = function (left, right, amount, result) {
  2173. result.r = left.r + (right.r - left.r) * amount;
  2174. result.g = left.g + (right.g - left.g) * amount;
  2175. result.b = left.b + (right.b - left.b) * amount;
  2176. result.a = left.a + (right.a - left.a) * amount;
  2177. };
  2178. /**
  2179. * Creates a new Color4 from a Color3 and an alpha value
  2180. * @param color3 defines the source Color3 to read from
  2181. * @param alpha defines the alpha component (1.0 by default)
  2182. * @returns a new Color4 object
  2183. */
  2184. Color4.FromColor3 = function (color3, alpha) {
  2185. if (alpha === void 0) { alpha = 1.0; }
  2186. return new Color4(color3.r, color3.g, color3.b, alpha);
  2187. };
  2188. /**
  2189. * Creates a new Color4 from the starting index element of the given array
  2190. * @param array defines the source array to read from
  2191. * @param offset defines the offset in the source array
  2192. * @returns a new Color4 object
  2193. */
  2194. Color4.FromArray = function (array, offset) {
  2195. if (offset === void 0) { offset = 0; }
  2196. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2197. };
  2198. /**
  2199. * Creates a new Color3 from integer values (< 256)
  2200. * @param r defines the red component to read from (value between 0 and 255)
  2201. * @param g defines the green component to read from (value between 0 and 255)
  2202. * @param b defines the blue component to read from (value between 0 and 255)
  2203. * @param a defines the alpha component to read from (value between 0 and 255)
  2204. * @returns a new Color3 object
  2205. */
  2206. Color4.FromInts = function (r, g, b, a) {
  2207. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  2208. };
  2209. /**
  2210. * Check the content of a given array and convert it to an array containing RGBA data
  2211. * If the original array was already containing count * 4 values then it is returned directly
  2212. * @param colors defines the array to check
  2213. * @param count defines the number of RGBA data to expect
  2214. * @returns an array containing count * 4 values (RGBA)
  2215. */
  2216. Color4.CheckColors4 = function (colors, count) {
  2217. // Check if color3 was used
  2218. if (colors.length === count * 3) {
  2219. var colors4 = [];
  2220. for (var index = 0; index < colors.length; index += 3) {
  2221. var newIndex = (index / 3) * 4;
  2222. colors4[newIndex] = colors[index];
  2223. colors4[newIndex + 1] = colors[index + 1];
  2224. colors4[newIndex + 2] = colors[index + 2];
  2225. colors4[newIndex + 3] = 1.0;
  2226. }
  2227. return colors4;
  2228. }
  2229. return colors;
  2230. };
  2231. return Color4;
  2232. }());
  2233. BABYLON.Color4 = Color4;
  2234. /**
  2235. * Class representing a vector containing 2 coordinates
  2236. */
  2237. var Vector2 = /** @class */ (function () {
  2238. /**
  2239. * Creates a new Vector2 from the given x and y coordinates
  2240. * @param x defines the first coordinate
  2241. * @param y defines the second coordinate
  2242. */
  2243. function Vector2(
  2244. /** defines the first coordinate */
  2245. x,
  2246. /** defines the second coordinate */
  2247. y) {
  2248. if (x === void 0) { x = 0; }
  2249. if (y === void 0) { y = 0; }
  2250. this.x = x;
  2251. this.y = y;
  2252. }
  2253. /**
  2254. * Gets a string with the Vector2 coordinates
  2255. * @returns a string with the Vector2 coordinates
  2256. */
  2257. Vector2.prototype.toString = function () {
  2258. return "{X: " + this.x + " Y:" + this.y + "}";
  2259. };
  2260. /**
  2261. * Gets class name
  2262. * @returns the string "Vector2"
  2263. */
  2264. Vector2.prototype.getClassName = function () {
  2265. return "Vector2";
  2266. };
  2267. /**
  2268. * Gets current vector hash code
  2269. * @returns the Vector2 hash code as a number
  2270. */
  2271. Vector2.prototype.getHashCode = function () {
  2272. var hash = this.x || 0;
  2273. hash = (hash * 397) ^ (this.y || 0);
  2274. return hash;
  2275. };
  2276. // Operators
  2277. /**
  2278. * Sets the Vector2 coordinates in the given array or Float32Array from the given index.
  2279. * @param array defines the source array
  2280. * @param index defines the offset in source array
  2281. * @returns the current Vector2
  2282. */
  2283. Vector2.prototype.toArray = function (array, index) {
  2284. if (index === void 0) { index = 0; }
  2285. array[index] = this.x;
  2286. array[index + 1] = this.y;
  2287. return this;
  2288. };
  2289. /**
  2290. * Copy the current vector to an array
  2291. * @returns a new array with 2 elements: the Vector2 coordinates.
  2292. */
  2293. Vector2.prototype.asArray = function () {
  2294. var result = new Array();
  2295. this.toArray(result, 0);
  2296. return result;
  2297. };
  2298. /**
  2299. * Sets the Vector2 coordinates with the given Vector2 coordinates
  2300. * @param source defines the source Vector2
  2301. * @returns the current updated Vector2
  2302. */
  2303. Vector2.prototype.copyFrom = function (source) {
  2304. this.x = source.x;
  2305. this.y = source.y;
  2306. return this;
  2307. };
  2308. /**
  2309. * Sets the Vector2 coordinates with the given floats
  2310. * @param x defines the first coordinate
  2311. * @param y defines the second coordinate
  2312. * @returns the current updated Vector2
  2313. */
  2314. Vector2.prototype.copyFromFloats = function (x, y) {
  2315. this.x = x;
  2316. this.y = y;
  2317. return this;
  2318. };
  2319. /**
  2320. * Sets the Vector2 coordinates with the given floats
  2321. * @param x defines the first coordinate
  2322. * @param y defines the second coordinate
  2323. * @returns the current updated Vector2
  2324. */
  2325. Vector2.prototype.set = function (x, y) {
  2326. return this.copyFromFloats(x, y);
  2327. };
  2328. /**
  2329. * Add another vector with the current one
  2330. * @param otherVector defines the other vector
  2331. * @returns a new Vector2 set with the addition of the current Vector2 and the given one coordinates
  2332. */
  2333. Vector2.prototype.add = function (otherVector) {
  2334. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2335. };
  2336. /**
  2337. * Sets the "result" coordinates with the addition of the current Vector2 and the given one coordinates
  2338. * @param otherVector defines the other vector
  2339. * @param result defines the target vector
  2340. * @returns the unmodified current Vector2
  2341. */
  2342. Vector2.prototype.addToRef = function (otherVector, result) {
  2343. result.x = this.x + otherVector.x;
  2344. result.y = this.y + otherVector.y;
  2345. return this;
  2346. };
  2347. /**
  2348. * Set the Vector2 coordinates by adding the given Vector2 coordinates
  2349. * @param otherVector defines the other vector
  2350. * @returns the current updated Vector2
  2351. */
  2352. Vector2.prototype.addInPlace = function (otherVector) {
  2353. this.x += otherVector.x;
  2354. this.y += otherVector.y;
  2355. return this;
  2356. };
  2357. /**
  2358. * Gets a new Vector2 by adding the current Vector2 coordinates to the given Vector3 x, y coordinates
  2359. * @param otherVector defines the other vector
  2360. * @returns a new Vector2
  2361. */
  2362. Vector2.prototype.addVector3 = function (otherVector) {
  2363. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2364. };
  2365. /**
  2366. * Gets a new Vector2 set with the subtracted coordinates of the given one from the current Vector2
  2367. * @param otherVector defines the other vector
  2368. * @returns a new Vector2
  2369. */
  2370. Vector2.prototype.subtract = function (otherVector) {
  2371. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  2372. };
  2373. /**
  2374. * Sets the "result" coordinates with the subtraction of the given one from the current Vector2 coordinates.
  2375. * @param otherVector defines the other vector
  2376. * @param result defines the target vector
  2377. * @returns the unmodified current Vector2
  2378. */
  2379. Vector2.prototype.subtractToRef = function (otherVector, result) {
  2380. result.x = this.x - otherVector.x;
  2381. result.y = this.y - otherVector.y;
  2382. return this;
  2383. };
  2384. /**
  2385. * Sets the current Vector2 coordinates by subtracting from it the given one coordinates
  2386. * @param otherVector defines the other vector
  2387. * @returns the current updated Vector2
  2388. */
  2389. Vector2.prototype.subtractInPlace = function (otherVector) {
  2390. this.x -= otherVector.x;
  2391. this.y -= otherVector.y;
  2392. return this;
  2393. };
  2394. /**
  2395. * Multiplies in place the current Vector2 coordinates by the given ones
  2396. * @param otherVector defines the other vector
  2397. * @returns the current updated Vector2
  2398. */
  2399. Vector2.prototype.multiplyInPlace = function (otherVector) {
  2400. this.x *= otherVector.x;
  2401. this.y *= otherVector.y;
  2402. return this;
  2403. };
  2404. /**
  2405. * Returns a new Vector2 set with the multiplication of the current Vector2 and the given one coordinates
  2406. * @param otherVector defines the other vector
  2407. * @returns a new Vector2
  2408. */
  2409. Vector2.prototype.multiply = function (otherVector) {
  2410. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  2411. };
  2412. /**
  2413. * Sets "result" coordinates with the multiplication of the current Vector2 and the given one coordinates
  2414. * @param otherVector defines the other vector
  2415. * @param result defines the target vector
  2416. * @returns the unmodified current Vector2
  2417. */
  2418. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  2419. result.x = this.x * otherVector.x;
  2420. result.y = this.y * otherVector.y;
  2421. return this;
  2422. };
  2423. /**
  2424. * Gets a new Vector2 set with the Vector2 coordinates multiplied by the given floats
  2425. * @param x defines the first coordinate
  2426. * @param y defines the second coordinate
  2427. * @returns a new Vector2
  2428. */
  2429. Vector2.prototype.multiplyByFloats = function (x, y) {
  2430. return new Vector2(this.x * x, this.y * y);
  2431. };
  2432. /**
  2433. * Returns a new Vector2 set with the Vector2 coordinates divided by the given one coordinates
  2434. * @param otherVector defines the other vector
  2435. * @returns a new Vector2
  2436. */
  2437. Vector2.prototype.divide = function (otherVector) {
  2438. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  2439. };
  2440. /**
  2441. * Sets the "result" coordinates with the Vector2 divided by the given one coordinates
  2442. * @param otherVector defines the other vector
  2443. * @param result defines the target vector
  2444. * @returns the unmodified current Vector2
  2445. */
  2446. Vector2.prototype.divideToRef = function (otherVector, result) {
  2447. result.x = this.x / otherVector.x;
  2448. result.y = this.y / otherVector.y;
  2449. return this;
  2450. };
  2451. /**
  2452. * Divides the current Vector2 coordinates by the given ones
  2453. * @param otherVector defines the other vector
  2454. * @returns the current updated Vector2
  2455. */
  2456. Vector2.prototype.divideInPlace = function (otherVector) {
  2457. return this.divideToRef(otherVector, this);
  2458. };
  2459. /**
  2460. * Gets a new Vector2 with current Vector2 negated coordinates
  2461. * @returns a new Vector2
  2462. */
  2463. Vector2.prototype.negate = function () {
  2464. return new Vector2(-this.x, -this.y);
  2465. };
  2466. /**
  2467. * Multiply the Vector2 coordinates by scale
  2468. * @param scale defines the scaling factor
  2469. * @returns the current updated Vector2
  2470. */
  2471. Vector2.prototype.scaleInPlace = function (scale) {
  2472. this.x *= scale;
  2473. this.y *= scale;
  2474. return this;
  2475. };
  2476. /**
  2477. * Returns a new Vector2 scaled by "scale" from the current Vector2
  2478. * @param scale defines the scaling factor
  2479. * @returns a new Vector2
  2480. */
  2481. Vector2.prototype.scale = function (scale) {
  2482. var result = new Vector2(0, 0);
  2483. this.scaleToRef(scale, result);
  2484. return result;
  2485. };
  2486. /**
  2487. * Scale the current Vector2 values by a factor to a given Vector2
  2488. * @param scale defines the scale factor
  2489. * @param result defines the Vector2 object where to store the result
  2490. * @returns the unmodified current Vector2
  2491. */
  2492. Vector2.prototype.scaleToRef = function (scale, result) {
  2493. result.x = this.x * scale;
  2494. result.y = this.y * scale;
  2495. return this;
  2496. };
  2497. /**
  2498. * Scale the current Vector2 values by a factor and add the result to a given Vector2
  2499. * @param scale defines the scale factor
  2500. * @param result defines the Vector2 object where to store the result
  2501. * @returns the unmodified current Vector2
  2502. */
  2503. Vector2.prototype.scaleAndAddToRef = function (scale, result) {
  2504. result.x += this.x * scale;
  2505. result.y += this.y * scale;
  2506. return this;
  2507. };
  2508. /**
  2509. * Gets a boolean if two vectors are equals
  2510. * @param otherVector defines the other vector
  2511. * @returns true if the given vector coordinates strictly equal the current Vector2 ones
  2512. */
  2513. Vector2.prototype.equals = function (otherVector) {
  2514. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  2515. };
  2516. /**
  2517. * Gets a boolean if two vectors are equals (using an epsilon value)
  2518. * @param otherVector defines the other vector
  2519. * @param epsilon defines the minimal distance to consider equality
  2520. * @returns true if the given vector coordinates are close to the current ones by a distance of epsilon.
  2521. */
  2522. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2523. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2524. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon);
  2525. };
  2526. /**
  2527. * Gets a new Vector2 from current Vector2 floored values
  2528. * @returns a new Vector2
  2529. */
  2530. Vector2.prototype.floor = function () {
  2531. return new Vector2(Math.floor(this.x), Math.floor(this.y));
  2532. };
  2533. /**
  2534. * Gets a new Vector2 from current Vector2 floored values
  2535. * @returns a new Vector2
  2536. */
  2537. Vector2.prototype.fract = function () {
  2538. return new Vector2(this.x - Math.floor(this.x), this.y - Math.floor(this.y));
  2539. };
  2540. // Properties
  2541. /**
  2542. * Gets the length of the vector
  2543. * @returns the vector length (float)
  2544. */
  2545. Vector2.prototype.length = function () {
  2546. return Math.sqrt(this.x * this.x + this.y * this.y);
  2547. };
  2548. /**
  2549. * Gets the vector squared length
  2550. * @returns the vector squared length (float)
  2551. */
  2552. Vector2.prototype.lengthSquared = function () {
  2553. return (this.x * this.x + this.y * this.y);
  2554. };
  2555. // Methods
  2556. /**
  2557. * Normalize the vector
  2558. * @returns the current updated Vector2
  2559. */
  2560. Vector2.prototype.normalize = function () {
  2561. var len = this.length();
  2562. if (len === 0)
  2563. return this;
  2564. var num = 1.0 / len;
  2565. this.x *= num;
  2566. this.y *= num;
  2567. return this;
  2568. };
  2569. /**
  2570. * Gets a new Vector2 copied from the Vector2
  2571. * @returns a new Vector2
  2572. */
  2573. Vector2.prototype.clone = function () {
  2574. return new Vector2(this.x, this.y);
  2575. };
  2576. // Statics
  2577. /**
  2578. * Gets a new Vector2(0, 0)
  2579. * @returns a new Vector2
  2580. */
  2581. Vector2.Zero = function () {
  2582. return new Vector2(0, 0);
  2583. };
  2584. /**
  2585. * Gets a new Vector2(1, 1)
  2586. * @returns a new Vector2
  2587. */
  2588. Vector2.One = function () {
  2589. return new Vector2(1, 1);
  2590. };
  2591. /**
  2592. * Gets a new Vector2 set from the given index element of the given array
  2593. * @param array defines the data source
  2594. * @param offset defines the offset in the data source
  2595. * @returns a new Vector2
  2596. */
  2597. Vector2.FromArray = function (array, offset) {
  2598. if (offset === void 0) { offset = 0; }
  2599. return new Vector2(array[offset], array[offset + 1]);
  2600. };
  2601. /**
  2602. * Sets "result" from the given index element of the given array
  2603. * @param array defines the data source
  2604. * @param offset defines the offset in the data source
  2605. * @param result defines the target vector
  2606. */
  2607. Vector2.FromArrayToRef = function (array, offset, result) {
  2608. result.x = array[offset];
  2609. result.y = array[offset + 1];
  2610. };
  2611. /**
  2612. * Gets a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the given four Vector2
  2613. * @param value1 defines 1st point of control
  2614. * @param value2 defines 2nd point of control
  2615. * @param value3 defines 3rd point of control
  2616. * @param value4 defines 4th point of control
  2617. * @param amount defines the interpolation factor
  2618. * @returns a new Vector2
  2619. */
  2620. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  2621. var squared = amount * amount;
  2622. var cubed = amount * squared;
  2623. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  2624. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  2625. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  2626. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  2627. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  2628. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  2629. return new Vector2(x, y);
  2630. };
  2631. /**
  2632. * 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".
  2633. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  2634. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate
  2635. * @param value defines the value to clamp
  2636. * @param min defines the lower limit
  2637. * @param max defines the upper limit
  2638. * @returns a new Vector2
  2639. */
  2640. Vector2.Clamp = function (value, min, max) {
  2641. var x = value.x;
  2642. x = (x > max.x) ? max.x : x;
  2643. x = (x < min.x) ? min.x : x;
  2644. var y = value.y;
  2645. y = (y > max.y) ? max.y : y;
  2646. y = (y < min.y) ? min.y : y;
  2647. return new Vector2(x, y);
  2648. };
  2649. /**
  2650. * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2"
  2651. * @param value1 defines the 1st control point
  2652. * @param tangent1 defines the outgoing tangent
  2653. * @param value2 defines the 2nd control point
  2654. * @param tangent2 defines the incoming tangent
  2655. * @param amount defines the interpolation factor
  2656. * @returns a new Vector2
  2657. */
  2658. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  2659. var squared = amount * amount;
  2660. var cubed = amount * squared;
  2661. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  2662. var part2 = (-2.0 * cubed) + (3.0 * squared);
  2663. var part3 = (cubed - (2.0 * squared)) + amount;
  2664. var part4 = cubed - squared;
  2665. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  2666. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  2667. return new Vector2(x, y);
  2668. };
  2669. /**
  2670. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  2671. * @param start defines the start vector
  2672. * @param end defines the end vector
  2673. * @param amount defines the interpolation factor
  2674. * @returns a new Vector2
  2675. */
  2676. Vector2.Lerp = function (start, end, amount) {
  2677. var x = start.x + ((end.x - start.x) * amount);
  2678. var y = start.y + ((end.y - start.y) * amount);
  2679. return new Vector2(x, y);
  2680. };
  2681. /**
  2682. * Gets the dot product of the vector "left" and the vector "right"
  2683. * @param left defines first vector
  2684. * @param right defines second vector
  2685. * @returns the dot product (float)
  2686. */
  2687. Vector2.Dot = function (left, right) {
  2688. return left.x * right.x + left.y * right.y;
  2689. };
  2690. /**
  2691. * Returns a new Vector2 equal to the normalized given vector
  2692. * @param vector defines the vector to normalize
  2693. * @returns a new Vector2
  2694. */
  2695. Vector2.Normalize = function (vector) {
  2696. var newVector = vector.clone();
  2697. newVector.normalize();
  2698. return newVector;
  2699. };
  2700. /**
  2701. * Gets a new Vector2 set with the minimal coordinate values from the "left" and "right" vectors
  2702. * @param left defines 1st vector
  2703. * @param right defines 2nd vector
  2704. * @returns a new Vector2
  2705. */
  2706. Vector2.Minimize = function (left, right) {
  2707. var x = (left.x < right.x) ? left.x : right.x;
  2708. var y = (left.y < right.y) ? left.y : right.y;
  2709. return new Vector2(x, y);
  2710. };
  2711. /**
  2712. * Gets a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors
  2713. * @param left defines 1st vector
  2714. * @param right defines 2nd vector
  2715. * @returns a new Vector2
  2716. */
  2717. Vector2.Maximize = function (left, right) {
  2718. var x = (left.x > right.x) ? left.x : right.x;
  2719. var y = (left.y > right.y) ? left.y : right.y;
  2720. return new Vector2(x, y);
  2721. };
  2722. /**
  2723. * Gets a new Vector2 set with the transformed coordinates of the given vector by the given transformation matrix
  2724. * @param vector defines the vector to transform
  2725. * @param transformation defines the matrix to apply
  2726. * @returns a new Vector2
  2727. */
  2728. Vector2.Transform = function (vector, transformation) {
  2729. var r = Vector2.Zero();
  2730. Vector2.TransformToRef(vector, transformation, r);
  2731. return r;
  2732. };
  2733. /**
  2734. * Transforms the given vector coordinates by the given transformation matrix and stores the result in the vector "result" coordinates
  2735. * @param vector defines the vector to transform
  2736. * @param transformation defines the matrix to apply
  2737. * @param result defines the target vector
  2738. */
  2739. Vector2.TransformToRef = function (vector, transformation, result) {
  2740. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  2741. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  2742. result.x = x;
  2743. result.y = y;
  2744. };
  2745. /**
  2746. * Determines if a given vector is included in a triangle
  2747. * @param p defines the vector to test
  2748. * @param p0 defines 1st triangle point
  2749. * @param p1 defines 2nd triangle point
  2750. * @param p2 defines 3rd triangle point
  2751. * @returns true if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  2752. */
  2753. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  2754. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  2755. var sign = a < 0 ? -1 : 1;
  2756. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  2757. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  2758. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  2759. };
  2760. /**
  2761. * Gets the distance between the vectors "value1" and "value2"
  2762. * @param value1 defines first vector
  2763. * @param value2 defines second vector
  2764. * @returns the distance between vectors
  2765. */
  2766. Vector2.Distance = function (value1, value2) {
  2767. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  2768. };
  2769. /**
  2770. * Returns the squared distance between the vectors "value1" and "value2"
  2771. * @param value1 defines first vector
  2772. * @param value2 defines second vector
  2773. * @returns the squared distance between vectors
  2774. */
  2775. Vector2.DistanceSquared = function (value1, value2) {
  2776. var x = value1.x - value2.x;
  2777. var y = value1.y - value2.y;
  2778. return (x * x) + (y * y);
  2779. };
  2780. /**
  2781. * Gets a new Vector2 located at the center of the vectors "value1" and "value2"
  2782. * @param value1 defines first vector
  2783. * @param value2 defines second vector
  2784. * @returns a new Vector2
  2785. */
  2786. Vector2.Center = function (value1, value2) {
  2787. var center = value1.add(value2);
  2788. center.scaleInPlace(0.5);
  2789. return center;
  2790. };
  2791. /**
  2792. * Gets the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  2793. * @param p defines the middle point
  2794. * @param segA defines one point of the segment
  2795. * @param segB defines the other point of the segment
  2796. * @returns the shortest distance
  2797. */
  2798. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  2799. var l2 = Vector2.DistanceSquared(segA, segB);
  2800. if (l2 === 0.0) {
  2801. return Vector2.Distance(p, segA);
  2802. }
  2803. var v = segB.subtract(segA);
  2804. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  2805. var proj = segA.add(v.multiplyByFloats(t, t));
  2806. return Vector2.Distance(p, proj);
  2807. };
  2808. return Vector2;
  2809. }());
  2810. BABYLON.Vector2 = Vector2;
  2811. /**
  2812. * Classed used to store (x,y,z) vector representation
  2813. * A Vector3 is the main object used in 3D geometry
  2814. * It can represent etiher the coordinates of a point the space, either a direction
  2815. * Reminder: Babylon.js uses a left handed forward facing system
  2816. */
  2817. var Vector3 = /** @class */ (function () {
  2818. /**
  2819. * Creates a new Vector3 object from the given x, y, z (floats) coordinates.
  2820. * @param x defines the first coordinates (on X axis)
  2821. * @param y defines the second coordinates (on Y axis)
  2822. * @param z defines the third coordinates (on Z axis)
  2823. */
  2824. function Vector3(
  2825. /**
  2826. * Defines the first coordinates (on X axis)
  2827. */
  2828. x,
  2829. /**
  2830. * Defines the second coordinates (on Y axis)
  2831. */
  2832. y,
  2833. /**
  2834. * Defines the third coordinates (on Z axis)
  2835. */
  2836. z) {
  2837. if (x === void 0) { x = 0; }
  2838. if (y === void 0) { y = 0; }
  2839. if (z === void 0) { z = 0; }
  2840. this.x = x;
  2841. this.y = y;
  2842. this.z = z;
  2843. }
  2844. /**
  2845. * Creates a string representation of the Vector3
  2846. * @returns a string with the Vector3 coordinates.
  2847. */
  2848. Vector3.prototype.toString = function () {
  2849. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  2850. };
  2851. /**
  2852. * Gets the class name
  2853. * @returns the string "Vector3"
  2854. */
  2855. Vector3.prototype.getClassName = function () {
  2856. return "Vector3";
  2857. };
  2858. /**
  2859. * Creates the Vector3 hash code
  2860. * @returns a number which tends to be unique between Vector3 instances
  2861. */
  2862. Vector3.prototype.getHashCode = function () {
  2863. var hash = this.x || 0;
  2864. hash = (hash * 397) ^ (this.y || 0);
  2865. hash = (hash * 397) ^ (this.z || 0);
  2866. return hash;
  2867. };
  2868. // Operators
  2869. /**
  2870. * Creates an array containing three elements : the coordinates of the Vector3
  2871. * @returns a new array of numbers
  2872. */
  2873. Vector3.prototype.asArray = function () {
  2874. var result = [];
  2875. this.toArray(result, 0);
  2876. return result;
  2877. };
  2878. /**
  2879. * Populates the given array or Float32Array from the given index with the successive coordinates of the Vector3
  2880. * @param array defines the destination array
  2881. * @param index defines the offset in the destination array
  2882. * @returns the current Vector3
  2883. */
  2884. Vector3.prototype.toArray = function (array, index) {
  2885. if (index === void 0) { index = 0; }
  2886. array[index] = this.x;
  2887. array[index + 1] = this.y;
  2888. array[index + 2] = this.z;
  2889. return this;
  2890. };
  2891. /**
  2892. * Converts the current Vector3 into a quaternion (considering that the Vector3 contains Euler angles representation of a rotation)
  2893. * @returns a new Quaternion object, computed from the Vector3 coordinates
  2894. */
  2895. Vector3.prototype.toQuaternion = function () {
  2896. return BABYLON.Quaternion.RotationYawPitchRoll(this.x, this.y, this.z);
  2897. };
  2898. /**
  2899. * Adds the given vector to the current Vector3
  2900. * @param otherVector defines the second operand
  2901. * @returns the current updated Vector3
  2902. */
  2903. Vector3.prototype.addInPlace = function (otherVector) {
  2904. this.x += otherVector.x;
  2905. this.y += otherVector.y;
  2906. this.z += otherVector.z;
  2907. return this;
  2908. };
  2909. /**
  2910. * Gets a new Vector3, result of the addition the current Vector3 and the given vector
  2911. * @param otherVector defines the second operand
  2912. * @returns the resulting Vector3
  2913. */
  2914. Vector3.prototype.add = function (otherVector) {
  2915. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  2916. };
  2917. /**
  2918. * Adds the current Vector3 to the given one and stores the result in the vector "result"
  2919. * @param otherVector defines the second operand
  2920. * @param result defines the Vector3 object where to store the result
  2921. * @returns the current Vector3
  2922. */
  2923. Vector3.prototype.addToRef = function (otherVector, result) {
  2924. result.x = this.x + otherVector.x;
  2925. result.y = this.y + otherVector.y;
  2926. result.z = this.z + otherVector.z;
  2927. return this;
  2928. };
  2929. /**
  2930. * Subtract the given vector from the current Vector3
  2931. * @param otherVector defines the second operand
  2932. * @returns the current updated Vector3
  2933. */
  2934. Vector3.prototype.subtractInPlace = function (otherVector) {
  2935. this.x -= otherVector.x;
  2936. this.y -= otherVector.y;
  2937. this.z -= otherVector.z;
  2938. return this;
  2939. };
  2940. /**
  2941. * Returns a new Vector3, result of the subtraction of the given vector from the current Vector3
  2942. * @param otherVector defines the second operand
  2943. * @returns the resulting Vector3
  2944. */
  2945. Vector3.prototype.subtract = function (otherVector) {
  2946. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  2947. };
  2948. /**
  2949. * Subtracts the given vector from the current Vector3 and stores the result in the vector "result".
  2950. * @param otherVector defines the second operand
  2951. * @param result defines the Vector3 object where to store the result
  2952. * @returns the current Vector3
  2953. */
  2954. Vector3.prototype.subtractToRef = function (otherVector, result) {
  2955. result.x = this.x - otherVector.x;
  2956. result.y = this.y - otherVector.y;
  2957. result.z = this.z - otherVector.z;
  2958. return this;
  2959. };
  2960. /**
  2961. * Returns a new Vector3 set with the subtraction of the given floats from the current Vector3 coordinates
  2962. * @param x defines the x coordinate of the operand
  2963. * @param y defines the y coordinate of the operand
  2964. * @param z defines the z coordinate of the operand
  2965. * @returns the resulting Vector3
  2966. */
  2967. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  2968. return new Vector3(this.x - x, this.y - y, this.z - z);
  2969. };
  2970. /**
  2971. * Subtracts the given floats from the current Vector3 coordinates and set the given vector "result" with this result
  2972. * @param x defines the x coordinate of the operand
  2973. * @param y defines the y coordinate of the operand
  2974. * @param z defines the z coordinate of the operand
  2975. * @param result defines the Vector3 object where to store the result
  2976. * @returns the current Vector3
  2977. */
  2978. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  2979. result.x = this.x - x;
  2980. result.y = this.y - y;
  2981. result.z = this.z - z;
  2982. return this;
  2983. };
  2984. /**
  2985. * Gets a new Vector3 set with the current Vector3 negated coordinates
  2986. * @returns a new Vector3
  2987. */
  2988. Vector3.prototype.negate = function () {
  2989. return new Vector3(-this.x, -this.y, -this.z);
  2990. };
  2991. /**
  2992. * Multiplies the Vector3 coordinates by the float "scale"
  2993. * @param scale defines the multiplier factor
  2994. * @returns the current updated Vector3
  2995. */
  2996. Vector3.prototype.scaleInPlace = function (scale) {
  2997. this.x *= scale;
  2998. this.y *= scale;
  2999. this.z *= scale;
  3000. return this;
  3001. };
  3002. /**
  3003. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale"
  3004. * @param scale defines the multiplier factor
  3005. * @returns a new Vector3
  3006. */
  3007. Vector3.prototype.scale = function (scale) {
  3008. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  3009. };
  3010. /**
  3011. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the given vector "result" coordinates
  3012. * @param scale defines the multiplier factor
  3013. * @param result defines the Vector3 object where to store the result
  3014. * @returns the current Vector3
  3015. */
  3016. Vector3.prototype.scaleToRef = function (scale, result) {
  3017. result.x = this.x * scale;
  3018. result.y = this.y * scale;
  3019. result.z = this.z * scale;
  3020. return this;
  3021. };
  3022. /**
  3023. * Scale the current Vector3 values by a factor and add the result to a given Vector3
  3024. * @param scale defines the scale factor
  3025. * @param result defines the Vector3 object where to store the result
  3026. * @returns the unmodified current Vector3
  3027. */
  3028. Vector3.prototype.scaleAndAddToRef = function (scale, result) {
  3029. result.x += this.x * scale;
  3030. result.y += this.y * scale;
  3031. result.z += this.z * scale;
  3032. return this;
  3033. };
  3034. /**
  3035. * Returns true if the current Vector3 and the given vector coordinates are strictly equal
  3036. * @param otherVector defines the second operand
  3037. * @returns true if both vectors are equals
  3038. */
  3039. Vector3.prototype.equals = function (otherVector) {
  3040. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  3041. };
  3042. /**
  3043. * Returns true if the current Vector3 and the given vector coordinates are distant less than epsilon
  3044. * @param otherVector defines the second operand
  3045. * @param epsilon defines the minimal distance to define values as equals
  3046. * @returns true if both vectors are distant less than epsilon
  3047. */
  3048. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  3049. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  3050. 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);
  3051. };
  3052. /**
  3053. * Returns true if the current Vector3 coordinates equals the given floats
  3054. * @param x defines the x coordinate of the operand
  3055. * @param y defines the y coordinate of the operand
  3056. * @param z defines the z coordinate of the operand
  3057. * @returns true if both vectors are equals
  3058. */
  3059. Vector3.prototype.equalsToFloats = function (x, y, z) {
  3060. return this.x === x && this.y === y && this.z === z;
  3061. };
  3062. /**
  3063. * Multiplies the current Vector3 coordinates by the given ones
  3064. * @param otherVector defines the second operand
  3065. * @returns the current updated Vector3
  3066. */
  3067. Vector3.prototype.multiplyInPlace = function (otherVector) {
  3068. this.x *= otherVector.x;
  3069. this.y *= otherVector.y;
  3070. this.z *= otherVector.z;
  3071. return this;
  3072. };
  3073. /**
  3074. * Returns a new Vector3, result of the multiplication of the current Vector3 by the given vector
  3075. * @param otherVector defines the second operand
  3076. * @returns the new Vector3
  3077. */
  3078. Vector3.prototype.multiply = function (otherVector) {
  3079. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  3080. };
  3081. /**
  3082. * Multiplies the current Vector3 by the given one and stores the result in the given vector "result"
  3083. * @param otherVector defines the second operand
  3084. * @param result defines the Vector3 object where to store the result
  3085. * @returns the current Vector3
  3086. */
  3087. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  3088. result.x = this.x * otherVector.x;
  3089. result.y = this.y * otherVector.y;
  3090. result.z = this.z * otherVector.z;
  3091. return this;
  3092. };
  3093. /**
  3094. * Returns a new Vector3 set with the result of the mulliplication of the current Vector3 coordinates by the given floats
  3095. * @param x defines the x coordinate of the operand
  3096. * @param y defines the y coordinate of the operand
  3097. * @param z defines the z coordinate of the operand
  3098. * @returns the new Vector3
  3099. */
  3100. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  3101. return new Vector3(this.x * x, this.y * y, this.z * z);
  3102. };
  3103. /**
  3104. * Returns a new Vector3 set with the result of the division of the current Vector3 coordinates by the given ones
  3105. * @param otherVector defines the second operand
  3106. * @returns the new Vector3
  3107. */
  3108. Vector3.prototype.divide = function (otherVector) {
  3109. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  3110. };
  3111. /**
  3112. * Divides the current Vector3 coordinates by the given ones and stores the result in the given vector "result"
  3113. * @param otherVector defines the second operand
  3114. * @param result defines the Vector3 object where to store the result
  3115. * @returns the current Vector3
  3116. */
  3117. Vector3.prototype.divideToRef = function (otherVector, result) {
  3118. result.x = this.x / otherVector.x;
  3119. result.y = this.y / otherVector.y;
  3120. result.z = this.z / otherVector.z;
  3121. return this;
  3122. };
  3123. /**
  3124. * Divides the current Vector3 coordinates by the given ones.
  3125. * @param otherVector defines the second operand
  3126. * @returns the current updated Vector3
  3127. */
  3128. Vector3.prototype.divideInPlace = function (otherVector) {
  3129. return this.divideToRef(otherVector, this);
  3130. };
  3131. /**
  3132. * Updates the current Vector3 with the minimal coordinate values between its and the given vector ones
  3133. * @param other defines the second operand
  3134. * @returns the current updated Vector3
  3135. */
  3136. Vector3.prototype.minimizeInPlace = function (other) {
  3137. if (other.x < this.x)
  3138. this.x = other.x;
  3139. if (other.y < this.y)
  3140. this.y = other.y;
  3141. if (other.z < this.z)
  3142. this.z = other.z;
  3143. return this;
  3144. };
  3145. /**
  3146. * Updates the current Vector3 with the maximal coordinate values between its and the given vector ones.
  3147. * @param other defines the second operand
  3148. * @returns the current updated Vector3
  3149. */
  3150. Vector3.prototype.maximizeInPlace = function (other) {
  3151. if (other.x > this.x)
  3152. this.x = other.x;
  3153. if (other.y > this.y)
  3154. this.y = other.y;
  3155. if (other.z > this.z)
  3156. this.z = other.z;
  3157. return this;
  3158. };
  3159. Object.defineProperty(Vector3.prototype, "isNonUniform", {
  3160. /**
  3161. * Gets a boolean indicating that the vector is non uniform meaning x, y or z are not all the same
  3162. */
  3163. get: function () {
  3164. var absX = Math.abs(this.x);
  3165. var absY = Math.abs(this.y);
  3166. if (absX !== absY) {
  3167. return true;
  3168. }
  3169. var absZ = Math.abs(this.z);
  3170. if (absX !== absZ) {
  3171. return true;
  3172. }
  3173. if (absY !== absZ) {
  3174. return true;
  3175. }
  3176. return false;
  3177. },
  3178. enumerable: true,
  3179. configurable: true
  3180. });
  3181. /**
  3182. * Gets a new Vector3 from current Vector3 floored values
  3183. * @returns a new Vector3
  3184. */
  3185. Vector3.prototype.floor = function () {
  3186. return new Vector3(Math.floor(this.x), Math.floor(this.y), Math.floor(this.z));
  3187. };
  3188. /**
  3189. * Gets a new Vector3 from current Vector3 floored values
  3190. * @returns a new Vector3
  3191. */
  3192. Vector3.prototype.fract = function () {
  3193. return new Vector3(this.x - Math.floor(this.x), this.y - Math.floor(this.y), this.z - Math.floor(this.z));
  3194. };
  3195. // Properties
  3196. /**
  3197. * Gets the length of the Vector3
  3198. * @returns the length of the Vecto3
  3199. */
  3200. Vector3.prototype.length = function () {
  3201. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  3202. };
  3203. /**
  3204. * Gets the squared length of the Vector3
  3205. * @returns squared length of the Vector3
  3206. */
  3207. Vector3.prototype.lengthSquared = function () {
  3208. return (this.x * this.x + this.y * this.y + this.z * this.z);
  3209. };
  3210. /**
  3211. * Normalize the current Vector3.
  3212. * Please note that this is an in place operation.
  3213. * @returns the current updated Vector3
  3214. */
  3215. Vector3.prototype.normalize = function () {
  3216. var len = this.length();
  3217. if (len === 0 || len === 1.0)
  3218. return this;
  3219. var num = 1.0 / len;
  3220. this.x *= num;
  3221. this.y *= num;
  3222. this.z *= num;
  3223. return this;
  3224. };
  3225. /**
  3226. * Normalize the current Vector3 to a new vector
  3227. * @returns the new Vector3
  3228. */
  3229. Vector3.prototype.normalizeToNew = function () {
  3230. var normalized = new Vector3(0, 0, 0);
  3231. this.normalizeToRef(normalized);
  3232. return normalized;
  3233. };
  3234. /**
  3235. * Normalize the current Vector3 to the reference
  3236. * @param reference define the Vector3 to update
  3237. * @returns the updated Vector3
  3238. */
  3239. Vector3.prototype.normalizeToRef = function (reference) {
  3240. var len = this.length();
  3241. if (len === 0 || len === 1.0) {
  3242. reference.set(this.x, this.y, this.z);
  3243. return reference;
  3244. }
  3245. var scale = 1.0 / len;
  3246. this.scaleToRef(scale, reference);
  3247. return reference;
  3248. };
  3249. /**
  3250. * Creates a new Vector3 copied from the current Vector3
  3251. * @returns the new Vector3
  3252. */
  3253. Vector3.prototype.clone = function () {
  3254. return new Vector3(this.x, this.y, this.z);
  3255. };
  3256. /**
  3257. * Copies the given vector coordinates to the current Vector3 ones
  3258. * @param source defines the source Vector3
  3259. * @returns the current updated Vector3
  3260. */
  3261. Vector3.prototype.copyFrom = function (source) {
  3262. this.x = source.x;
  3263. this.y = source.y;
  3264. this.z = source.z;
  3265. return this;
  3266. };
  3267. /**
  3268. * Copies the given floats to the current Vector3 coordinates
  3269. * @param x defines the x coordinate of the operand
  3270. * @param y defines the y coordinate of the operand
  3271. * @param z defines the z coordinate of the operand
  3272. * @returns the current updated Vector3
  3273. */
  3274. Vector3.prototype.copyFromFloats = function (x, y, z) {
  3275. this.x = x;
  3276. this.y = y;
  3277. this.z = z;
  3278. return this;
  3279. };
  3280. /**
  3281. * Copies the given floats to the current Vector3 coordinates
  3282. * @param x defines the x coordinate of the operand
  3283. * @param y defines the y coordinate of the operand
  3284. * @param z defines the z coordinate of the operand
  3285. * @returns the current updated Vector3
  3286. */
  3287. Vector3.prototype.set = function (x, y, z) {
  3288. return this.copyFromFloats(x, y, z);
  3289. };
  3290. // Statics
  3291. /**
  3292. * Get the clip factor between two vectors
  3293. * @param vector0 defines the first operand
  3294. * @param vector1 defines the second operand
  3295. * @param axis defines the axis to use
  3296. * @param size defines the size along the axis
  3297. * @returns the clip factor
  3298. */
  3299. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  3300. var d0 = Vector3.Dot(vector0, axis) - size;
  3301. var d1 = Vector3.Dot(vector1, axis) - size;
  3302. var s = d0 / (d0 - d1);
  3303. return s;
  3304. };
  3305. /**
  3306. * Get angle between two vectors
  3307. * @param vector0 angle between vector0 and vector1
  3308. * @param vector1 angle between vector0 and vector1
  3309. * @param normal direction of the normal
  3310. * @return the angle between vector0 and vector1
  3311. */
  3312. Vector3.GetAngleBetweenVectors = function (vector0, vector1, normal) {
  3313. var v0 = vector0.clone().normalize();
  3314. var v1 = vector1.clone().normalize();
  3315. var dot = Vector3.Dot(v0, v1);
  3316. var n = Vector3.Cross(v0, v1);
  3317. if (Vector3.Dot(n, normal) > 0) {
  3318. return Math.acos(dot);
  3319. }
  3320. return -Math.acos(dot);
  3321. };
  3322. /**
  3323. * Returns a new Vector3 set from the index "offset" of the given array
  3324. * @param array defines the source array
  3325. * @param offset defines the offset in the source array
  3326. * @returns the new Vector3
  3327. */
  3328. Vector3.FromArray = function (array, offset) {
  3329. if (!offset) {
  3330. offset = 0;
  3331. }
  3332. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  3333. };
  3334. /**
  3335. * Returns a new Vector3 set from the index "offset" of the given Float32Array
  3336. * This function is deprecated. Use FromArray instead
  3337. * @param array defines the source array
  3338. * @param offset defines the offset in the source array
  3339. * @returns the new Vector3
  3340. */
  3341. Vector3.FromFloatArray = function (array, offset) {
  3342. return Vector3.FromArray(array, offset);
  3343. };
  3344. /**
  3345. * Sets the given vector "result" with the element values from the index "offset" of the given array
  3346. * @param array defines the source array
  3347. * @param offset defines the offset in the source array
  3348. * @param result defines the Vector3 where to store the result
  3349. */
  3350. Vector3.FromArrayToRef = function (array, offset, result) {
  3351. result.x = array[offset];
  3352. result.y = array[offset + 1];
  3353. result.z = array[offset + 2];
  3354. };
  3355. /**
  3356. * Sets the given vector "result" with the element values from the index "offset" of the given Float32Array
  3357. * This function is deprecated. Use FromArrayToRef instead.
  3358. * @param array defines the source array
  3359. * @param offset defines the offset in the source array
  3360. * @param result defines the Vector3 where to store the result
  3361. */
  3362. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  3363. return Vector3.FromArrayToRef(array, offset, result);
  3364. };
  3365. /**
  3366. * Sets the given vector "result" with the given floats.
  3367. * @param x defines the x coordinate of the source
  3368. * @param y defines the y coordinate of the source
  3369. * @param z defines the z coordinate of the source
  3370. * @param result defines the Vector3 where to store the result
  3371. */
  3372. Vector3.FromFloatsToRef = function (x, y, z, result) {
  3373. result.x = x;
  3374. result.y = y;
  3375. result.z = z;
  3376. };
  3377. /**
  3378. * Returns a new Vector3 set to (0.0, 0.0, 0.0)
  3379. * @returns a new empty Vector3
  3380. */
  3381. Vector3.Zero = function () {
  3382. return new Vector3(0.0, 0.0, 0.0);
  3383. };
  3384. /**
  3385. * Returns a new Vector3 set to (1.0, 1.0, 1.0)
  3386. * @returns a new unit Vector3
  3387. */
  3388. Vector3.One = function () {
  3389. return new Vector3(1.0, 1.0, 1.0);
  3390. };
  3391. /**
  3392. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  3393. * @returns a new up Vector3
  3394. */
  3395. Vector3.Up = function () {
  3396. return new Vector3(0.0, 1.0, 0.0);
  3397. };
  3398. /**
  3399. * Returns a new Vector3 set to (0.0, -1.0, 0.0)
  3400. * @returns a new down Vector3
  3401. */
  3402. Vector3.Down = function () {
  3403. return new Vector3(0.0, -1.0, 0.0);
  3404. };
  3405. /**
  3406. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  3407. * @returns a new forward Vector3
  3408. */
  3409. Vector3.Forward = function () {
  3410. return new Vector3(0.0, 0.0, 1.0);
  3411. };
  3412. /**
  3413. * Returns a new Vector3 set to (0.0, 0.0, -1.0)
  3414. * @returns a new forward Vector3
  3415. */
  3416. Vector3.Backward = function () {
  3417. return new Vector3(0.0, 0.0, -1.0);
  3418. };
  3419. /**
  3420. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  3421. * @returns a new right Vector3
  3422. */
  3423. Vector3.Right = function () {
  3424. return new Vector3(1.0, 0.0, 0.0);
  3425. };
  3426. /**
  3427. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  3428. * @returns a new left Vector3
  3429. */
  3430. Vector3.Left = function () {
  3431. return new Vector3(-1.0, 0.0, 0.0);
  3432. };
  3433. /**
  3434. * Returns a new Vector3 set with the result of the transformation by the given matrix of the given vector.
  3435. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3436. * @param vector defines the Vector3 to transform
  3437. * @param transformation defines the transformation matrix
  3438. * @returns the transformed Vector3
  3439. */
  3440. Vector3.TransformCoordinates = function (vector, transformation) {
  3441. var result = Vector3.Zero();
  3442. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  3443. return result;
  3444. };
  3445. /**
  3446. * Sets the given vector "result" coordinates with the result of the transformation by the given matrix of the given vector
  3447. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3448. * @param vector defines the Vector3 to transform
  3449. * @param transformation defines the transformation matrix
  3450. * @param result defines the Vector3 where to store the result
  3451. */
  3452. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  3453. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  3454. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  3455. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  3456. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  3457. result.x = x / w;
  3458. result.y = y / w;
  3459. result.z = z / w;
  3460. };
  3461. /**
  3462. * Sets the given vector "result" coordinates with the result of the transformation by the given matrix of the given floats (x, y, z)
  3463. * This method computes tranformed coordinates only, not transformed direction vectors
  3464. * @param x define the x coordinate of the source vector
  3465. * @param y define the y coordinate of the source vector
  3466. * @param z define the z coordinate of the source vector
  3467. * @param transformation defines the transformation matrix
  3468. * @param result defines the Vector3 where to store the result
  3469. */
  3470. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  3471. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  3472. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  3473. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  3474. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  3475. result.x = rx / rw;
  3476. result.y = ry / rw;
  3477. result.z = rz / rw;
  3478. };
  3479. /**
  3480. * Returns a new Vector3 set with the result of the normal transformation by the given matrix of the given vector
  3481. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3482. * @param vector defines the Vector3 to transform
  3483. * @param transformation defines the transformation matrix
  3484. * @returns the new Vector3
  3485. */
  3486. Vector3.TransformNormal = function (vector, transformation) {
  3487. var result = Vector3.Zero();
  3488. Vector3.TransformNormalToRef(vector, transformation, result);
  3489. return result;
  3490. };
  3491. /**
  3492. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given vector
  3493. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3494. * @param vector defines the Vector3 to transform
  3495. * @param transformation defines the transformation matrix
  3496. * @param result defines the Vector3 where to store the result
  3497. */
  3498. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  3499. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  3500. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  3501. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  3502. result.x = x;
  3503. result.y = y;
  3504. result.z = z;
  3505. };
  3506. /**
  3507. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given floats (x, y, z)
  3508. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3509. * @param x define the x coordinate of the source vector
  3510. * @param y define the y coordinate of the source vector
  3511. * @param z define the z coordinate of the source vector
  3512. * @param transformation defines the transformation matrix
  3513. * @param result defines the Vector3 where to store the result
  3514. */
  3515. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  3516. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  3517. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  3518. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  3519. };
  3520. /**
  3521. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4"
  3522. * @param value1 defines the first control point
  3523. * @param value2 defines the second control point
  3524. * @param value3 defines the third control point
  3525. * @param value4 defines the fourth control point
  3526. * @param amount defines the amount on the spline to use
  3527. * @returns the new Vector3
  3528. */
  3529. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  3530. var squared = amount * amount;
  3531. var cubed = amount * squared;
  3532. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  3533. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  3534. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  3535. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  3536. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  3537. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  3538. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  3539. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  3540. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  3541. return new Vector3(x, y, z);
  3542. };
  3543. /**
  3544. * 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"
  3545. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one
  3546. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one
  3547. * @param value defines the current value
  3548. * @param min defines the lower range value
  3549. * @param max defines the upper range value
  3550. * @returns the new Vector3
  3551. */
  3552. Vector3.Clamp = function (value, min, max) {
  3553. var x = value.x;
  3554. x = (x > max.x) ? max.x : x;
  3555. x = (x < min.x) ? min.x : x;
  3556. var y = value.y;
  3557. y = (y > max.y) ? max.y : y;
  3558. y = (y < min.y) ? min.y : y;
  3559. var z = value.z;
  3560. z = (z > max.z) ? max.z : z;
  3561. z = (z < min.z) ? min.z : z;
  3562. return new Vector3(x, y, z);
  3563. };
  3564. /**
  3565. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2"
  3566. * @param value1 defines the first control point
  3567. * @param tangent1 defines the first tangent vector
  3568. * @param value2 defines the second control point
  3569. * @param tangent2 defines the second tangent vector
  3570. * @param amount defines the amount on the interpolation spline (between 0 and 1)
  3571. * @returns the new Vector3
  3572. */
  3573. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  3574. var squared = amount * amount;
  3575. var cubed = amount * squared;
  3576. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  3577. var part2 = (-2.0 * cubed) + (3.0 * squared);
  3578. var part3 = (cubed - (2.0 * squared)) + amount;
  3579. var part4 = cubed - squared;
  3580. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  3581. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  3582. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  3583. return new Vector3(x, y, z);
  3584. };
  3585. /**
  3586. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end"
  3587. * @param start defines the start value
  3588. * @param end defines the end value
  3589. * @param amount max defines amount between both (between 0 and 1)
  3590. * @returns the new Vector3
  3591. */
  3592. Vector3.Lerp = function (start, end, amount) {
  3593. var result = new Vector3(0, 0, 0);
  3594. Vector3.LerpToRef(start, end, amount, result);
  3595. return result;
  3596. };
  3597. /**
  3598. * Sets the given vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end"
  3599. * @param start defines the start value
  3600. * @param end defines the end value
  3601. * @param amount max defines amount between both (between 0 and 1)
  3602. * @param result defines the Vector3 where to store the result
  3603. */
  3604. Vector3.LerpToRef = function (start, end, amount, result) {
  3605. result.x = start.x + ((end.x - start.x) * amount);
  3606. result.y = start.y + ((end.y - start.y) * amount);
  3607. result.z = start.z + ((end.z - start.z) * amount);
  3608. };
  3609. /**
  3610. * Returns the dot product (float) between the vectors "left" and "right"
  3611. * @param left defines the left operand
  3612. * @param right defines the right operand
  3613. * @returns the dot product
  3614. */
  3615. Vector3.Dot = function (left, right) {
  3616. return (left.x * right.x + left.y * right.y + left.z * right.z);
  3617. };
  3618. /**
  3619. * Returns a new Vector3 as the cross product of the vectors "left" and "right"
  3620. * The cross product is then orthogonal to both "left" and "right"
  3621. * @param left defines the left operand
  3622. * @param right defines the right operand
  3623. * @returns the cross product
  3624. */
  3625. Vector3.Cross = function (left, right) {
  3626. var result = Vector3.Zero();
  3627. Vector3.CrossToRef(left, right, result);
  3628. return result;
  3629. };
  3630. /**
  3631. * Sets the given vector "result" with the cross product of "left" and "right"
  3632. * The cross product is then orthogonal to both "left" and "right"
  3633. * @param left defines the left operand
  3634. * @param right defines the right operand
  3635. * @param result defines the Vector3 where to store the result
  3636. */
  3637. Vector3.CrossToRef = function (left, right, result) {
  3638. MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  3639. MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  3640. MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  3641. result.copyFrom(MathTmp.Vector3[0]);
  3642. };
  3643. /**
  3644. * Returns a new Vector3 as the normalization of the given vector
  3645. * @param vector defines the Vector3 to normalize
  3646. * @returns the new Vector3
  3647. */
  3648. Vector3.Normalize = function (vector) {
  3649. var result = Vector3.Zero();
  3650. Vector3.NormalizeToRef(vector, result);
  3651. return result;
  3652. };
  3653. /**
  3654. * Sets the given vector "result" with the normalization of the given first vector
  3655. * @param vector defines the Vector3 to normalize
  3656. * @param result defines the Vector3 where to store the result
  3657. */
  3658. Vector3.NormalizeToRef = function (vector, result) {
  3659. result.copyFrom(vector);
  3660. result.normalize();
  3661. };
  3662. /**
  3663. * Project a Vector3 onto screen space
  3664. * @param vector defines the Vector3 to project
  3665. * @param world defines the world matrix to use
  3666. * @param transform defines the transform (view x projection) matrix to use
  3667. * @param viewport defines the screen viewport to use
  3668. * @returns the new Vector3
  3669. */
  3670. Vector3.Project = function (vector, world, transform, viewport) {
  3671. var cw = viewport.width;
  3672. var ch = viewport.height;
  3673. var cx = viewport.x;
  3674. var cy = viewport.y;
  3675. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  3676. 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);
  3677. var matrix = MathTmp.Matrix[0];
  3678. world.multiplyToRef(transform, matrix);
  3679. matrix.multiplyToRef(viewportMatrix, matrix);
  3680. return Vector3.TransformCoordinates(vector, matrix);
  3681. };
  3682. /**
  3683. * Unproject from screen space to object space
  3684. * @param source defines the screen space Vector3 to use
  3685. * @param viewportWidth defines the current width of the viewport
  3686. * @param viewportHeight defines the current height of the viewport
  3687. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3688. * @param transform defines the transform (view x projection) matrix to use
  3689. * @returns the new Vector3
  3690. */
  3691. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  3692. var matrix = MathTmp.Matrix[0];
  3693. world.multiplyToRef(transform, matrix);
  3694. matrix.invert();
  3695. source.x = source.x / viewportWidth * 2 - 1;
  3696. source.y = -(source.y / viewportHeight * 2 - 1);
  3697. var vector = Vector3.TransformCoordinates(source, matrix);
  3698. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  3699. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3700. vector = vector.scale(1.0 / num);
  3701. }
  3702. return vector;
  3703. };
  3704. /**
  3705. * Unproject from screen space to object space
  3706. * @param source defines the screen space Vector3 to use
  3707. * @param viewportWidth defines the current width of the viewport
  3708. * @param viewportHeight defines the current height of the viewport
  3709. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3710. * @param view defines the view matrix to use
  3711. * @param projection defines the projection matrix to use
  3712. * @returns the new Vector3
  3713. */
  3714. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  3715. var result = Vector3.Zero();
  3716. Vector3.UnprojectToRef(source, viewportWidth, viewportHeight, world, view, projection, result);
  3717. return result;
  3718. };
  3719. /**
  3720. * Unproject from screen space to object space
  3721. * @param source defines the screen space Vector3 to use
  3722. * @param viewportWidth defines the current width of the viewport
  3723. * @param viewportHeight defines the current height of the viewport
  3724. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3725. * @param view defines the view matrix to use
  3726. * @param projection defines the projection matrix to use
  3727. * @param result defines the Vector3 where to store the result
  3728. */
  3729. Vector3.UnprojectToRef = function (source, viewportWidth, viewportHeight, world, view, projection, result) {
  3730. Vector3.UnprojectFloatsToRef(source.x, source.y, source.z, viewportWidth, viewportHeight, world, view, projection, result);
  3731. };
  3732. /**
  3733. * Unproject from screen space to object space
  3734. * @param sourceX defines the screen space x coordinate to use
  3735. * @param sourceY defines the screen space y coordinate to use
  3736. * @param sourceZ defines the screen space z coordinate to use
  3737. * @param viewportWidth defines the current width of the viewport
  3738. * @param viewportHeight defines the current height of the viewport
  3739. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3740. * @param view defines the view matrix to use
  3741. * @param projection defines the projection matrix to use
  3742. * @param result defines the Vector3 where to store the result
  3743. */
  3744. Vector3.UnprojectFloatsToRef = function (sourceX, sourceY, sourceZ, viewportWidth, viewportHeight, world, view, projection, result) {
  3745. var matrix = MathTmp.Matrix[0];
  3746. world.multiplyToRef(view, matrix);
  3747. matrix.multiplyToRef(projection, matrix);
  3748. matrix.invert();
  3749. var screenSource = MathTmp.Vector3[0];
  3750. screenSource.x = sourceX / viewportWidth * 2 - 1;
  3751. screenSource.y = -(sourceY / viewportHeight * 2 - 1);
  3752. screenSource.z = 2 * sourceZ - 1.0;
  3753. Vector3.TransformCoordinatesToRef(screenSource, matrix, result);
  3754. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  3755. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3756. result.scaleInPlace(1.0 / num);
  3757. }
  3758. };
  3759. /**
  3760. * Gets the minimal coordinate values between two Vector3
  3761. * @param left defines the first operand
  3762. * @param right defines the second operand
  3763. * @returns the new Vector3
  3764. */
  3765. Vector3.Minimize = function (left, right) {
  3766. var min = left.clone();
  3767. min.minimizeInPlace(right);
  3768. return min;
  3769. };
  3770. /**
  3771. * Gets the maximal coordinate values between two Vector3
  3772. * @param left defines the first operand
  3773. * @param right defines the second operand
  3774. * @returns the new Vector3
  3775. */
  3776. Vector3.Maximize = function (left, right) {
  3777. var max = left.clone();
  3778. max.maximizeInPlace(right);
  3779. return max;
  3780. };
  3781. /**
  3782. * Returns the distance between the vectors "value1" and "value2"
  3783. * @param value1 defines the first operand
  3784. * @param value2 defines the second operand
  3785. * @returns the distance
  3786. */
  3787. Vector3.Distance = function (value1, value2) {
  3788. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  3789. };
  3790. /**
  3791. * Returns the squared distance between the vectors "value1" and "value2"
  3792. * @param value1 defines the first operand
  3793. * @param value2 defines the second operand
  3794. * @returns the squared distance
  3795. */
  3796. Vector3.DistanceSquared = function (value1, value2) {
  3797. var x = value1.x - value2.x;
  3798. var y = value1.y - value2.y;
  3799. var z = value1.z - value2.z;
  3800. return (x * x) + (y * y) + (z * z);
  3801. };
  3802. /**
  3803. * Returns a new Vector3 located at the center between "value1" and "value2"
  3804. * @param value1 defines the first operand
  3805. * @param value2 defines the second operand
  3806. * @returns the new Vector3
  3807. */
  3808. Vector3.Center = function (value1, value2) {
  3809. var center = value1.add(value2);
  3810. center.scaleInPlace(0.5);
  3811. return center;
  3812. };
  3813. /**
  3814. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  3815. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  3816. * to something in order to rotate it from its local system to the given target system
  3817. * Note: axis1, axis2 and axis3 are normalized during this operation
  3818. * @param axis1 defines the first axis
  3819. * @param axis2 defines the second axis
  3820. * @param axis3 defines the third axis
  3821. * @returns a new Vector3
  3822. */
  3823. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  3824. var rotation = Vector3.Zero();
  3825. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  3826. return rotation;
  3827. };
  3828. /**
  3829. * The same than RotationFromAxis but updates the given ref Vector3 parameter instead of returning a new Vector3
  3830. * @param axis1 defines the first axis
  3831. * @param axis2 defines the second axis
  3832. * @param axis3 defines the third axis
  3833. * @param ref defines the Vector3 where to store the result
  3834. */
  3835. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  3836. var quat = MathTmp.Quaternion[0];
  3837. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  3838. quat.toEulerAnglesToRef(ref);
  3839. };
  3840. return Vector3;
  3841. }());
  3842. BABYLON.Vector3 = Vector3;
  3843. //Vector4 class created for EulerAngle class conversion to Quaternion
  3844. var Vector4 = /** @class */ (function () {
  3845. /**
  3846. * Creates a Vector4 object from the given floats.
  3847. */
  3848. function Vector4(x, y, z, w) {
  3849. this.x = x;
  3850. this.y = y;
  3851. this.z = z;
  3852. this.w = w;
  3853. }
  3854. /**
  3855. * Returns the string with the Vector4 coordinates.
  3856. */
  3857. Vector4.prototype.toString = function () {
  3858. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  3859. };
  3860. /**
  3861. * Returns the string "Vector4".
  3862. */
  3863. Vector4.prototype.getClassName = function () {
  3864. return "Vector4";
  3865. };
  3866. /**
  3867. * Returns the Vector4 hash code.
  3868. */
  3869. Vector4.prototype.getHashCode = function () {
  3870. var hash = this.x || 0;
  3871. hash = (hash * 397) ^ (this.y || 0);
  3872. hash = (hash * 397) ^ (this.z || 0);
  3873. hash = (hash * 397) ^ (this.w || 0);
  3874. return hash;
  3875. };
  3876. // Operators
  3877. /**
  3878. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  3879. */
  3880. Vector4.prototype.asArray = function () {
  3881. var result = new Array();
  3882. this.toArray(result, 0);
  3883. return result;
  3884. };
  3885. /**
  3886. * Populates the given array from the given index with the Vector4 coordinates.
  3887. * Returns the Vector4.
  3888. */
  3889. Vector4.prototype.toArray = function (array, index) {
  3890. if (index === undefined) {
  3891. index = 0;
  3892. }
  3893. array[index] = this.x;
  3894. array[index + 1] = this.y;
  3895. array[index + 2] = this.z;
  3896. array[index + 3] = this.w;
  3897. return this;
  3898. };
  3899. /**
  3900. * Adds the given vector to the current Vector4.
  3901. * Returns the updated Vector4.
  3902. */
  3903. Vector4.prototype.addInPlace = function (otherVector) {
  3904. this.x += otherVector.x;
  3905. this.y += otherVector.y;
  3906. this.z += otherVector.z;
  3907. this.w += otherVector.w;
  3908. return this;
  3909. };
  3910. /**
  3911. * Returns a new Vector4 as the result of the addition of the current Vector4 and the given one.
  3912. */
  3913. Vector4.prototype.add = function (otherVector) {
  3914. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  3915. };
  3916. /**
  3917. * Updates the given vector "result" with the result of the addition of the current Vector4 and the given one.
  3918. * Returns the current Vector4.
  3919. */
  3920. Vector4.prototype.addToRef = function (otherVector, result) {
  3921. result.x = this.x + otherVector.x;
  3922. result.y = this.y + otherVector.y;
  3923. result.z = this.z + otherVector.z;
  3924. result.w = this.w + otherVector.w;
  3925. return this;
  3926. };
  3927. /**
  3928. * Subtract in place the given vector from the current Vector4.
  3929. * Returns the updated Vector4.
  3930. */
  3931. Vector4.prototype.subtractInPlace = function (otherVector) {
  3932. this.x -= otherVector.x;
  3933. this.y -= otherVector.y;
  3934. this.z -= otherVector.z;
  3935. this.w -= otherVector.w;
  3936. return this;
  3937. };
  3938. /**
  3939. * Returns a new Vector4 with the result of the subtraction of the given vector from the current Vector4.
  3940. */
  3941. Vector4.prototype.subtract = function (otherVector) {
  3942. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  3943. };
  3944. /**
  3945. * Sets the given vector "result" with the result of the subtraction of the given vector from the current Vector4.
  3946. * Returns the current Vector4.
  3947. */
  3948. Vector4.prototype.subtractToRef = function (otherVector, result) {
  3949. result.x = this.x - otherVector.x;
  3950. result.y = this.y - otherVector.y;
  3951. result.z = this.z - otherVector.z;
  3952. result.w = this.w - otherVector.w;
  3953. return this;
  3954. };
  3955. /**
  3956. * Returns a new Vector4 set with the result of the subtraction of the given floats from the current Vector4 coordinates.
  3957. */
  3958. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  3959. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  3960. };
  3961. /**
  3962. * Sets the given vector "result" set with the result of the subtraction of the given floats from the current Vector4 coordinates.
  3963. * Returns the current Vector4.
  3964. */
  3965. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  3966. result.x = this.x - x;
  3967. result.y = this.y - y;
  3968. result.z = this.z - z;
  3969. result.w = this.w - w;
  3970. return this;
  3971. };
  3972. /**
  3973. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  3974. */
  3975. Vector4.prototype.negate = function () {
  3976. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  3977. };
  3978. /**
  3979. * Multiplies the current Vector4 coordinates by scale (float).
  3980. * Returns the updated Vector4.
  3981. */
  3982. Vector4.prototype.scaleInPlace = function (scale) {
  3983. this.x *= scale;
  3984. this.y *= scale;
  3985. this.z *= scale;
  3986. this.w *= scale;
  3987. return this;
  3988. };
  3989. /**
  3990. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  3991. */
  3992. Vector4.prototype.scale = function (scale) {
  3993. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  3994. };
  3995. /**
  3996. * Sets the given vector "result" with the current Vector4 coordinates multiplied by scale (float).
  3997. * Returns the current Vector4.
  3998. */
  3999. Vector4.prototype.scaleToRef = function (scale, result) {
  4000. result.x = this.x * scale;
  4001. result.y = this.y * scale;
  4002. result.z = this.z * scale;
  4003. result.w = this.w * scale;
  4004. return this;
  4005. };
  4006. /**
  4007. * Scale the current Vector4 values by a factor and add the result to a given Vector4
  4008. * @param scale defines the scale factor
  4009. * @param result defines the Vector4 object where to store the result
  4010. * @returns the unmodified current Vector4
  4011. */
  4012. Vector4.prototype.scaleAndAddToRef = function (scale, result) {
  4013. result.x += this.x * scale;
  4014. result.y += this.y * scale;
  4015. result.z += this.z * scale;
  4016. result.w += this.w * scale;
  4017. return this;
  4018. };
  4019. /**
  4020. * Boolean : True if the current Vector4 coordinates are stricly equal to the given ones.
  4021. */
  4022. Vector4.prototype.equals = function (otherVector) {
  4023. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  4024. };
  4025. /**
  4026. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the given vector ones.
  4027. */
  4028. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  4029. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  4030. return otherVector
  4031. && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon)
  4032. && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon)
  4033. && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon)
  4034. && BABYLON.Scalar.WithinEpsilon(this.w, otherVector.w, epsilon);
  4035. };
  4036. /**
  4037. * Boolean : True if the given floats are strictly equal to the current Vector4 coordinates.
  4038. */
  4039. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  4040. return this.x === x && this.y === y && this.z === z && this.w === w;
  4041. };
  4042. /**
  4043. * Multiplies in place the current Vector4 by the given one.
  4044. * Returns the updated Vector4.
  4045. */
  4046. Vector4.prototype.multiplyInPlace = function (otherVector) {
  4047. this.x *= otherVector.x;
  4048. this.y *= otherVector.y;
  4049. this.z *= otherVector.z;
  4050. this.w *= otherVector.w;
  4051. return this;
  4052. };
  4053. /**
  4054. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the given one.
  4055. */
  4056. Vector4.prototype.multiply = function (otherVector) {
  4057. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  4058. };
  4059. /**
  4060. * Updates the given vector "result" with the multiplication result of the current Vector4 and the given one.
  4061. * Returns the current Vector4.
  4062. */
  4063. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  4064. result.x = this.x * otherVector.x;
  4065. result.y = this.y * otherVector.y;
  4066. result.z = this.z * otherVector.z;
  4067. result.w = this.w * otherVector.w;
  4068. return this;
  4069. };
  4070. /**
  4071. * Returns a new Vector4 set with the multiplication result of the given floats and the current Vector4 coordinates.
  4072. */
  4073. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  4074. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  4075. };
  4076. /**
  4077. * Returns a new Vector4 set with the division result of the current Vector4 by the given one.
  4078. */
  4079. Vector4.prototype.divide = function (otherVector) {
  4080. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  4081. };
  4082. /**
  4083. * Updates the given vector "result" with the division result of the current Vector4 by the given one.
  4084. * Returns the current Vector4.
  4085. */
  4086. Vector4.prototype.divideToRef = function (otherVector, result) {
  4087. result.x = this.x / otherVector.x;
  4088. result.y = this.y / otherVector.y;
  4089. result.z = this.z / otherVector.z;
  4090. result.w = this.w / otherVector.w;
  4091. return this;
  4092. };
  4093. /**
  4094. * Divides the current Vector3 coordinates by the given ones.
  4095. * @returns the updated Vector3.
  4096. */
  4097. Vector4.prototype.divideInPlace = function (otherVector) {
  4098. return this.divideToRef(otherVector, this);
  4099. };
  4100. /**
  4101. * Updates the Vector4 coordinates with the minimum values between its own and the given vector ones
  4102. * @param other defines the second operand
  4103. * @returns the current updated Vector4
  4104. */
  4105. Vector4.prototype.minimizeInPlace = function (other) {
  4106. if (other.x < this.x)
  4107. this.x = other.x;
  4108. if (other.y < this.y)
  4109. this.y = other.y;
  4110. if (other.z < this.z)
  4111. this.z = other.z;
  4112. if (other.w < this.w)
  4113. this.w = other.w;
  4114. return this;
  4115. };
  4116. /**
  4117. * Updates the Vector4 coordinates with the maximum values between its own and the given vector ones
  4118. * @param other defines the second operand
  4119. * @returns the current updated Vector4
  4120. */
  4121. Vector4.prototype.maximizeInPlace = function (other) {
  4122. if (other.x > this.x)
  4123. this.x = other.x;
  4124. if (other.y > this.y)
  4125. this.y = other.y;
  4126. if (other.z > this.z)
  4127. this.z = other.z;
  4128. if (other.w > this.w)
  4129. this.w = other.w;
  4130. return this;
  4131. };
  4132. /**
  4133. * Gets a new Vector4 from current Vector4 floored values
  4134. * @returns a new Vector4
  4135. */
  4136. Vector4.prototype.floor = function () {
  4137. return new Vector4(Math.floor(this.x), Math.floor(this.y), Math.floor(this.z), Math.floor(this.w));
  4138. };
  4139. /**
  4140. * Gets a new Vector4 from current Vector3 floored values
  4141. * @returns a new Vector4
  4142. */
  4143. Vector4.prototype.fract = function () {
  4144. return new Vector4(this.x - Math.floor(this.x), this.y - Math.floor(this.y), this.z - Math.floor(this.z), this.w - Math.floor(this.w));
  4145. };
  4146. // Properties
  4147. /**
  4148. * Returns the Vector4 length (float).
  4149. */
  4150. Vector4.prototype.length = function () {
  4151. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  4152. };
  4153. /**
  4154. * Returns the Vector4 squared length (float).
  4155. */
  4156. Vector4.prototype.lengthSquared = function () {
  4157. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  4158. };
  4159. // Methods
  4160. /**
  4161. * Normalizes in place the Vector4.
  4162. * Returns the updated Vector4.
  4163. */
  4164. Vector4.prototype.normalize = function () {
  4165. var len = this.length();
  4166. if (len === 0)
  4167. return this;
  4168. var num = 1.0 / len;
  4169. this.x *= num;
  4170. this.y *= num;
  4171. this.z *= num;
  4172. this.w *= num;
  4173. return this;
  4174. };
  4175. /**
  4176. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  4177. */
  4178. Vector4.prototype.toVector3 = function () {
  4179. return new Vector3(this.x, this.y, this.z);
  4180. };
  4181. /**
  4182. * Returns a new Vector4 copied from the current one.
  4183. */
  4184. Vector4.prototype.clone = function () {
  4185. return new Vector4(this.x, this.y, this.z, this.w);
  4186. };
  4187. /**
  4188. * Updates the current Vector4 with the given one coordinates.
  4189. * Returns the updated Vector4.
  4190. */
  4191. Vector4.prototype.copyFrom = function (source) {
  4192. this.x = source.x;
  4193. this.y = source.y;
  4194. this.z = source.z;
  4195. this.w = source.w;
  4196. return this;
  4197. };
  4198. /**
  4199. * Updates the current Vector4 coordinates with the given floats.
  4200. * Returns the updated Vector4.
  4201. */
  4202. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  4203. this.x = x;
  4204. this.y = y;
  4205. this.z = z;
  4206. this.w = w;
  4207. return this;
  4208. };
  4209. /**
  4210. * Updates the current Vector4 coordinates with the given floats.
  4211. * Returns the updated Vector4.
  4212. */
  4213. Vector4.prototype.set = function (x, y, z, w) {
  4214. return this.copyFromFloats(x, y, z, w);
  4215. };
  4216. // Statics
  4217. /**
  4218. * Returns a new Vector4 set from the starting index of the given array.
  4219. */
  4220. Vector4.FromArray = function (array, offset) {
  4221. if (!offset) {
  4222. offset = 0;
  4223. }
  4224. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4225. };
  4226. /**
  4227. * Updates the given vector "result" from the starting index of the given array.
  4228. */
  4229. Vector4.FromArrayToRef = function (array, offset, result) {
  4230. result.x = array[offset];
  4231. result.y = array[offset + 1];
  4232. result.z = array[offset + 2];
  4233. result.w = array[offset + 3];
  4234. };
  4235. /**
  4236. * Updates the given vector "result" from the starting index of the given Float32Array.
  4237. */
  4238. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  4239. Vector4.FromArrayToRef(array, offset, result);
  4240. };
  4241. /**
  4242. * Updates the given vector "result" coordinates from the given floats.
  4243. */
  4244. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  4245. result.x = x;
  4246. result.y = y;
  4247. result.z = z;
  4248. result.w = w;
  4249. };
  4250. /**
  4251. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  4252. */
  4253. Vector4.Zero = function () {
  4254. return new Vector4(0.0, 0.0, 0.0, 0.0);
  4255. };
  4256. /**
  4257. * Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0)
  4258. */
  4259. Vector4.One = function () {
  4260. return new Vector4(1.0, 1.0, 1.0, 1.0);
  4261. };
  4262. /**
  4263. * Returns a new normalized Vector4 from the given one.
  4264. */
  4265. Vector4.Normalize = function (vector) {
  4266. var result = Vector4.Zero();
  4267. Vector4.NormalizeToRef(vector, result);
  4268. return result;
  4269. };
  4270. /**
  4271. * Updates the given vector "result" from the normalization of the given one.
  4272. */
  4273. Vector4.NormalizeToRef = function (vector, result) {
  4274. result.copyFrom(vector);
  4275. result.normalize();
  4276. };
  4277. Vector4.Minimize = function (left, right) {
  4278. var min = left.clone();
  4279. min.minimizeInPlace(right);
  4280. return min;
  4281. };
  4282. Vector4.Maximize = function (left, right) {
  4283. var max = left.clone();
  4284. max.maximizeInPlace(right);
  4285. return max;
  4286. };
  4287. /**
  4288. * Returns the distance (float) between the vectors "value1" and "value2".
  4289. */
  4290. Vector4.Distance = function (value1, value2) {
  4291. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  4292. };
  4293. /**
  4294. * Returns the squared distance (float) between the vectors "value1" and "value2".
  4295. */
  4296. Vector4.DistanceSquared = function (value1, value2) {
  4297. var x = value1.x - value2.x;
  4298. var y = value1.y - value2.y;
  4299. var z = value1.z - value2.z;
  4300. var w = value1.w - value2.w;
  4301. return (x * x) + (y * y) + (z * z) + (w * w);
  4302. };
  4303. /**
  4304. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  4305. */
  4306. Vector4.Center = function (value1, value2) {
  4307. var center = value1.add(value2);
  4308. center.scaleInPlace(0.5);
  4309. return center;
  4310. };
  4311. /**
  4312. * Returns a new Vector4 set with the result of the normal transformation by the given matrix of the given vector.
  4313. * This methods computes transformed normalized direction vectors only.
  4314. */
  4315. Vector4.TransformNormal = function (vector, transformation) {
  4316. var result = Vector4.Zero();
  4317. Vector4.TransformNormalToRef(vector, transformation, result);
  4318. return result;
  4319. };
  4320. /**
  4321. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given vector.
  4322. * This methods computes transformed normalized direction vectors only.
  4323. */
  4324. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  4325. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  4326. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  4327. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  4328. result.x = x;
  4329. result.y = y;
  4330. result.z = z;
  4331. result.w = vector.w;
  4332. };
  4333. /**
  4334. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given floats (x, y, z, w).
  4335. * This methods computes transformed normalized direction vectors only.
  4336. */
  4337. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  4338. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  4339. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  4340. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  4341. result.w = w;
  4342. };
  4343. return Vector4;
  4344. }());
  4345. BABYLON.Vector4 = Vector4;
  4346. var Size = /** @class */ (function () {
  4347. /**
  4348. * Creates a Size object from the given width and height (floats).
  4349. */
  4350. function Size(width, height) {
  4351. this.width = width;
  4352. this.height = height;
  4353. }
  4354. // Returns a string with the Size width and height.
  4355. Size.prototype.toString = function () {
  4356. return "{W: " + this.width + ", H: " + this.height + "}";
  4357. };
  4358. /**
  4359. * Returns the string "Size"
  4360. */
  4361. Size.prototype.getClassName = function () {
  4362. return "Size";
  4363. };
  4364. /**
  4365. * Returns the Size hash code.
  4366. */
  4367. Size.prototype.getHashCode = function () {
  4368. var hash = this.width || 0;
  4369. hash = (hash * 397) ^ (this.height || 0);
  4370. return hash;
  4371. };
  4372. /**
  4373. * Updates the current size from the given one.
  4374. * Returns the updated Size.
  4375. */
  4376. Size.prototype.copyFrom = function (src) {
  4377. this.width = src.width;
  4378. this.height = src.height;
  4379. };
  4380. /**
  4381. * Updates in place the current Size from the given floats.
  4382. * Returns the updated Size.
  4383. */
  4384. Size.prototype.copyFromFloats = function (width, height) {
  4385. this.width = width;
  4386. this.height = height;
  4387. return this;
  4388. };
  4389. /**
  4390. * Updates in place the current Size from the given floats.
  4391. * Returns the updated Size.
  4392. */
  4393. Size.prototype.set = function (width, height) {
  4394. return this.copyFromFloats(width, height);
  4395. };
  4396. /**
  4397. * Returns a new Size set with the multiplication result of the current Size and the given floats.
  4398. */
  4399. Size.prototype.multiplyByFloats = function (w, h) {
  4400. return new Size(this.width * w, this.height * h);
  4401. };
  4402. /**
  4403. * Returns a new Size copied from the given one.
  4404. */
  4405. Size.prototype.clone = function () {
  4406. return new Size(this.width, this.height);
  4407. };
  4408. /**
  4409. * Boolean : True if the current Size and the given one width and height are strictly equal.
  4410. */
  4411. Size.prototype.equals = function (other) {
  4412. if (!other) {
  4413. return false;
  4414. }
  4415. return (this.width === other.width) && (this.height === other.height);
  4416. };
  4417. Object.defineProperty(Size.prototype, "surface", {
  4418. /**
  4419. * Returns the surface of the Size : width * height (float).
  4420. */
  4421. get: function () {
  4422. return this.width * this.height;
  4423. },
  4424. enumerable: true,
  4425. configurable: true
  4426. });
  4427. /**
  4428. * Returns a new Size set to (0.0, 0.0)
  4429. */
  4430. Size.Zero = function () {
  4431. return new Size(0.0, 0.0);
  4432. };
  4433. /**
  4434. * Returns a new Size set as the addition result of the current Size and the given one.
  4435. */
  4436. Size.prototype.add = function (otherSize) {
  4437. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  4438. return r;
  4439. };
  4440. /**
  4441. * Returns a new Size set as the subtraction result of the given one from the current Size.
  4442. */
  4443. Size.prototype.subtract = function (otherSize) {
  4444. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  4445. return r;
  4446. };
  4447. /**
  4448. * Returns a new Size set at the linear interpolation "amount" between "start" and "end".
  4449. */
  4450. Size.Lerp = function (start, end, amount) {
  4451. var w = start.width + ((end.width - start.width) * amount);
  4452. var h = start.height + ((end.height - start.height) * amount);
  4453. return new Size(w, h);
  4454. };
  4455. return Size;
  4456. }());
  4457. BABYLON.Size = Size;
  4458. /**
  4459. * Class used to store quaternion data
  4460. * @see https://en.wikipedia.org/wiki/Quaternion
  4461. * @see http://doc.babylonjs.com/features/position,_rotation,_scaling
  4462. */
  4463. var Quaternion = /** @class */ (function () {
  4464. /**
  4465. * Creates a new Quaternion from the given floats
  4466. * @param x defines the first component (0 by default)
  4467. * @param y defines the second component (0 by default)
  4468. * @param z defines the third component (0 by default)
  4469. * @param w defines the fourth component (1.0 by default)
  4470. */
  4471. function Quaternion(
  4472. /** defines the first component (0 by default) */
  4473. x,
  4474. /** defines the second component (0 by default) */
  4475. y,
  4476. /** defines the third component (0 by default) */
  4477. z,
  4478. /** defines the fourth component (1.0 by default) */
  4479. w) {
  4480. if (x === void 0) { x = 0.0; }
  4481. if (y === void 0) { y = 0.0; }
  4482. if (z === void 0) { z = 0.0; }
  4483. if (w === void 0) { w = 1.0; }
  4484. this.x = x;
  4485. this.y = y;
  4486. this.z = z;
  4487. this.w = w;
  4488. }
  4489. /**
  4490. * Gets a string representation for the current quaternion
  4491. * @returns a string with the Quaternion coordinates
  4492. */
  4493. Quaternion.prototype.toString = function () {
  4494. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  4495. };
  4496. /**
  4497. * Gets the class name of the quaternion
  4498. * @returns the string "Quaternion"
  4499. */
  4500. Quaternion.prototype.getClassName = function () {
  4501. return "Quaternion";
  4502. };
  4503. /**
  4504. * Gets a hash code for this quaternion
  4505. * @returns the quaternion hash code
  4506. */
  4507. Quaternion.prototype.getHashCode = function () {
  4508. var hash = this.x || 0;
  4509. hash = (hash * 397) ^ (this.y || 0);
  4510. hash = (hash * 397) ^ (this.z || 0);
  4511. hash = (hash * 397) ^ (this.w || 0);
  4512. return hash;
  4513. };
  4514. /**
  4515. * Copy the quaternion to an array
  4516. * @returns a new array populated with 4 elements from the quaternion coordinates
  4517. */
  4518. Quaternion.prototype.asArray = function () {
  4519. return [this.x, this.y, this.z, this.w];
  4520. };
  4521. /**
  4522. * Check if two quaternions are equals
  4523. * @param otherQuaternion defines the second operand
  4524. * @return true if the current quaternion and the given one coordinates are strictly equals
  4525. */
  4526. Quaternion.prototype.equals = function (otherQuaternion) {
  4527. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  4528. };
  4529. /**
  4530. * Clone the current quaternion
  4531. * @returns a new quaternion copied from the current one
  4532. */
  4533. Quaternion.prototype.clone = function () {
  4534. return new Quaternion(this.x, this.y, this.z, this.w);
  4535. };
  4536. /**
  4537. * Copy a quaternion to the current one
  4538. * @param other defines the other quaternion
  4539. * @returns the updated current quaternion
  4540. */
  4541. Quaternion.prototype.copyFrom = function (other) {
  4542. this.x = other.x;
  4543. this.y = other.y;
  4544. this.z = other.z;
  4545. this.w = other.w;
  4546. return this;
  4547. };
  4548. /**
  4549. * Updates the current quaternion with the given float coordinates
  4550. * @param x defines the x coordinate
  4551. * @param y defines the y coordinate
  4552. * @param z defines the z coordinate
  4553. * @param w defines the w coordinate
  4554. * @returns the updated current quaternion
  4555. */
  4556. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  4557. this.x = x;
  4558. this.y = y;
  4559. this.z = z;
  4560. this.w = w;
  4561. return this;
  4562. };
  4563. /**
  4564. * Updates the current quaternion from the given float coordinates
  4565. * @param x defines the x coordinate
  4566. * @param y defines the y coordinate
  4567. * @param z defines the z coordinate
  4568. * @param w defines the w coordinate
  4569. * @returns the updated current quaternion
  4570. */
  4571. Quaternion.prototype.set = function (x, y, z, w) {
  4572. return this.copyFromFloats(x, y, z, w);
  4573. };
  4574. /**
  4575. * Adds two quaternions
  4576. * @param other defines the second operand
  4577. * @returns a new quaternion as the addition result of the given one and the current quaternion
  4578. */
  4579. Quaternion.prototype.add = function (other) {
  4580. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  4581. };
  4582. /**
  4583. * Add a quaternion to the current one
  4584. * @param other defines the quaternion to add
  4585. * @returns the current quaternion
  4586. */
  4587. Quaternion.prototype.addInPlace = function (other) {
  4588. this.x += other.x;
  4589. this.y += other.y;
  4590. this.z += other.z;
  4591. this.w += other.w;
  4592. return this;
  4593. };
  4594. /**
  4595. * Subtract two quaternions
  4596. * @param other defines the second operand
  4597. * @returns a new quaternion as the subtraction result of the given one from the current one
  4598. */
  4599. Quaternion.prototype.subtract = function (other) {
  4600. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  4601. };
  4602. /**
  4603. * Multiplies the current quaternion by a scale factor
  4604. * @param value defines the scale factor
  4605. * @returns a new quaternion set by multiplying the current quaternion coordinates by the float "scale"
  4606. */
  4607. Quaternion.prototype.scale = function (value) {
  4608. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  4609. };
  4610. /**
  4611. * Scale the current quaternion values by a factor and stores the result to a given quaternion
  4612. * @param scale defines the scale factor
  4613. * @param result defines the Quaternion object where to store the result
  4614. * @returns the unmodified current quaternion
  4615. */
  4616. Quaternion.prototype.scaleToRef = function (scale, result) {
  4617. result.x = this.x * scale;
  4618. result.y = this.y * scale;
  4619. result.z = this.z * scale;
  4620. result.w = this.w * scale;
  4621. return this;
  4622. };
  4623. /**
  4624. * Multiplies in place the current quaternion by a scale factor
  4625. * @param value defines the scale factor
  4626. * @returns the current modified quaternion
  4627. */
  4628. Quaternion.prototype.scaleInPlace = function (value) {
  4629. this.x *= value;
  4630. this.y *= value;
  4631. this.z *= value;
  4632. this.w *= value;
  4633. return this;
  4634. };
  4635. /**
  4636. * Scale the current quaternion values by a factor and add the result to a given quaternion
  4637. * @param scale defines the scale factor
  4638. * @param result defines the Quaternion object where to store the result
  4639. * @returns the unmodified current quaternion
  4640. */
  4641. Quaternion.prototype.scaleAndAddToRef = function (scale, result) {
  4642. result.x += this.x * scale;
  4643. result.y += this.y * scale;
  4644. result.z += this.z * scale;
  4645. result.w += this.w * scale;
  4646. return this;
  4647. };
  4648. /**
  4649. * Multiplies two quaternions
  4650. * @param q1 defines the second operand
  4651. * @returns a new quaternion set as the multiplication result of the current one with the given one "q1"
  4652. */
  4653. Quaternion.prototype.multiply = function (q1) {
  4654. var result = new Quaternion(0, 0, 0, 1.0);
  4655. this.multiplyToRef(q1, result);
  4656. return result;
  4657. };
  4658. /**
  4659. * Sets the given "result" as the the multiplication result of the current one with the given one "q1"
  4660. * @param q1 defines the second operand
  4661. * @param result defines the target quaternion
  4662. * @returns the current quaternion
  4663. */
  4664. Quaternion.prototype.multiplyToRef = function (q1, result) {
  4665. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  4666. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  4667. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  4668. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  4669. result.copyFromFloats(x, y, z, w);
  4670. return this;
  4671. };
  4672. /**
  4673. * Updates the current quaternion with the multiplication of itself with the given one "q1"
  4674. * @param q1 defines the second operand
  4675. * @returns the currentupdated quaternion
  4676. */
  4677. Quaternion.prototype.multiplyInPlace = function (q1) {
  4678. this.multiplyToRef(q1, this);
  4679. return this;
  4680. };
  4681. /**
  4682. * Conjugates (1-q) the current quaternion and stores the result in the given quaternion
  4683. * @param ref defines the target quaternion
  4684. * @returns the current quaternion
  4685. */
  4686. Quaternion.prototype.conjugateToRef = function (ref) {
  4687. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  4688. return this;
  4689. };
  4690. /**
  4691. * Conjugates in place (1-q) the current quaternion
  4692. * @returns the current updated quaternion
  4693. */
  4694. Quaternion.prototype.conjugateInPlace = function () {
  4695. this.x *= -1;
  4696. this.y *= -1;
  4697. this.z *= -1;
  4698. return this;
  4699. };
  4700. /**
  4701. * Conjugates in place (1-q) the current quaternion
  4702. * @returns a new quaternion
  4703. */
  4704. Quaternion.prototype.conjugate = function () {
  4705. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  4706. return result;
  4707. };
  4708. /**
  4709. * Gets length of current quaternion
  4710. * @returns the quaternion length (float)
  4711. */
  4712. Quaternion.prototype.length = function () {
  4713. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  4714. };
  4715. /**
  4716. * Normalize in place the current quaternion
  4717. * @returns the current updated quaternion
  4718. */
  4719. Quaternion.prototype.normalize = function () {
  4720. var length = 1.0 / this.length();
  4721. this.x *= length;
  4722. this.y *= length;
  4723. this.z *= length;
  4724. this.w *= length;
  4725. return this;
  4726. };
  4727. /**
  4728. * Returns a new Vector3 set with the Euler angles translated from the current quaternion
  4729. * @param order is a reserved parameter and is ignore for now
  4730. * @returns a new Vector3 containing the Euler angles
  4731. */
  4732. Quaternion.prototype.toEulerAngles = function (order) {
  4733. if (order === void 0) { order = "YZX"; }
  4734. var result = Vector3.Zero();
  4735. this.toEulerAnglesToRef(result, order);
  4736. return result;
  4737. };
  4738. /**
  4739. * Sets the given vector3 "result" with the Euler angles translated from the current quaternion
  4740. * @param result defines the vector which will be filled with the Euler angles
  4741. * @param order is a reserved parameter and is ignore for now
  4742. * @returns the current unchanged quaternion
  4743. */
  4744. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  4745. if (order === void 0) { order = "YZX"; }
  4746. var qz = this.z;
  4747. var qx = this.x;
  4748. var qy = this.y;
  4749. var qw = this.w;
  4750. var sqw = qw * qw;
  4751. var sqz = qz * qz;
  4752. var sqx = qx * qx;
  4753. var sqy = qy * qy;
  4754. var zAxisY = qy * qz - qx * qw;
  4755. var limit = .4999999;
  4756. if (zAxisY < -limit) {
  4757. result.y = 2 * Math.atan2(qy, qw);
  4758. result.x = Math.PI / 2;
  4759. result.z = 0;
  4760. }
  4761. else if (zAxisY > limit) {
  4762. result.y = 2 * Math.atan2(qy, qw);
  4763. result.x = -Math.PI / 2;
  4764. result.z = 0;
  4765. }
  4766. else {
  4767. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  4768. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  4769. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  4770. }
  4771. return this;
  4772. };
  4773. /**
  4774. * Updates the given rotation matrix with the current quaternion values
  4775. * @param result defines the target matrix
  4776. * @returns the current unchanged quaternion
  4777. */
  4778. Quaternion.prototype.toRotationMatrix = function (result) {
  4779. var xx = this.x * this.x;
  4780. var yy = this.y * this.y;
  4781. var zz = this.z * this.z;
  4782. var xy = this.x * this.y;
  4783. var zw = this.z * this.w;
  4784. var zx = this.z * this.x;
  4785. var yw = this.y * this.w;
  4786. var yz = this.y * this.z;
  4787. var xw = this.x * this.w;
  4788. result.m[0] = 1.0 - (2.0 * (yy + zz));
  4789. result.m[1] = 2.0 * (xy + zw);
  4790. result.m[2] = 2.0 * (zx - yw);
  4791. result.m[3] = 0;
  4792. result.m[4] = 2.0 * (xy - zw);
  4793. result.m[5] = 1.0 - (2.0 * (zz + xx));
  4794. result.m[6] = 2.0 * (yz + xw);
  4795. result.m[7] = 0;
  4796. result.m[8] = 2.0 * (zx + yw);
  4797. result.m[9] = 2.0 * (yz - xw);
  4798. result.m[10] = 1.0 - (2.0 * (yy + xx));
  4799. result.m[11] = 0;
  4800. result.m[12] = 0;
  4801. result.m[13] = 0;
  4802. result.m[14] = 0;
  4803. result.m[15] = 1.0;
  4804. result._markAsUpdated();
  4805. return this;
  4806. };
  4807. /**
  4808. * Updates the current quaternion from the given rotation matrix values
  4809. * @param matrix defines the source matrix
  4810. * @returns the current updated quaternion
  4811. */
  4812. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  4813. Quaternion.FromRotationMatrixToRef(matrix, this);
  4814. return this;
  4815. };
  4816. // Statics
  4817. /**
  4818. * Creates a new quaternion from a rotation matrix
  4819. * @param matrix defines the source matrix
  4820. * @returns a new quaternion created from the given rotation matrix values
  4821. */
  4822. Quaternion.FromRotationMatrix = function (matrix) {
  4823. var result = new Quaternion();
  4824. Quaternion.FromRotationMatrixToRef(matrix, result);
  4825. return result;
  4826. };
  4827. /**
  4828. * Updates the given quaternion with the given rotation matrix values
  4829. * @param matrix defines the source matrix
  4830. * @param result defines the target quaternion
  4831. */
  4832. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  4833. var data = matrix.m;
  4834. var m11 = data[0], m12 = data[4], m13 = data[8];
  4835. var m21 = data[1], m22 = data[5], m23 = data[9];
  4836. var m31 = data[2], m32 = data[6], m33 = data[10];
  4837. var trace = m11 + m22 + m33;
  4838. var s;
  4839. if (trace > 0) {
  4840. s = 0.5 / Math.sqrt(trace + 1.0);
  4841. result.w = 0.25 / s;
  4842. result.x = (m32 - m23) * s;
  4843. result.y = (m13 - m31) * s;
  4844. result.z = (m21 - m12) * s;
  4845. }
  4846. else if (m11 > m22 && m11 > m33) {
  4847. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  4848. result.w = (m32 - m23) / s;
  4849. result.x = 0.25 * s;
  4850. result.y = (m12 + m21) / s;
  4851. result.z = (m13 + m31) / s;
  4852. }
  4853. else if (m22 > m33) {
  4854. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  4855. result.w = (m13 - m31) / s;
  4856. result.x = (m12 + m21) / s;
  4857. result.y = 0.25 * s;
  4858. result.z = (m23 + m32) / s;
  4859. }
  4860. else {
  4861. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  4862. result.w = (m21 - m12) / s;
  4863. result.x = (m13 + m31) / s;
  4864. result.y = (m23 + m32) / s;
  4865. result.z = 0.25 * s;
  4866. }
  4867. };
  4868. /**
  4869. * Returns the dot product (float) between the quaternions "left" and "right"
  4870. * @param left defines the left operand
  4871. * @param right defines the right operand
  4872. * @returns the dot product
  4873. */
  4874. Quaternion.Dot = function (left, right) {
  4875. return (left.x * right.x + left.y * right.y + left.z * right.z + left.w * right.w);
  4876. };
  4877. /**
  4878. * Checks if the two quaternions are close to each other
  4879. * @param quat0 defines the first quaternion to check
  4880. * @param quat1 defines the second quaternion to check
  4881. * @returns true if the two quaternions are close to each other
  4882. */
  4883. Quaternion.AreClose = function (quat0, quat1) {
  4884. var dot = Quaternion.Dot(quat0, quat1);
  4885. return dot >= 0;
  4886. };
  4887. /**
  4888. * Creates an empty quaternion
  4889. * @returns a new quaternion set to (0.0, 0.0, 0.0)
  4890. */
  4891. Quaternion.Zero = function () {
  4892. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  4893. };
  4894. /**
  4895. * Inverse a given quaternion
  4896. * @param q defines the source quaternion
  4897. * @returns a new quaternion as the inverted current quaternion
  4898. */
  4899. Quaternion.Inverse = function (q) {
  4900. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  4901. };
  4902. /**
  4903. * Creates an identity quaternion
  4904. * @returns the identity quaternion
  4905. */
  4906. Quaternion.Identity = function () {
  4907. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  4908. };
  4909. /**
  4910. * Gets a boolean indicating if the given quaternion is identity
  4911. * @param quaternion defines the quaternion to check
  4912. * @returns true if the quaternion is identity
  4913. */
  4914. Quaternion.IsIdentity = function (quaternion) {
  4915. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  4916. };
  4917. /**
  4918. * Creates a quaternion from a rotation around an axis
  4919. * @param axis defines the axis to use
  4920. * @param angle defines the angle to use
  4921. * @returns a new quaternion created from the given axis (Vector3) and angle in radians (float)
  4922. */
  4923. Quaternion.RotationAxis = function (axis, angle) {
  4924. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  4925. };
  4926. /**
  4927. * Creates a rotation around an axis and stores it into the given quaternion
  4928. * @param axis defines the axis to use
  4929. * @param angle defines the angle to use
  4930. * @param result defines the target quaternion
  4931. * @returns the target quaternion
  4932. */
  4933. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  4934. var sin = Math.sin(angle / 2);
  4935. axis.normalize();
  4936. result.w = Math.cos(angle / 2);
  4937. result.x = axis.x * sin;
  4938. result.y = axis.y * sin;
  4939. result.z = axis.z * sin;
  4940. return result;
  4941. };
  4942. /**
  4943. * Creates a new quaternion from data stored into an array
  4944. * @param array defines the data source
  4945. * @param offset defines the offset in the source array where the data starts
  4946. * @returns a new quaternion
  4947. */
  4948. Quaternion.FromArray = function (array, offset) {
  4949. if (!offset) {
  4950. offset = 0;
  4951. }
  4952. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4953. };
  4954. /**
  4955. * Creates a new quaternion from the given Euler float angles (y, x, z)
  4956. * @param yaw defines the rotation around Y axis
  4957. * @param pitch defines the rotation around X axis
  4958. * @param roll defines the rotation around Z axis
  4959. * @returns the new quaternion
  4960. */
  4961. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  4962. var q = new Quaternion();
  4963. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  4964. return q;
  4965. };
  4966. /**
  4967. * Creates a new rotation from the given Euler float angles (y, x, z) and stores it in the target quaternion
  4968. * @param yaw defines the rotation around Y axis
  4969. * @param pitch defines the rotation around X axis
  4970. * @param roll defines the rotation around Z axis
  4971. * @param result defines the target quaternion
  4972. */
  4973. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  4974. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  4975. var halfRoll = roll * 0.5;
  4976. var halfPitch = pitch * 0.5;
  4977. var halfYaw = yaw * 0.5;
  4978. var sinRoll = Math.sin(halfRoll);
  4979. var cosRoll = Math.cos(halfRoll);
  4980. var sinPitch = Math.sin(halfPitch);
  4981. var cosPitch = Math.cos(halfPitch);
  4982. var sinYaw = Math.sin(halfYaw);
  4983. var cosYaw = Math.cos(halfYaw);
  4984. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  4985. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  4986. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  4987. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  4988. };
  4989. /**
  4990. * Creates a new quaternion from the given Euler float angles expressed in z-x-z orientation
  4991. * @param alpha defines the rotation around first axis
  4992. * @param beta defines the rotation around second axis
  4993. * @param gamma defines the rotation around third axis
  4994. * @returns the new quaternion
  4995. */
  4996. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  4997. var result = new Quaternion();
  4998. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  4999. return result;
  5000. };
  5001. /**
  5002. * Creates a new quaternion from the given Euler float angles expressed in z-x-z orientation and stores it in the target quaternion
  5003. * @param alpha defines the rotation around first axis
  5004. * @param beta defines the rotation around second axis
  5005. * @param gamma defines the rotation around third axis
  5006. * @param result defines the target quaternion
  5007. */
  5008. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  5009. // Produces a quaternion from Euler angles in the z-x-z orientation
  5010. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  5011. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  5012. var halfBeta = beta * 0.5;
  5013. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  5014. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  5015. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  5016. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  5017. };
  5018. /**
  5019. * 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)
  5020. * @param axis1 defines the first axis
  5021. * @param axis2 defines the second axis
  5022. * @param axis3 defines the third axis
  5023. * @returns the new quaternion
  5024. */
  5025. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3) {
  5026. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  5027. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  5028. return quat;
  5029. };
  5030. /**
  5031. * 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
  5032. * @param axis1 defines the first axis
  5033. * @param axis2 defines the second axis
  5034. * @param axis3 defines the third axis
  5035. * @param ref defines the target quaternion
  5036. */
  5037. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  5038. var rotMat = MathTmp.Matrix[0];
  5039. Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  5040. Quaternion.FromRotationMatrixToRef(rotMat, ref);
  5041. };
  5042. /**
  5043. * Interpolates between two quaternions
  5044. * @param left defines first quaternion
  5045. * @param right defines second quaternion
  5046. * @param amount defines the gradient to use
  5047. * @returns the new interpolated quaternion
  5048. */
  5049. Quaternion.Slerp = function (left, right, amount) {
  5050. var result = Quaternion.Identity();
  5051. Quaternion.SlerpToRef(left, right, amount, result);
  5052. return result;
  5053. };
  5054. /**
  5055. * Interpolates between two quaternions and stores it into a target quaternion
  5056. * @param left defines first quaternion
  5057. * @param right defines second quaternion
  5058. * @param amount defines the gradient to use
  5059. * @param result defines the target quaternion
  5060. */
  5061. Quaternion.SlerpToRef = function (left, right, amount, result) {
  5062. var num2;
  5063. var num3;
  5064. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  5065. var flag = false;
  5066. if (num4 < 0) {
  5067. flag = true;
  5068. num4 = -num4;
  5069. }
  5070. if (num4 > 0.999999) {
  5071. num3 = 1 - amount;
  5072. num2 = flag ? -amount : amount;
  5073. }
  5074. else {
  5075. var num5 = Math.acos(num4);
  5076. var num6 = (1.0 / Math.sin(num5));
  5077. num3 = (Math.sin((1.0 - amount) * num5)) * num6;
  5078. num2 = flag ? ((-Math.sin(amount * num5)) * num6) : ((Math.sin(amount * num5)) * num6);
  5079. }
  5080. result.x = (num3 * left.x) + (num2 * right.x);
  5081. result.y = (num3 * left.y) + (num2 * right.y);
  5082. result.z = (num3 * left.z) + (num2 * right.z);
  5083. result.w = (num3 * left.w) + (num2 * right.w);
  5084. };
  5085. /**
  5086. * Interpolate between two quaternions using Hermite interpolation
  5087. * @param value1 defines first quaternion
  5088. * @param tangent1 defines the incoming tangent
  5089. * @param value2 defines second quaternion
  5090. * @param tangent2 defines the outgoing tangent
  5091. * @param amount defines the target quaternion
  5092. * @returns the new interpolated quaternion
  5093. */
  5094. Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  5095. var squared = amount * amount;
  5096. var cubed = amount * squared;
  5097. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  5098. var part2 = (-2.0 * cubed) + (3.0 * squared);
  5099. var part3 = (cubed - (2.0 * squared)) + amount;
  5100. var part4 = cubed - squared;
  5101. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  5102. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  5103. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  5104. var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
  5105. return new Quaternion(x, y, z, w);
  5106. };
  5107. return Quaternion;
  5108. }());
  5109. BABYLON.Quaternion = Quaternion;
  5110. /**
  5111. * Class used to store matrix data (4x4)
  5112. */
  5113. var Matrix = /** @class */ (function () {
  5114. /**
  5115. * Creates an empty matrix (filled with zeros)
  5116. */
  5117. function Matrix() {
  5118. this._isIdentity = false;
  5119. this._isIdentityDirty = true;
  5120. /**
  5121. * Gets or sets the internal data of the matrix
  5122. */
  5123. this.m = new Float32Array(16);
  5124. this._markAsUpdated();
  5125. }
  5126. /** @hidden */
  5127. Matrix.prototype._markAsUpdated = function () {
  5128. this.updateFlag = Matrix._updateFlagSeed++;
  5129. this._isIdentityDirty = true;
  5130. };
  5131. // Properties
  5132. /**
  5133. * Check if the current matrix is indentity
  5134. * @param considerAsTextureMatrix defines if the current matrix must be considered as a texture matrix (3x2)
  5135. * @returns true is the matrix is the identity matrix
  5136. */
  5137. Matrix.prototype.isIdentity = function (considerAsTextureMatrix) {
  5138. if (considerAsTextureMatrix === void 0) { considerAsTextureMatrix = false; }
  5139. if (this._isIdentityDirty) {
  5140. this._isIdentityDirty = false;
  5141. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[15] !== 1.0) {
  5142. this._isIdentity = false;
  5143. }
  5144. else if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  5145. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  5146. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  5147. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0) {
  5148. this._isIdentity = false;
  5149. }
  5150. else {
  5151. this._isIdentity = true;
  5152. }
  5153. if (!considerAsTextureMatrix && this.m[10] !== 1.0) {
  5154. this._isIdentity = false;
  5155. }
  5156. }
  5157. return this._isIdentity;
  5158. };
  5159. /**
  5160. * Gets the determinant of the matrix
  5161. * @returns the matrix determinant
  5162. */
  5163. Matrix.prototype.determinant = function () {
  5164. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  5165. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  5166. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  5167. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  5168. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  5169. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  5170. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  5171. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  5172. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  5173. };
  5174. // Methods
  5175. /**
  5176. * Returns the matrix as a Float32Array
  5177. * @returns the matrix underlying array
  5178. */
  5179. Matrix.prototype.toArray = function () {
  5180. return this.m;
  5181. };
  5182. /**
  5183. * Returns the matrix as a Float32Array
  5184. * @returns the matrix underlying array.
  5185. */
  5186. Matrix.prototype.asArray = function () {
  5187. return this.toArray();
  5188. };
  5189. /**
  5190. * Inverts the current matrix in place
  5191. * @returns the current inverted matrix
  5192. */
  5193. Matrix.prototype.invert = function () {
  5194. this.invertToRef(this);
  5195. return this;
  5196. };
  5197. /**
  5198. * Sets all the matrix elements to zero
  5199. * @returns the current matrix
  5200. */
  5201. Matrix.prototype.reset = function () {
  5202. for (var index = 0; index < 16; index++) {
  5203. this.m[index] = 0.0;
  5204. }
  5205. this._markAsUpdated();
  5206. return this;
  5207. };
  5208. /**
  5209. * Adds the current matrix with a second one
  5210. * @param other defines the matrix to add
  5211. * @returns a new matrix as the addition of the current matrix and the given one
  5212. */
  5213. Matrix.prototype.add = function (other) {
  5214. var result = new Matrix();
  5215. this.addToRef(other, result);
  5216. return result;
  5217. };
  5218. /**
  5219. * Sets the given matrix "result" to the addition of the current matrix and the given one
  5220. * @param other defines the matrix to add
  5221. * @param result defines the target matrix
  5222. * @returns the current matrix
  5223. */
  5224. Matrix.prototype.addToRef = function (other, result) {
  5225. for (var index = 0; index < 16; index++) {
  5226. result.m[index] = this.m[index] + other.m[index];
  5227. }
  5228. result._markAsUpdated();
  5229. return this;
  5230. };
  5231. /**
  5232. * Adds in place the given matrix to the current matrix
  5233. * @param other defines the second operand
  5234. * @returns the current updated matrix
  5235. */
  5236. Matrix.prototype.addToSelf = function (other) {
  5237. for (var index = 0; index < 16; index++) {
  5238. this.m[index] += other.m[index];
  5239. }
  5240. this._markAsUpdated();
  5241. return this;
  5242. };
  5243. /**
  5244. * Sets the given matrix to the current inverted Matrix
  5245. * @param other defines the target matrix
  5246. * @returns the unmodified current matrix
  5247. */
  5248. Matrix.prototype.invertToRef = function (other) {
  5249. var l1 = this.m[0];
  5250. var l2 = this.m[1];
  5251. var l3 = this.m[2];
  5252. var l4 = this.m[3];
  5253. var l5 = this.m[4];
  5254. var l6 = this.m[5];
  5255. var l7 = this.m[6];
  5256. var l8 = this.m[7];
  5257. var l9 = this.m[8];
  5258. var l10 = this.m[9];
  5259. var l11 = this.m[10];
  5260. var l12 = this.m[11];
  5261. var l13 = this.m[12];
  5262. var l14 = this.m[13];
  5263. var l15 = this.m[14];
  5264. var l16 = this.m[15];
  5265. var l17 = (l11 * l16) - (l12 * l15);
  5266. var l18 = (l10 * l16) - (l12 * l14);
  5267. var l19 = (l10 * l15) - (l11 * l14);
  5268. var l20 = (l9 * l16) - (l12 * l13);
  5269. var l21 = (l9 * l15) - (l11 * l13);
  5270. var l22 = (l9 * l14) - (l10 * l13);
  5271. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  5272. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  5273. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  5274. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  5275. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  5276. var l28 = (l7 * l16) - (l8 * l15);
  5277. var l29 = (l6 * l16) - (l8 * l14);
  5278. var l30 = (l6 * l15) - (l7 * l14);
  5279. var l31 = (l5 * l16) - (l8 * l13);
  5280. var l32 = (l5 * l15) - (l7 * l13);
  5281. var l33 = (l5 * l14) - (l6 * l13);
  5282. var l34 = (l7 * l12) - (l8 * l11);
  5283. var l35 = (l6 * l12) - (l8 * l10);
  5284. var l36 = (l6 * l11) - (l7 * l10);
  5285. var l37 = (l5 * l12) - (l8 * l9);
  5286. var l38 = (l5 * l11) - (l7 * l9);
  5287. var l39 = (l5 * l10) - (l6 * l9);
  5288. other.m[0] = l23 * l27;
  5289. other.m[4] = l24 * l27;
  5290. other.m[8] = l25 * l27;
  5291. other.m[12] = l26 * l27;
  5292. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  5293. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  5294. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  5295. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  5296. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  5297. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  5298. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  5299. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  5300. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  5301. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  5302. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  5303. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  5304. other._markAsUpdated();
  5305. return this;
  5306. };
  5307. /**
  5308. * Inserts the translation vector (using 3 floats) in the current matrix
  5309. * @param x defines the 1st component of the translation
  5310. * @param y defines the 2nd component of the translation
  5311. * @param z defines the 3rd component of the translation
  5312. * @returns the current updated matrix
  5313. */
  5314. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  5315. this.m[12] = x;
  5316. this.m[13] = y;
  5317. this.m[14] = z;
  5318. this._markAsUpdated();
  5319. return this;
  5320. };
  5321. /**
  5322. * Inserts the translation vector in the current matrix
  5323. * @param vector3 defines the translation to insert
  5324. * @returns the current updated matrix
  5325. */
  5326. Matrix.prototype.setTranslation = function (vector3) {
  5327. this.m[12] = vector3.x;
  5328. this.m[13] = vector3.y;
  5329. this.m[14] = vector3.z;
  5330. this._markAsUpdated();
  5331. return this;
  5332. };
  5333. /**
  5334. * Gets the translation value of the current matrix
  5335. * @returns a new Vector3 as the extracted translation from the matrix
  5336. */
  5337. Matrix.prototype.getTranslation = function () {
  5338. return new Vector3(this.m[12], this.m[13], this.m[14]);
  5339. };
  5340. /**
  5341. * Fill a Vector3 with the extracted translation from the matrix
  5342. * @param result defines the Vector3 where to store the translation
  5343. * @returns the current matrix
  5344. */
  5345. Matrix.prototype.getTranslationToRef = function (result) {
  5346. result.x = this.m[12];
  5347. result.y = this.m[13];
  5348. result.z = this.m[14];
  5349. return this;
  5350. };
  5351. /**
  5352. * Remove rotation and scaling part from the matrix
  5353. * @returns the updated matrix
  5354. */
  5355. Matrix.prototype.removeRotationAndScaling = function () {
  5356. this.setRowFromFloats(0, 1, 0, 0, 0);
  5357. this.setRowFromFloats(1, 0, 1, 0, 0);
  5358. this.setRowFromFloats(2, 0, 0, 1, 0);
  5359. return this;
  5360. };
  5361. /**
  5362. * Multiply two matrices
  5363. * @param other defines the second operand
  5364. * @returns a new matrix set with the multiplication result of the current Matrix and the given one
  5365. */
  5366. Matrix.prototype.multiply = function (other) {
  5367. var result = new Matrix();
  5368. this.multiplyToRef(other, result);
  5369. return result;
  5370. };
  5371. /**
  5372. * Copy the current matrix from the given one
  5373. * @param other defines the source matrix
  5374. * @returns the current updated matrix
  5375. */
  5376. Matrix.prototype.copyFrom = function (other) {
  5377. for (var index = 0; index < 16; index++) {
  5378. this.m[index] = other.m[index];
  5379. }
  5380. this._markAsUpdated();
  5381. return this;
  5382. };
  5383. /**
  5384. * Populates the given array from the starting index with the current matrix values
  5385. * @param array defines the target array
  5386. * @param offset defines the offset in the target array where to start storing values
  5387. * @returns the current matrix
  5388. */
  5389. Matrix.prototype.copyToArray = function (array, offset) {
  5390. if (offset === void 0) { offset = 0; }
  5391. for (var index = 0; index < 16; index++) {
  5392. array[offset + index] = this.m[index];
  5393. }
  5394. return this;
  5395. };
  5396. /**
  5397. * Sets the given matrix "result" with the multiplication result of the current Matrix and the given one
  5398. * @param other defines the second operand
  5399. * @param result defines the matrix where to store the multiplication
  5400. * @returns the current matrix
  5401. */
  5402. Matrix.prototype.multiplyToRef = function (other, result) {
  5403. this.multiplyToArray(other, result.m, 0);
  5404. result._markAsUpdated();
  5405. return this;
  5406. };
  5407. /**
  5408. * Sets the Float32Array "result" from the given index "offset" with the multiplication of the current matrix and the given one
  5409. * @param other defines the second operand
  5410. * @param result defines the array where to store the multiplication
  5411. * @param offset defines the offset in the target array where to start storing values
  5412. * @returns the current matrix
  5413. */
  5414. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  5415. var tm0 = this.m[0];
  5416. var tm1 = this.m[1];
  5417. var tm2 = this.m[2];
  5418. var tm3 = this.m[3];
  5419. var tm4 = this.m[4];
  5420. var tm5 = this.m[5];
  5421. var tm6 = this.m[6];
  5422. var tm7 = this.m[7];
  5423. var tm8 = this.m[8];
  5424. var tm9 = this.m[9];
  5425. var tm10 = this.m[10];
  5426. var tm11 = this.m[11];
  5427. var tm12 = this.m[12];
  5428. var tm13 = this.m[13];
  5429. var tm14 = this.m[14];
  5430. var tm15 = this.m[15];
  5431. var om0 = other.m[0];
  5432. var om1 = other.m[1];
  5433. var om2 = other.m[2];
  5434. var om3 = other.m[3];
  5435. var om4 = other.m[4];
  5436. var om5 = other.m[5];
  5437. var om6 = other.m[6];
  5438. var om7 = other.m[7];
  5439. var om8 = other.m[8];
  5440. var om9 = other.m[9];
  5441. var om10 = other.m[10];
  5442. var om11 = other.m[11];
  5443. var om12 = other.m[12];
  5444. var om13 = other.m[13];
  5445. var om14 = other.m[14];
  5446. var om15 = other.m[15];
  5447. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  5448. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  5449. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  5450. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  5451. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  5452. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  5453. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  5454. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  5455. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  5456. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  5457. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  5458. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  5459. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  5460. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  5461. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  5462. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  5463. return this;
  5464. };
  5465. /**
  5466. * Check equality between this matrix and a second one
  5467. * @param value defines the second matrix to compare
  5468. * @returns true is the current matrix and the given one values are strictly equal
  5469. */
  5470. Matrix.prototype.equals = function (value) {
  5471. return value &&
  5472. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  5473. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  5474. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  5475. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  5476. };
  5477. /**
  5478. * Clone the current matrix
  5479. * @returns a new matrix from the current matrix
  5480. */
  5481. Matrix.prototype.clone = function () {
  5482. 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]);
  5483. };
  5484. /**
  5485. * Returns the name of the current matrix class
  5486. * @returns the string "Matrix"
  5487. */
  5488. Matrix.prototype.getClassName = function () {
  5489. return "Matrix";
  5490. };
  5491. /**
  5492. * Gets the hash code of the current matrix
  5493. * @returns the hash code
  5494. */
  5495. Matrix.prototype.getHashCode = function () {
  5496. var hash = this.m[0] || 0;
  5497. for (var i = 1; i < 16; i++) {
  5498. hash = (hash * 397) ^ (this.m[i] || 0);
  5499. }
  5500. return hash;
  5501. };
  5502. /**
  5503. * Decomposes the current Matrix into a translation, rotation and scaling components
  5504. * @param scale defines the scale vector3 given as a reference to update
  5505. * @param rotation defines the rotation quaternion given as a reference to update
  5506. * @param translation defines the translation vector3 given as a reference to update
  5507. * @returns true if operation was successful
  5508. */
  5509. Matrix.prototype.decompose = function (scale, rotation, translation) {
  5510. if (translation) {
  5511. translation.x = this.m[12];
  5512. translation.y = this.m[13];
  5513. translation.z = this.m[14];
  5514. }
  5515. scale = scale || MathTmp.Vector3[0];
  5516. scale.x = Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  5517. scale.y = Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  5518. scale.z = Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  5519. if (this.determinant() <= 0) {
  5520. scale.y *= -1;
  5521. }
  5522. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  5523. if (rotation) {
  5524. rotation.x = 0;
  5525. rotation.y = 0;
  5526. rotation.z = 0;
  5527. rotation.w = 1;
  5528. }
  5529. return false;
  5530. }
  5531. if (rotation) {
  5532. 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]);
  5533. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  5534. }
  5535. return true;
  5536. };
  5537. /**
  5538. * Gets specific row of the matrix
  5539. * @param index defines the number of the row to get
  5540. * @returns the index-th row of the current matrix as a new Vector4
  5541. */
  5542. Matrix.prototype.getRow = function (index) {
  5543. if (index < 0 || index > 3) {
  5544. return null;
  5545. }
  5546. var i = index * 4;
  5547. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  5548. };
  5549. /**
  5550. * Sets the index-th row of the current matrix to the vector4 values
  5551. * @param index defines the number of the row to set
  5552. * @param row defines the target vector4
  5553. * @returns the updated current matrix
  5554. */
  5555. Matrix.prototype.setRow = function (index, row) {
  5556. if (index < 0 || index > 3) {
  5557. return this;
  5558. }
  5559. var i = index * 4;
  5560. this.m[i + 0] = row.x;
  5561. this.m[i + 1] = row.y;
  5562. this.m[i + 2] = row.z;
  5563. this.m[i + 3] = row.w;
  5564. this._markAsUpdated();
  5565. return this;
  5566. };
  5567. /**
  5568. * Compute the transpose of the matrix
  5569. * @returns the new transposed matrix
  5570. */
  5571. Matrix.prototype.transpose = function () {
  5572. return Matrix.Transpose(this);
  5573. };
  5574. /**
  5575. * Compute the transpose of the matrix and store it in a given matrix
  5576. * @param result defines the target matrix
  5577. * @returns the current matrix
  5578. */
  5579. Matrix.prototype.transposeToRef = function (result) {
  5580. Matrix.TransposeToRef(this, result);
  5581. return this;
  5582. };
  5583. /**
  5584. * Sets the index-th row of the current matrix with the given 4 x float values
  5585. * @param index defines the row index
  5586. * @param x defines the x component to set
  5587. * @param y defines the y component to set
  5588. * @param z defines the z component to set
  5589. * @param w defines the w component to set
  5590. * @returns the updated current matrix
  5591. */
  5592. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  5593. if (index < 0 || index > 3) {
  5594. return this;
  5595. }
  5596. var i = index * 4;
  5597. this.m[i + 0] = x;
  5598. this.m[i + 1] = y;
  5599. this.m[i + 2] = z;
  5600. this.m[i + 3] = w;
  5601. this._markAsUpdated();
  5602. return this;
  5603. };
  5604. /**
  5605. * Compute a new matrix set with the current matrix values multiplied by scale (float)
  5606. * @param scale defines the scale factor
  5607. * @returns a new matrix
  5608. */
  5609. Matrix.prototype.scale = function (scale) {
  5610. var result = new Matrix();
  5611. this.scaleToRef(scale, result);
  5612. return result;
  5613. };
  5614. /**
  5615. * Scale the current matrix values by a factor to a given result matrix
  5616. * @param scale defines the scale factor
  5617. * @param result defines the matrix to store the result
  5618. * @returns the current matrix
  5619. */
  5620. Matrix.prototype.scaleToRef = function (scale, result) {
  5621. for (var index = 0; index < 16; index++) {
  5622. result.m[index] = this.m[index] * scale;
  5623. }
  5624. result._markAsUpdated();
  5625. return this;
  5626. };
  5627. /**
  5628. * Scale the current matrix values by a factor and add the result to a given matrix
  5629. * @param scale defines the scale factor
  5630. * @param result defines the Matrix to store the result
  5631. * @returns the current matrix
  5632. */
  5633. Matrix.prototype.scaleAndAddToRef = function (scale, result) {
  5634. for (var index = 0; index < 16; index++) {
  5635. result.m[index] += this.m[index] * scale;
  5636. }
  5637. result._markAsUpdated();
  5638. return this;
  5639. };
  5640. /**
  5641. * Writes to the given matrix a normal matrix, computed from this one (using values from identity matrix for fourth row and column).
  5642. * @param ref matrix to store the result
  5643. */
  5644. Matrix.prototype.toNormalMatrix = function (ref) {
  5645. this.invertToRef(ref);
  5646. ref.transpose();
  5647. var m = ref.m;
  5648. 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);
  5649. };
  5650. /**
  5651. * Gets only rotation part of the current matrix
  5652. * @returns a new matrix sets to the extracted rotation matrix from the current one
  5653. */
  5654. Matrix.prototype.getRotationMatrix = function () {
  5655. var result = Matrix.Identity();
  5656. this.getRotationMatrixToRef(result);
  5657. return result;
  5658. };
  5659. /**
  5660. * Extracts the rotation matrix from the current one and sets it as the given "result"
  5661. * @param result defines the target matrix to store data to
  5662. * @returns the current matrix
  5663. */
  5664. Matrix.prototype.getRotationMatrixToRef = function (result) {
  5665. var m = this.m;
  5666. var sx = Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  5667. var sy = Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  5668. var sz = Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  5669. if (this.determinant() <= 0) {
  5670. sy *= -1;
  5671. }
  5672. if (sx === 0 || sy === 0 || sz === 0) {
  5673. Matrix.IdentityToRef(result);
  5674. }
  5675. else {
  5676. 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);
  5677. }
  5678. return this;
  5679. };
  5680. // Statics
  5681. /**
  5682. * Creates a matrix from an array
  5683. * @param array defines the source array
  5684. * @param offset defines an offset in the source array
  5685. * @returns a new Matrix set from the starting index of the given array
  5686. */
  5687. Matrix.FromArray = function (array, offset) {
  5688. var result = new Matrix();
  5689. if (!offset) {
  5690. offset = 0;
  5691. }
  5692. Matrix.FromArrayToRef(array, offset, result);
  5693. return result;
  5694. };
  5695. /**
  5696. * Copy the content of an array into a given matrix
  5697. * @param array defines the source array
  5698. * @param offset defines an offset in the source array
  5699. * @param result defines the target matrix
  5700. */
  5701. Matrix.FromArrayToRef = function (array, offset, result) {
  5702. for (var index = 0; index < 16; index++) {
  5703. result.m[index] = array[index + offset];
  5704. }
  5705. result._markAsUpdated();
  5706. };
  5707. /**
  5708. * Stores an array into a matrix after having multiplied each component by a given factor
  5709. * @param array defines the source array
  5710. * @param offset defines the offset in the source array
  5711. * @param scale defines the scaling factor
  5712. * @param result defines the target matrix
  5713. */
  5714. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  5715. for (var index = 0; index < 16; index++) {
  5716. result.m[index] = array[index + offset] * scale;
  5717. }
  5718. result._markAsUpdated();
  5719. };
  5720. /**
  5721. * Stores a list of values (16) inside a given matrix
  5722. * @param initialM11 defines 1st value of 1st row
  5723. * @param initialM12 defines 2nd value of 1st row
  5724. * @param initialM13 defines 3rd value of 1st row
  5725. * @param initialM14 defines 4th value of 1st row
  5726. * @param initialM21 defines 1st value of 2nd row
  5727. * @param initialM22 defines 2nd value of 2nd row
  5728. * @param initialM23 defines 3rd value of 2nd row
  5729. * @param initialM24 defines 4th value of 2nd row
  5730. * @param initialM31 defines 1st value of 3rd row
  5731. * @param initialM32 defines 2nd value of 3rd row
  5732. * @param initialM33 defines 3rd value of 3rd row
  5733. * @param initialM34 defines 4th value of 3rd row
  5734. * @param initialM41 defines 1st value of 4th row
  5735. * @param initialM42 defines 2nd value of 4th row
  5736. * @param initialM43 defines 3rd value of 4th row
  5737. * @param initialM44 defines 4th value of 4th row
  5738. * @param result defines the target matrix
  5739. */
  5740. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  5741. result.m[0] = initialM11;
  5742. result.m[1] = initialM12;
  5743. result.m[2] = initialM13;
  5744. result.m[3] = initialM14;
  5745. result.m[4] = initialM21;
  5746. result.m[5] = initialM22;
  5747. result.m[6] = initialM23;
  5748. result.m[7] = initialM24;
  5749. result.m[8] = initialM31;
  5750. result.m[9] = initialM32;
  5751. result.m[10] = initialM33;
  5752. result.m[11] = initialM34;
  5753. result.m[12] = initialM41;
  5754. result.m[13] = initialM42;
  5755. result.m[14] = initialM43;
  5756. result.m[15] = initialM44;
  5757. result._markAsUpdated();
  5758. };
  5759. Object.defineProperty(Matrix, "IdentityReadOnly", {
  5760. /**
  5761. * Gets an identity matrix that must not be updated
  5762. */
  5763. get: function () {
  5764. return Matrix._identityReadOnly;
  5765. },
  5766. enumerable: true,
  5767. configurable: true
  5768. });
  5769. /**
  5770. * Creates new matrix from a list of values (16)
  5771. * @param initialM11 defines 1st value of 1st row
  5772. * @param initialM12 defines 2nd value of 1st row
  5773. * @param initialM13 defines 3rd value of 1st row
  5774. * @param initialM14 defines 4th value of 1st row
  5775. * @param initialM21 defines 1st value of 2nd row
  5776. * @param initialM22 defines 2nd value of 2nd row
  5777. * @param initialM23 defines 3rd value of 2nd row
  5778. * @param initialM24 defines 4th value of 2nd row
  5779. * @param initialM31 defines 1st value of 3rd row
  5780. * @param initialM32 defines 2nd value of 3rd row
  5781. * @param initialM33 defines 3rd value of 3rd row
  5782. * @param initialM34 defines 4th value of 3rd row
  5783. * @param initialM41 defines 1st value of 4th row
  5784. * @param initialM42 defines 2nd value of 4th row
  5785. * @param initialM43 defines 3rd value of 4th row
  5786. * @param initialM44 defines 4th value of 4th row
  5787. * @returns the new matrix
  5788. */
  5789. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  5790. var result = new Matrix();
  5791. result.m[0] = initialM11;
  5792. result.m[1] = initialM12;
  5793. result.m[2] = initialM13;
  5794. result.m[3] = initialM14;
  5795. result.m[4] = initialM21;
  5796. result.m[5] = initialM22;
  5797. result.m[6] = initialM23;
  5798. result.m[7] = initialM24;
  5799. result.m[8] = initialM31;
  5800. result.m[9] = initialM32;
  5801. result.m[10] = initialM33;
  5802. result.m[11] = initialM34;
  5803. result.m[12] = initialM41;
  5804. result.m[13] = initialM42;
  5805. result.m[14] = initialM43;
  5806. result.m[15] = initialM44;
  5807. return result;
  5808. };
  5809. /**
  5810. * Creates a new matrix composed by merging scale (vector3), rotation (quaternion) and translation (vector3)
  5811. * @param scale defines the scale vector3
  5812. * @param rotation defines the rotation quaternion
  5813. * @param translation defines the translation vector3
  5814. * @returns a new matrix
  5815. */
  5816. Matrix.Compose = function (scale, rotation, translation) {
  5817. var result = Matrix.Identity();
  5818. Matrix.ComposeToRef(scale, rotation, translation, result);
  5819. return result;
  5820. };
  5821. /**
  5822. * Sets a matrix to a value composed by merging scale (vector3), rotation (quaternion) and translation (vector3)
  5823. * @param scale defines the scale vector3
  5824. * @param rotation defines the rotation quaternion
  5825. * @param translation defines the translation vector3
  5826. * @param result defines the target matrix
  5827. */
  5828. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  5829. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  5830. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  5831. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  5832. result.setTranslation(translation);
  5833. };
  5834. /**
  5835. * Creates a new identity matrix
  5836. * @returns a new identity matrix
  5837. */
  5838. Matrix.Identity = function () {
  5839. 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);
  5840. };
  5841. /**
  5842. * Creates a new identity matrix and stores the result in a given matrix
  5843. * @param result defines the target matrix
  5844. */
  5845. Matrix.IdentityToRef = function (result) {
  5846. 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);
  5847. };
  5848. /**
  5849. * Creates a new zero matrix
  5850. * @returns a new zero matrix
  5851. */
  5852. Matrix.Zero = function () {
  5853. 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);
  5854. };
  5855. /**
  5856. * Creates a new rotation matrix for "angle" radians around the X axis
  5857. * @param angle defines the angle (in radians) to use
  5858. * @return the new matrix
  5859. */
  5860. Matrix.RotationX = function (angle) {
  5861. var result = new Matrix();
  5862. Matrix.RotationXToRef(angle, result);
  5863. return result;
  5864. };
  5865. /**
  5866. * Creates a new matrix as the invert of a given matrix
  5867. * @param source defines the source matrix
  5868. * @returns the new matrix
  5869. */
  5870. Matrix.Invert = function (source) {
  5871. var result = new Matrix();
  5872. source.invertToRef(result);
  5873. return result;
  5874. };
  5875. /**
  5876. * Creates a new rotation matrix for "angle" radians around the X axis and stores it in a given matrix
  5877. * @param angle defines the angle (in radians) to use
  5878. * @param result defines the target matrix
  5879. */
  5880. Matrix.RotationXToRef = function (angle, result) {
  5881. var s = Math.sin(angle);
  5882. var c = Math.cos(angle);
  5883. result.m[0] = 1.0;
  5884. result.m[15] = 1.0;
  5885. result.m[5] = c;
  5886. result.m[10] = c;
  5887. result.m[9] = -s;
  5888. result.m[6] = s;
  5889. result.m[1] = 0.0;
  5890. result.m[2] = 0.0;
  5891. result.m[3] = 0.0;
  5892. result.m[4] = 0.0;
  5893. result.m[7] = 0.0;
  5894. result.m[8] = 0.0;
  5895. result.m[11] = 0.0;
  5896. result.m[12] = 0.0;
  5897. result.m[13] = 0.0;
  5898. result.m[14] = 0.0;
  5899. result._markAsUpdated();
  5900. };
  5901. /**
  5902. * Creates a new rotation matrix for "angle" radians around the Y axis
  5903. * @param angle defines the angle (in radians) to use
  5904. * @return the new matrix
  5905. */
  5906. Matrix.RotationY = function (angle) {
  5907. var result = new Matrix();
  5908. Matrix.RotationYToRef(angle, result);
  5909. return result;
  5910. };
  5911. /**
  5912. * Creates a new rotation matrix for "angle" radians around the Y axis and stores it in a given matrix
  5913. * @param angle defines the angle (in radians) to use
  5914. * @param result defines the target matrix
  5915. */
  5916. Matrix.RotationYToRef = function (angle, result) {
  5917. var s = Math.sin(angle);
  5918. var c = Math.cos(angle);
  5919. result.m[5] = 1.0;
  5920. result.m[15] = 1.0;
  5921. result.m[0] = c;
  5922. result.m[2] = -s;
  5923. result.m[8] = s;
  5924. result.m[10] = c;
  5925. result.m[1] = 0.0;
  5926. result.m[3] = 0.0;
  5927. result.m[4] = 0.0;
  5928. result.m[6] = 0.0;
  5929. result.m[7] = 0.0;
  5930. result.m[9] = 0.0;
  5931. result.m[11] = 0.0;
  5932. result.m[12] = 0.0;
  5933. result.m[13] = 0.0;
  5934. result.m[14] = 0.0;
  5935. result._markAsUpdated();
  5936. };
  5937. /**
  5938. * Creates a new rotation matrix for "angle" radians around the Z axis
  5939. * @param angle defines the angle (in radians) to use
  5940. * @return the new matrix
  5941. */
  5942. Matrix.RotationZ = function (angle) {
  5943. var result = new Matrix();
  5944. Matrix.RotationZToRef(angle, result);
  5945. return result;
  5946. };
  5947. /**
  5948. * Creates a new rotation matrix for "angle" radians around the Z axis and stores it in a given matrix
  5949. * @param angle defines the angle (in radians) to use
  5950. * @param result defines the target matrix
  5951. */
  5952. Matrix.RotationZToRef = function (angle, result) {
  5953. var s = Math.sin(angle);
  5954. var c = Math.cos(angle);
  5955. result.m[10] = 1.0;
  5956. result.m[15] = 1.0;
  5957. result.m[0] = c;
  5958. result.m[1] = s;
  5959. result.m[4] = -s;
  5960. result.m[5] = c;
  5961. result.m[2] = 0.0;
  5962. result.m[3] = 0.0;
  5963. result.m[6] = 0.0;
  5964. result.m[7] = 0.0;
  5965. result.m[8] = 0.0;
  5966. result.m[9] = 0.0;
  5967. result.m[11] = 0.0;
  5968. result.m[12] = 0.0;
  5969. result.m[13] = 0.0;
  5970. result.m[14] = 0.0;
  5971. result._markAsUpdated();
  5972. };
  5973. /**
  5974. * Creates a new rotation matrix for "angle" radians around the given axis
  5975. * @param axis defines the axis to use
  5976. * @param angle defines the angle (in radians) to use
  5977. * @return the new matrix
  5978. */
  5979. Matrix.RotationAxis = function (axis, angle) {
  5980. var result = Matrix.Zero();
  5981. Matrix.RotationAxisToRef(axis, angle, result);
  5982. return result;
  5983. };
  5984. /**
  5985. * Creates a new rotation matrix for "angle" radians around the given axis and stores it in a given matrix
  5986. * @param axis defines the axis to use
  5987. * @param angle defines the angle (in radians) to use
  5988. * @param result defines the target matrix
  5989. */
  5990. Matrix.RotationAxisToRef = function (axis, angle, result) {
  5991. var s = Math.sin(-angle);
  5992. var c = Math.cos(-angle);
  5993. var c1 = 1 - c;
  5994. axis.normalize();
  5995. result.m[0] = (axis.x * axis.x) * c1 + c;
  5996. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  5997. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  5998. result.m[3] = 0.0;
  5999. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  6000. result.m[5] = (axis.y * axis.y) * c1 + c;
  6001. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  6002. result.m[7] = 0.0;
  6003. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  6004. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  6005. result.m[10] = (axis.z * axis.z) * c1 + c;
  6006. result.m[11] = 0.0;
  6007. result.m[15] = 1.0;
  6008. result._markAsUpdated();
  6009. };
  6010. /**
  6011. * Creates a rotation matrix
  6012. * @param yaw defines the yaw angle in radians (Y axis)
  6013. * @param pitch defines the pitch angle in radians (X axis)
  6014. * @param roll defines the roll angle in radians (X axis)
  6015. * @returns the new rotation matrix
  6016. */
  6017. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  6018. var result = new Matrix();
  6019. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  6020. return result;
  6021. };
  6022. /**
  6023. * Creates a rotation matrix and stores it in a given matrix
  6024. * @param yaw defines the yaw angle in radians (Y axis)
  6025. * @param pitch defines the pitch angle in radians (X axis)
  6026. * @param roll defines the roll angle in radians (X axis)
  6027. * @param result defines the target matrix
  6028. */
  6029. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  6030. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  6031. this._tempQuaternion.toRotationMatrix(result);
  6032. };
  6033. /**
  6034. * Creates a scaling matrix
  6035. * @param x defines the scale factor on X axis
  6036. * @param y defines the scale factor on Y axis
  6037. * @param z defines the scale factor on Z axis
  6038. * @returns the new matrix
  6039. */
  6040. Matrix.Scaling = function (x, y, z) {
  6041. var result = Matrix.Zero();
  6042. Matrix.ScalingToRef(x, y, z, result);
  6043. return result;
  6044. };
  6045. /**
  6046. * Creates a scaling matrix and stores it in a given matrix
  6047. * @param x defines the scale factor on X axis
  6048. * @param y defines the scale factor on Y axis
  6049. * @param z defines the scale factor on Z axis
  6050. * @param result defines the target matrix
  6051. */
  6052. Matrix.ScalingToRef = function (x, y, z, result) {
  6053. result.m[0] = x;
  6054. result.m[1] = 0.0;
  6055. result.m[2] = 0.0;
  6056. result.m[3] = 0.0;
  6057. result.m[4] = 0.0;
  6058. result.m[5] = y;
  6059. result.m[6] = 0.0;
  6060. result.m[7] = 0.0;
  6061. result.m[8] = 0.0;
  6062. result.m[9] = 0.0;
  6063. result.m[10] = z;
  6064. result.m[11] = 0.0;
  6065. result.m[12] = 0.0;
  6066. result.m[13] = 0.0;
  6067. result.m[14] = 0.0;
  6068. result.m[15] = 1.0;
  6069. result._markAsUpdated();
  6070. };
  6071. /**
  6072. * Creates a translation matrix
  6073. * @param x defines the translation on X axis
  6074. * @param y defines the translation on Y axis
  6075. * @param z defines the translationon Z axis
  6076. * @returns the new matrix
  6077. */
  6078. Matrix.Translation = function (x, y, z) {
  6079. var result = Matrix.Identity();
  6080. Matrix.TranslationToRef(x, y, z, result);
  6081. return result;
  6082. };
  6083. /**
  6084. * Creates a translation matrix and stores it in a given matrix
  6085. * @param x defines the translation on X axis
  6086. * @param y defines the translation on Y axis
  6087. * @param z defines the translationon Z axis
  6088. * @param result defines the target matrix
  6089. */
  6090. Matrix.TranslationToRef = function (x, y, z, result) {
  6091. 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);
  6092. };
  6093. /**
  6094. * Returns a new Matrix whose values are the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  6095. * @param startValue defines the start value
  6096. * @param endValue defines the end value
  6097. * @param gradient defines the gradient factor
  6098. * @returns the new matrix
  6099. */
  6100. Matrix.Lerp = function (startValue, endValue, gradient) {
  6101. var result = Matrix.Zero();
  6102. Matrix.LerpToRef(startValue, endValue, gradient, result);
  6103. return result;
  6104. };
  6105. /**
  6106. * Set the given matrix "result" as the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  6107. * @param startValue defines the start value
  6108. * @param endValue defines the end value
  6109. * @param gradient defines the gradient factor
  6110. * @param result defines the Matrix object where to store data
  6111. */
  6112. Matrix.LerpToRef = function (startValue, endValue, gradient, result) {
  6113. for (var index = 0; index < 16; index++) {
  6114. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  6115. }
  6116. result._markAsUpdated();
  6117. };
  6118. /**
  6119. * Builds a new matrix whose values are computed by:
  6120. * * decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices
  6121. * * interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end
  6122. * * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices
  6123. * @param startValue defines the first matrix
  6124. * @param endValue defines the second matrix
  6125. * @param gradient defines the gradient between the two matrices
  6126. * @returns the new matrix
  6127. */
  6128. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  6129. var result = Matrix.Zero();
  6130. Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
  6131. return result;
  6132. };
  6133. /**
  6134. * Update a matrix to values which are computed by:
  6135. * * decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices
  6136. * * interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end
  6137. * * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices
  6138. * @param startValue defines the first matrix
  6139. * @param endValue defines the second matrix
  6140. * @param gradient defines the gradient between the two matrices
  6141. * @param result defines the target matrix
  6142. */
  6143. Matrix.DecomposeLerpToRef = function (startValue, endValue, gradient, result) {
  6144. var startScale = MathTmp.Vector3[0];
  6145. var startRotation = MathTmp.Quaternion[0];
  6146. var startTranslation = MathTmp.Vector3[1];
  6147. startValue.decompose(startScale, startRotation, startTranslation);
  6148. var endScale = MathTmp.Vector3[2];
  6149. var endRotation = MathTmp.Quaternion[1];
  6150. var endTranslation = MathTmp.Vector3[3];
  6151. endValue.decompose(endScale, endRotation, endTranslation);
  6152. var resultScale = MathTmp.Vector3[4];
  6153. Vector3.LerpToRef(startScale, endScale, gradient, resultScale);
  6154. var resultRotation = MathTmp.Quaternion[2];
  6155. Quaternion.SlerpToRef(startRotation, endRotation, gradient, resultRotation);
  6156. var resultTranslation = MathTmp.Vector3[5];
  6157. Vector3.LerpToRef(startTranslation, endTranslation, gradient, resultTranslation);
  6158. Matrix.ComposeToRef(resultScale, resultRotation, resultTranslation, result);
  6159. };
  6160. /**
  6161. * 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"
  6162. * This function works in left handed mode
  6163. * @param eye defines the final position of the entity
  6164. * @param target defines where the entity should look at
  6165. * @param up defines the up vector for the entity
  6166. * @returns the new matrix
  6167. */
  6168. Matrix.LookAtLH = function (eye, target, up) {
  6169. var result = Matrix.Zero();
  6170. Matrix.LookAtLHToRef(eye, target, up, result);
  6171. return result;
  6172. };
  6173. /**
  6174. * 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".
  6175. * This function works in left handed mode
  6176. * @param eye defines the final position of the entity
  6177. * @param target defines where the entity should look at
  6178. * @param up defines the up vector for the entity
  6179. * @param result defines the target matrix
  6180. */
  6181. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  6182. // Z axis
  6183. target.subtractToRef(eye, this._zAxis);
  6184. this._zAxis.normalize();
  6185. // X axis
  6186. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  6187. if (this._xAxis.lengthSquared() === 0) {
  6188. this._xAxis.x = 1.0;
  6189. }
  6190. else {
  6191. this._xAxis.normalize();
  6192. }
  6193. // Y axis
  6194. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  6195. this._yAxis.normalize();
  6196. // Eye angles
  6197. var ex = -Vector3.Dot(this._xAxis, eye);
  6198. var ey = -Vector3.Dot(this._yAxis, eye);
  6199. var ez = -Vector3.Dot(this._zAxis, eye);
  6200. 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);
  6201. };
  6202. /**
  6203. * 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"
  6204. * This function works in right handed mode
  6205. * @param eye defines the final position of the entity
  6206. * @param target defines where the entity should look at
  6207. * @param up defines the up vector for the entity
  6208. * @returns the new matrix
  6209. */
  6210. Matrix.LookAtRH = function (eye, target, up) {
  6211. var result = Matrix.Zero();
  6212. Matrix.LookAtRHToRef(eye, target, up, result);
  6213. return result;
  6214. };
  6215. /**
  6216. * 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".
  6217. * This function works in right handed mode
  6218. * @param eye defines the final position of the entity
  6219. * @param target defines where the entity should look at
  6220. * @param up defines the up vector for the entity
  6221. * @param result defines the target matrix
  6222. */
  6223. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  6224. // Z axis
  6225. eye.subtractToRef(target, this._zAxis);
  6226. this._zAxis.normalize();
  6227. // X axis
  6228. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  6229. if (this._xAxis.lengthSquared() === 0) {
  6230. this._xAxis.x = 1.0;
  6231. }
  6232. else {
  6233. this._xAxis.normalize();
  6234. }
  6235. // Y axis
  6236. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  6237. this._yAxis.normalize();
  6238. // Eye angles
  6239. var ex = -Vector3.Dot(this._xAxis, eye);
  6240. var ey = -Vector3.Dot(this._yAxis, eye);
  6241. var ez = -Vector3.Dot(this._zAxis, eye);
  6242. 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);
  6243. };
  6244. /**
  6245. * Create a left-handed orthographic projection matrix
  6246. * @param width defines the viewport width
  6247. * @param height defines the viewport height
  6248. * @param znear defines the near clip plane
  6249. * @param zfar defines the far clip plane
  6250. * @returns a new matrix as a left-handed orthographic projection matrix
  6251. */
  6252. Matrix.OrthoLH = function (width, height, znear, zfar) {
  6253. var matrix = Matrix.Zero();
  6254. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  6255. return matrix;
  6256. };
  6257. /**
  6258. * Store a left-handed orthographic projection to a given matrix
  6259. * @param width defines the viewport width
  6260. * @param height defines the viewport height
  6261. * @param znear defines the near clip plane
  6262. * @param zfar defines the far clip plane
  6263. * @param result defines the target matrix
  6264. */
  6265. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  6266. var n = znear;
  6267. var f = zfar;
  6268. var a = 2.0 / width;
  6269. var b = 2.0 / height;
  6270. var c = 2.0 / (f - n);
  6271. var d = -(f + n) / (f - n);
  6272. 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);
  6273. };
  6274. /**
  6275. * Create a left-handed orthographic projection matrix
  6276. * @param left defines the viewport left coordinate
  6277. * @param right defines the viewport right coordinate
  6278. * @param bottom defines the viewport bottom coordinate
  6279. * @param top defines the viewport top coordinate
  6280. * @param znear defines the near clip plane
  6281. * @param zfar defines the far clip plane
  6282. * @returns a new matrix as a left-handed orthographic projection matrix
  6283. */
  6284. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  6285. var matrix = Matrix.Zero();
  6286. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  6287. return matrix;
  6288. };
  6289. /**
  6290. * Stores a left-handed orthographic projection into a given matrix
  6291. * @param left defines the viewport left coordinate
  6292. * @param right defines the viewport right coordinate
  6293. * @param bottom defines the viewport bottom coordinate
  6294. * @param top defines the viewport top coordinate
  6295. * @param znear defines the near clip plane
  6296. * @param zfar defines the far clip plane
  6297. * @param result defines the target matrix
  6298. */
  6299. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  6300. var n = znear;
  6301. var f = zfar;
  6302. var a = 2.0 / (right - left);
  6303. var b = 2.0 / (top - bottom);
  6304. var c = 2.0 / (f - n);
  6305. var d = -(f + n) / (f - n);
  6306. var i0 = (left + right) / (left - right);
  6307. var i1 = (top + bottom) / (bottom - top);
  6308. 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);
  6309. };
  6310. /**
  6311. * Creates a right-handed orthographic projection matrix
  6312. * @param left defines the viewport left coordinate
  6313. * @param right defines the viewport right coordinate
  6314. * @param bottom defines the viewport bottom coordinate
  6315. * @param top defines the viewport top coordinate
  6316. * @param znear defines the near clip plane
  6317. * @param zfar defines the far clip plane
  6318. * @returns a new matrix as a right-handed orthographic projection matrix
  6319. */
  6320. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  6321. var matrix = Matrix.Zero();
  6322. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  6323. return matrix;
  6324. };
  6325. /**
  6326. * Stores a right-handed orthographic projection into a given matrix
  6327. * @param left defines the viewport left coordinate
  6328. * @param right defines the viewport right coordinate
  6329. * @param bottom defines the viewport bottom coordinate
  6330. * @param top defines the viewport top coordinate
  6331. * @param znear defines the near clip plane
  6332. * @param zfar defines the far clip plane
  6333. * @param result defines the target matrix
  6334. */
  6335. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  6336. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  6337. result.m[10] *= -1.0;
  6338. };
  6339. /**
  6340. * Creates a left-handed perspective projection matrix
  6341. * @param width defines the viewport width
  6342. * @param height defines the viewport height
  6343. * @param znear defines the near clip plane
  6344. * @param zfar defines the far clip plane
  6345. * @returns a new matrix as a left-handed perspective projection matrix
  6346. */
  6347. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  6348. var matrix = Matrix.Zero();
  6349. var n = znear;
  6350. var f = zfar;
  6351. var a = 2.0 * n / width;
  6352. var b = 2.0 * n / height;
  6353. var c = (f + n) / (f - n);
  6354. var d = -2.0 * f * n / (f - n);
  6355. 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);
  6356. return matrix;
  6357. };
  6358. /**
  6359. * Creates a left-handed perspective projection matrix
  6360. * @param fov defines the horizontal field of view
  6361. * @param aspect defines the aspect ratio
  6362. * @param znear defines the near clip plane
  6363. * @param zfar defines the far clip plane
  6364. * @returns a new matrix as a left-handed perspective projection matrix
  6365. */
  6366. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  6367. var matrix = Matrix.Zero();
  6368. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  6369. return matrix;
  6370. };
  6371. /**
  6372. * Stores a left-handed perspective projection into a given matrix
  6373. * @param fov defines the horizontal field of view
  6374. * @param aspect defines the aspect ratio
  6375. * @param znear defines the near clip plane
  6376. * @param zfar defines the far clip plane
  6377. * @param result defines the target matrix
  6378. * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally
  6379. */
  6380. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  6381. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  6382. var n = znear;
  6383. var f = zfar;
  6384. var t = 1.0 / (Math.tan(fov * 0.5));
  6385. var a = isVerticalFovFixed ? (t / aspect) : t;
  6386. var b = isVerticalFovFixed ? t : (t * aspect);
  6387. var c = (f + n) / (f - n);
  6388. var d = -2.0 * f * n / (f - n);
  6389. 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);
  6390. };
  6391. /**
  6392. * Creates a right-handed perspective projection matrix
  6393. * @param fov defines the horizontal field of view
  6394. * @param aspect defines the aspect ratio
  6395. * @param znear defines the near clip plane
  6396. * @param zfar defines the far clip plane
  6397. * @returns a new matrix as a right-handed perspective projection matrix
  6398. */
  6399. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  6400. var matrix = Matrix.Zero();
  6401. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  6402. return matrix;
  6403. };
  6404. /**
  6405. * Stores a right-handed perspective projection into a given matrix
  6406. * @param fov defines the horizontal field of view
  6407. * @param aspect defines the aspect ratio
  6408. * @param znear defines the near clip plane
  6409. * @param zfar defines the far clip plane
  6410. * @param result defines the target matrix
  6411. * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally
  6412. */
  6413. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  6414. //alternatively this could be expressed as:
  6415. // m = PerspectiveFovLHToRef
  6416. // m[10] *= -1.0;
  6417. // m[11] *= -1.0;
  6418. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  6419. var n = znear;
  6420. var f = zfar;
  6421. var t = 1.0 / (Math.tan(fov * 0.5));
  6422. var a = isVerticalFovFixed ? (t / aspect) : t;
  6423. var b = isVerticalFovFixed ? t : (t * aspect);
  6424. var c = -(f + n) / (f - n);
  6425. var d = -2 * f * n / (f - n);
  6426. 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);
  6427. };
  6428. /**
  6429. * Stores a perspective projection for WebVR info a given matrix
  6430. * @param fov defines the field of view
  6431. * @param znear defines the near clip plane
  6432. * @param zfar defines the far clip plane
  6433. * @param result defines the target matrix
  6434. * @param rightHanded defines if the matrix must be in right-handed mode (false by default)
  6435. */
  6436. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  6437. if (rightHanded === void 0) { rightHanded = false; }
  6438. var rightHandedFactor = rightHanded ? -1 : 1;
  6439. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  6440. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  6441. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  6442. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  6443. var xScale = 2.0 / (leftTan + rightTan);
  6444. var yScale = 2.0 / (upTan + downTan);
  6445. result.m[0] = xScale;
  6446. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  6447. result.m[5] = yScale;
  6448. result.m[6] = result.m[7] = 0.0;
  6449. result.m[8] = ((leftTan - rightTan) * xScale * 0.5);
  6450. result.m[9] = -((upTan - downTan) * yScale * 0.5);
  6451. result.m[10] = -zfar / (znear - zfar);
  6452. result.m[11] = 1.0 * rightHandedFactor;
  6453. result.m[12] = result.m[13] = result.m[15] = 0.0;
  6454. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  6455. result._markAsUpdated();
  6456. };
  6457. /**
  6458. * Computes a complete transformation matrix
  6459. * @param viewport defines the viewport to use
  6460. * @param world defines the world matrix
  6461. * @param view defines the view matrix
  6462. * @param projection defines the projection matrix
  6463. * @param zmin defines the near clip plane
  6464. * @param zmax defines the far clip plane
  6465. * @returns the transformation matrix
  6466. */
  6467. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  6468. var cw = viewport.width;
  6469. var ch = viewport.height;
  6470. var cx = viewport.x;
  6471. var cy = viewport.y;
  6472. 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);
  6473. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  6474. };
  6475. /**
  6476. * Extracts a 2x2 matrix from a given matrix and store the result in a Float32Array
  6477. * @param matrix defines the matrix to use
  6478. * @returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the given matrix
  6479. */
  6480. Matrix.GetAsMatrix2x2 = function (matrix) {
  6481. return new Float32Array([
  6482. matrix.m[0], matrix.m[1],
  6483. matrix.m[4], matrix.m[5]
  6484. ]);
  6485. };
  6486. /**
  6487. * Extracts a 3x3 matrix from a given matrix and store the result in a Float32Array
  6488. * @param matrix defines the matrix to use
  6489. * @returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the given matrix
  6490. */
  6491. Matrix.GetAsMatrix3x3 = function (matrix) {
  6492. return new Float32Array([
  6493. matrix.m[0], matrix.m[1], matrix.m[2],
  6494. matrix.m[4], matrix.m[5], matrix.m[6],
  6495. matrix.m[8], matrix.m[9], matrix.m[10]
  6496. ]);
  6497. };
  6498. /**
  6499. * Compute the transpose of a given matrix
  6500. * @param matrix defines the matrix to transpose
  6501. * @returns the new matrix
  6502. */
  6503. Matrix.Transpose = function (matrix) {
  6504. var result = new Matrix();
  6505. Matrix.TransposeToRef(matrix, result);
  6506. return result;
  6507. };
  6508. /**
  6509. * Compute the transpose of a matrix and store it in a target matrix
  6510. * @param matrix defines the matrix to transpose
  6511. * @param result defines the target matrix
  6512. */
  6513. Matrix.TransposeToRef = function (matrix, result) {
  6514. result.m[0] = matrix.m[0];
  6515. result.m[1] = matrix.m[4];
  6516. result.m[2] = matrix.m[8];
  6517. result.m[3] = matrix.m[12];
  6518. result.m[4] = matrix.m[1];
  6519. result.m[5] = matrix.m[5];
  6520. result.m[6] = matrix.m[9];
  6521. result.m[7] = matrix.m[13];
  6522. result.m[8] = matrix.m[2];
  6523. result.m[9] = matrix.m[6];
  6524. result.m[10] = matrix.m[10];
  6525. result.m[11] = matrix.m[14];
  6526. result.m[12] = matrix.m[3];
  6527. result.m[13] = matrix.m[7];
  6528. result.m[14] = matrix.m[11];
  6529. result.m[15] = matrix.m[15];
  6530. };
  6531. /**
  6532. * Computes a reflection matrix from a plane
  6533. * @param plane defines the reflection plane
  6534. * @returns a new matrix
  6535. */
  6536. Matrix.Reflection = function (plane) {
  6537. var matrix = new Matrix();
  6538. Matrix.ReflectionToRef(plane, matrix);
  6539. return matrix;
  6540. };
  6541. /**
  6542. * Computes a reflection matrix from a plane
  6543. * @param plane defines the reflection plane
  6544. * @param result defines the target matrix
  6545. */
  6546. Matrix.ReflectionToRef = function (plane, result) {
  6547. plane.normalize();
  6548. var x = plane.normal.x;
  6549. var y = plane.normal.y;
  6550. var z = plane.normal.z;
  6551. var temp = -2 * x;
  6552. var temp2 = -2 * y;
  6553. var temp3 = -2 * z;
  6554. result.m[0] = (temp * x) + 1;
  6555. result.m[1] = temp2 * x;
  6556. result.m[2] = temp3 * x;
  6557. result.m[3] = 0.0;
  6558. result.m[4] = temp * y;
  6559. result.m[5] = (temp2 * y) + 1;
  6560. result.m[6] = temp3 * y;
  6561. result.m[7] = 0.0;
  6562. result.m[8] = temp * z;
  6563. result.m[9] = temp2 * z;
  6564. result.m[10] = (temp3 * z) + 1;
  6565. result.m[11] = 0.0;
  6566. result.m[12] = temp * plane.d;
  6567. result.m[13] = temp2 * plane.d;
  6568. result.m[14] = temp3 * plane.d;
  6569. result.m[15] = 1.0;
  6570. result._markAsUpdated();
  6571. };
  6572. /**
  6573. * Sets the given matrix as a rotation matrix composed from the 3 left handed axes
  6574. * @param xaxis defines the value of the 1st axis
  6575. * @param yaxis defines the value of the 2nd axis
  6576. * @param zaxis defines the value of the 3rd axis
  6577. * @param result defines the target matrix
  6578. */
  6579. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  6580. result.m[0] = xaxis.x;
  6581. result.m[1] = xaxis.y;
  6582. result.m[2] = xaxis.z;
  6583. result.m[3] = 0.0;
  6584. result.m[4] = yaxis.x;
  6585. result.m[5] = yaxis.y;
  6586. result.m[6] = yaxis.z;
  6587. result.m[7] = 0.0;
  6588. result.m[8] = zaxis.x;
  6589. result.m[9] = zaxis.y;
  6590. result.m[10] = zaxis.z;
  6591. result.m[11] = 0.0;
  6592. result.m[12] = 0.0;
  6593. result.m[13] = 0.0;
  6594. result.m[14] = 0.0;
  6595. result.m[15] = 1.0;
  6596. result._markAsUpdated();
  6597. };
  6598. /**
  6599. * Creates a rotation matrix from a quaternion and stores it in a target matrix
  6600. * @param quat defines the quaternion to use
  6601. * @param result defines the target matrix
  6602. */
  6603. Matrix.FromQuaternionToRef = function (quat, result) {
  6604. var xx = quat.x * quat.x;
  6605. var yy = quat.y * quat.y;
  6606. var zz = quat.z * quat.z;
  6607. var xy = quat.x * quat.y;
  6608. var zw = quat.z * quat.w;
  6609. var zx = quat.z * quat.x;
  6610. var yw = quat.y * quat.w;
  6611. var yz = quat.y * quat.z;
  6612. var xw = quat.x * quat.w;
  6613. result.m[0] = 1.0 - (2.0 * (yy + zz));
  6614. result.m[1] = 2.0 * (xy + zw);
  6615. result.m[2] = 2.0 * (zx - yw);
  6616. result.m[3] = 0.0;
  6617. result.m[4] = 2.0 * (xy - zw);
  6618. result.m[5] = 1.0 - (2.0 * (zz + xx));
  6619. result.m[6] = 2.0 * (yz + xw);
  6620. result.m[7] = 0.0;
  6621. result.m[8] = 2.0 * (zx + yw);
  6622. result.m[9] = 2.0 * (yz - xw);
  6623. result.m[10] = 1.0 - (2.0 * (yy + xx));
  6624. result.m[11] = 0.0;
  6625. result.m[12] = 0.0;
  6626. result.m[13] = 0.0;
  6627. result.m[14] = 0.0;
  6628. result.m[15] = 1.0;
  6629. result._markAsUpdated();
  6630. };
  6631. Matrix._tempQuaternion = new Quaternion();
  6632. Matrix._xAxis = Vector3.Zero();
  6633. Matrix._yAxis = Vector3.Zero();
  6634. Matrix._zAxis = Vector3.Zero();
  6635. Matrix._updateFlagSeed = 0;
  6636. Matrix._identityReadOnly = Matrix.Identity();
  6637. return Matrix;
  6638. }());
  6639. BABYLON.Matrix = Matrix;
  6640. var Plane = /** @class */ (function () {
  6641. /**
  6642. * Creates a Plane object according to the given floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  6643. */
  6644. function Plane(a, b, c, d) {
  6645. this.normal = new Vector3(a, b, c);
  6646. this.d = d;
  6647. }
  6648. /**
  6649. * Returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  6650. */
  6651. Plane.prototype.asArray = function () {
  6652. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  6653. };
  6654. // Methods
  6655. /**
  6656. * Returns a new plane copied from the current Plane.
  6657. */
  6658. Plane.prototype.clone = function () {
  6659. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  6660. };
  6661. /**
  6662. * Returns the string "Plane".
  6663. */
  6664. Plane.prototype.getClassName = function () {
  6665. return "Plane";
  6666. };
  6667. /**
  6668. * Returns the Plane hash code.
  6669. */
  6670. Plane.prototype.getHashCode = function () {
  6671. var hash = this.normal.getHashCode();
  6672. hash = (hash * 397) ^ (this.d || 0);
  6673. return hash;
  6674. };
  6675. /**
  6676. * Normalize the current Plane in place.
  6677. * Returns the updated Plane.
  6678. */
  6679. Plane.prototype.normalize = function () {
  6680. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  6681. var magnitude = 0.0;
  6682. if (norm !== 0) {
  6683. magnitude = 1.0 / norm;
  6684. }
  6685. this.normal.x *= magnitude;
  6686. this.normal.y *= magnitude;
  6687. this.normal.z *= magnitude;
  6688. this.d *= magnitude;
  6689. return this;
  6690. };
  6691. /**
  6692. * Returns a new Plane as the result of the transformation of the current Plane by the given matrix.
  6693. */
  6694. Plane.prototype.transform = function (transformation) {
  6695. var transposedMatrix = Matrix.Transpose(transformation);
  6696. var x = this.normal.x;
  6697. var y = this.normal.y;
  6698. var z = this.normal.z;
  6699. var d = this.d;
  6700. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  6701. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  6702. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  6703. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  6704. return new Plane(normalX, normalY, normalZ, finalD);
  6705. };
  6706. /**
  6707. * Returns the dot product (float) of the point coordinates and the plane normal.
  6708. */
  6709. Plane.prototype.dotCoordinate = function (point) {
  6710. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  6711. };
  6712. /**
  6713. * Updates the current Plane from the plane defined by the three given points.
  6714. * Returns the updated Plane.
  6715. */
  6716. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  6717. var x1 = point2.x - point1.x;
  6718. var y1 = point2.y - point1.y;
  6719. var z1 = point2.z - point1.z;
  6720. var x2 = point3.x - point1.x;
  6721. var y2 = point3.y - point1.y;
  6722. var z2 = point3.z - point1.z;
  6723. var yz = (y1 * z2) - (z1 * y2);
  6724. var xz = (z1 * x2) - (x1 * z2);
  6725. var xy = (x1 * y2) - (y1 * x2);
  6726. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  6727. var invPyth;
  6728. if (pyth !== 0) {
  6729. invPyth = 1.0 / pyth;
  6730. }
  6731. else {
  6732. invPyth = 0.0;
  6733. }
  6734. this.normal.x = yz * invPyth;
  6735. this.normal.y = xz * invPyth;
  6736. this.normal.z = xy * invPyth;
  6737. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  6738. return this;
  6739. };
  6740. /**
  6741. * Boolean : True is the vector "direction" is the same side than the plane normal.
  6742. */
  6743. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  6744. var dot = Vector3.Dot(this.normal, direction);
  6745. return (dot <= epsilon);
  6746. };
  6747. /**
  6748. * Returns the signed distance (float) from the given point to the Plane.
  6749. */
  6750. Plane.prototype.signedDistanceTo = function (point) {
  6751. return Vector3.Dot(point, this.normal) + this.d;
  6752. };
  6753. // Statics
  6754. /**
  6755. * Returns a new Plane from the given array.
  6756. */
  6757. Plane.FromArray = function (array) {
  6758. return new Plane(array[0], array[1], array[2], array[3]);
  6759. };
  6760. /**
  6761. * Returns a new Plane defined by the three given points.
  6762. */
  6763. Plane.FromPoints = function (point1, point2, point3) {
  6764. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  6765. result.copyFromPoints(point1, point2, point3);
  6766. return result;
  6767. };
  6768. /**
  6769. * Returns a new Plane the normal vector to this plane at the given origin point.
  6770. * Note : the vector "normal" is updated because normalized.
  6771. */
  6772. Plane.FromPositionAndNormal = function (origin, normal) {
  6773. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  6774. normal.normalize();
  6775. result.normal = normal;
  6776. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6777. return result;
  6778. };
  6779. /**
  6780. * Returns the signed distance between the plane defined by the normal vector at the "origin"" point and the given other point.
  6781. */
  6782. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  6783. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6784. return Vector3.Dot(point, normal) + d;
  6785. };
  6786. return Plane;
  6787. }());
  6788. BABYLON.Plane = Plane;
  6789. /**
  6790. * Class used to represent a viewport on screen
  6791. */
  6792. var Viewport = /** @class */ (function () {
  6793. /**
  6794. * Creates a Viewport object located at (x, y) and sized (width, height)
  6795. * @param x defines viewport left coordinate
  6796. * @param y defines viewport top coordinate
  6797. * @param width defines the viewport width
  6798. * @param height defines the viewport height
  6799. */
  6800. function Viewport(
  6801. /** viewport left coordinate */
  6802. x,
  6803. /** viewport top coordinate */
  6804. y,
  6805. /**viewport width */
  6806. width,
  6807. /** viewport height */
  6808. height) {
  6809. this.x = x;
  6810. this.y = y;
  6811. this.width = width;
  6812. this.height = height;
  6813. }
  6814. /**
  6815. * Creates a new viewport using absolute sizing (from 0-> width, 0-> height instead of 0->1)
  6816. * @param renderWidthOrEngine defines either an engine or the rendering width
  6817. * @param renderHeight defines the rendering height
  6818. * @returns a new Viewport
  6819. */
  6820. Viewport.prototype.toGlobal = function (renderWidthOrEngine, renderHeight) {
  6821. if (renderWidthOrEngine.getRenderWidth) {
  6822. var engine = renderWidthOrEngine;
  6823. return this.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  6824. }
  6825. var renderWidth = renderWidthOrEngine;
  6826. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  6827. };
  6828. /**
  6829. * Returns a new Viewport copied from the current one
  6830. * @returns a new Viewport
  6831. */
  6832. Viewport.prototype.clone = function () {
  6833. return new Viewport(this.x, this.y, this.width, this.height);
  6834. };
  6835. return Viewport;
  6836. }());
  6837. BABYLON.Viewport = Viewport;
  6838. var Frustum = /** @class */ (function () {
  6839. function Frustum() {
  6840. }
  6841. /**
  6842. * Returns a new array of 6 Frustum planes computed by the given transformation matrix.
  6843. */
  6844. Frustum.GetPlanes = function (transform) {
  6845. var frustumPlanes = [];
  6846. for (var index = 0; index < 6; index++) {
  6847. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  6848. }
  6849. Frustum.GetPlanesToRef(transform, frustumPlanes);
  6850. return frustumPlanes;
  6851. };
  6852. Frustum.GetNearPlaneToRef = function (transform, frustumPlane) {
  6853. frustumPlane.normal.x = transform.m[3] + transform.m[2];
  6854. frustumPlane.normal.y = transform.m[7] + transform.m[6];
  6855. frustumPlane.normal.z = transform.m[11] + transform.m[10];
  6856. frustumPlane.d = transform.m[15] + transform.m[14];
  6857. frustumPlane.normalize();
  6858. };
  6859. Frustum.GetFarPlaneToRef = function (transform, frustumPlane) {
  6860. frustumPlane.normal.x = transform.m[3] - transform.m[2];
  6861. frustumPlane.normal.y = transform.m[7] - transform.m[6];
  6862. frustumPlane.normal.z = transform.m[11] - transform.m[10];
  6863. frustumPlane.d = transform.m[15] - transform.m[14];
  6864. frustumPlane.normalize();
  6865. };
  6866. Frustum.GetLeftPlaneToRef = function (transform, frustumPlane) {
  6867. frustumPlane.normal.x = transform.m[3] + transform.m[0];
  6868. frustumPlane.normal.y = transform.m[7] + transform.m[4];
  6869. frustumPlane.normal.z = transform.m[11] + transform.m[8];
  6870. frustumPlane.d = transform.m[15] + transform.m[12];
  6871. frustumPlane.normalize();
  6872. };
  6873. Frustum.GetRightPlaneToRef = function (transform, frustumPlane) {
  6874. frustumPlane.normal.x = transform.m[3] - transform.m[0];
  6875. frustumPlane.normal.y = transform.m[7] - transform.m[4];
  6876. frustumPlane.normal.z = transform.m[11] - transform.m[8];
  6877. frustumPlane.d = transform.m[15] - transform.m[12];
  6878. frustumPlane.normalize();
  6879. };
  6880. Frustum.GetTopPlaneToRef = function (transform, frustumPlane) {
  6881. frustumPlane.normal.x = transform.m[3] - transform.m[1];
  6882. frustumPlane.normal.y = transform.m[7] - transform.m[5];
  6883. frustumPlane.normal.z = transform.m[11] - transform.m[9];
  6884. frustumPlane.d = transform.m[15] - transform.m[13];
  6885. frustumPlane.normalize();
  6886. };
  6887. Frustum.GetBottomPlaneToRef = function (transform, frustumPlane) {
  6888. frustumPlane.normal.x = transform.m[3] + transform.m[1];
  6889. frustumPlane.normal.y = transform.m[7] + transform.m[5];
  6890. frustumPlane.normal.z = transform.m[11] + transform.m[9];
  6891. frustumPlane.d = transform.m[15] + transform.m[13];
  6892. frustumPlane.normalize();
  6893. };
  6894. /**
  6895. * Sets the given array "frustumPlanes" with the 6 Frustum planes computed by the given transformation matrix.
  6896. */
  6897. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  6898. // Near
  6899. Frustum.GetNearPlaneToRef(transform, frustumPlanes[0]);
  6900. // Far
  6901. Frustum.GetFarPlaneToRef(transform, frustumPlanes[1]);
  6902. // Left
  6903. Frustum.GetLeftPlaneToRef(transform, frustumPlanes[2]);
  6904. // Right
  6905. Frustum.GetRightPlaneToRef(transform, frustumPlanes[3]);
  6906. // Top
  6907. Frustum.GetTopPlaneToRef(transform, frustumPlanes[4]);
  6908. // Bottom
  6909. Frustum.GetBottomPlaneToRef(transform, frustumPlanes[5]);
  6910. };
  6911. return Frustum;
  6912. }());
  6913. BABYLON.Frustum = Frustum;
  6914. /** Defines supported spaces */
  6915. var Space;
  6916. (function (Space) {
  6917. /** Local (object) space */
  6918. Space[Space["LOCAL"] = 0] = "LOCAL";
  6919. /** World space */
  6920. Space[Space["WORLD"] = 1] = "WORLD";
  6921. /** Bone space */
  6922. Space[Space["BONE"] = 2] = "BONE";
  6923. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  6924. /** Defines the 3 main axes */
  6925. var Axis = /** @class */ (function () {
  6926. function Axis() {
  6927. }
  6928. /** X axis */
  6929. Axis.X = new Vector3(1.0, 0.0, 0.0);
  6930. /** Y axis */
  6931. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  6932. /** Z axis */
  6933. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  6934. return Axis;
  6935. }());
  6936. BABYLON.Axis = Axis;
  6937. ;
  6938. /** Class used to represent a Bezier curve */
  6939. var BezierCurve = /** @class */ (function () {
  6940. function BezierCurve() {
  6941. }
  6942. /**
  6943. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the given x1, y1, x2, y2 floats
  6944. * @param t defines the time
  6945. * @param x1 defines the left coordinate on X axis
  6946. * @param y1 defines the left coordinate on Y axis
  6947. * @param x2 defines the right coordinate on X axis
  6948. * @param y2 defines the right coordinate on Y axis
  6949. * @returns the interpolated value
  6950. */
  6951. BezierCurve.Interpolate = function (t, x1, y1, x2, y2) {
  6952. // Extract X (which is equal to time here)
  6953. var f0 = 1 - 3 * x2 + 3 * x1;
  6954. var f1 = 3 * x2 - 6 * x1;
  6955. var f2 = 3 * x1;
  6956. var refinedT = t;
  6957. for (var i = 0; i < 5; i++) {
  6958. var refinedT2 = refinedT * refinedT;
  6959. var refinedT3 = refinedT2 * refinedT;
  6960. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  6961. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  6962. refinedT -= (x - t) * slope;
  6963. refinedT = Math.min(1, Math.max(0, refinedT));
  6964. }
  6965. // Resolve cubic bezier for the given x
  6966. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  6967. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  6968. Math.pow(refinedT, 3);
  6969. };
  6970. return BezierCurve;
  6971. }());
  6972. BABYLON.BezierCurve = BezierCurve;
  6973. /**
  6974. * Defines potential orientation for back face culling
  6975. */
  6976. var Orientation;
  6977. (function (Orientation) {
  6978. /**
  6979. * Clockwise
  6980. */
  6981. Orientation[Orientation["CW"] = 0] = "CW";
  6982. /** Counter clockwise */
  6983. Orientation[Orientation["CCW"] = 1] = "CCW";
  6984. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  6985. /**
  6986. * Defines angle representation
  6987. */
  6988. var Angle = /** @class */ (function () {
  6989. /**
  6990. * Creates an Angle object of "radians" radians (float).
  6991. */
  6992. function Angle(radians) {
  6993. this._radians = radians;
  6994. if (this._radians < 0.0)
  6995. this._radians += (2.0 * Math.PI);
  6996. }
  6997. /**
  6998. * Get value in degrees
  6999. * @returns the Angle value in degrees (float)
  7000. */
  7001. Angle.prototype.degrees = function () {
  7002. return this._radians * 180.0 / Math.PI;
  7003. };
  7004. /**
  7005. * Get value in radians
  7006. * @returns the Angle value in radians (float)
  7007. */
  7008. Angle.prototype.radians = function () {
  7009. return this._radians;
  7010. };
  7011. /**
  7012. * Gets a new Angle object valued with the angle value in radians between the two given vectors
  7013. * @param a defines first vector
  7014. * @param b defines second vector
  7015. * @returns a new Angle
  7016. */
  7017. Angle.BetweenTwoPoints = function (a, b) {
  7018. var delta = b.subtract(a);
  7019. var theta = Math.atan2(delta.y, delta.x);
  7020. return new Angle(theta);
  7021. };
  7022. /**
  7023. * Gets a new Angle object from the given float in radians
  7024. * @param radians defines the angle value in radians
  7025. * @returns a new Angle
  7026. */
  7027. Angle.FromRadians = function (radians) {
  7028. return new Angle(radians);
  7029. };
  7030. /**
  7031. * Gets a new Angle object from the given float in degrees
  7032. * @param degrees defines the angle value in degrees
  7033. * @returns a new Angle
  7034. */
  7035. Angle.FromDegrees = function (degrees) {
  7036. return new Angle(degrees * Math.PI / 180.0);
  7037. };
  7038. return Angle;
  7039. }());
  7040. BABYLON.Angle = Angle;
  7041. /**
  7042. * This represents an arc in a 2d space.
  7043. */
  7044. var Arc2 = /** @class */ (function () {
  7045. /**
  7046. * Creates an Arc object from the three given points : start, middle and end.
  7047. * @param startPoint Defines the start point of the arc
  7048. * @param midPoint Defines the midlle point of the arc
  7049. * @param endPoint Defines the end point of the arc
  7050. */
  7051. function Arc2(
  7052. /** Defines the start point of the arc */
  7053. startPoint,
  7054. /** Defines the mid point of the arc */
  7055. midPoint,
  7056. /** Defines the end point of the arc */
  7057. endPoint) {
  7058. this.startPoint = startPoint;
  7059. this.midPoint = midPoint;
  7060. this.endPoint = endPoint;
  7061. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  7062. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  7063. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  7064. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  7065. 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);
  7066. this.radius = this.centerPoint.subtract(this.startPoint).length();
  7067. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  7068. var a1 = this.startAngle.degrees();
  7069. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  7070. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  7071. // angles correction
  7072. if (a2 - a1 > +180.0)
  7073. a2 -= 360.0;
  7074. if (a2 - a1 < -180.0)
  7075. a2 += 360.0;
  7076. if (a3 - a2 > +180.0)
  7077. a3 -= 360.0;
  7078. if (a3 - a2 < -180.0)
  7079. a3 += 360.0;
  7080. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  7081. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  7082. }
  7083. return Arc2;
  7084. }());
  7085. BABYLON.Arc2 = Arc2;
  7086. var Path2 = /** @class */ (function () {
  7087. /**
  7088. * Creates a Path2 object from the starting 2D coordinates x and y.
  7089. */
  7090. function Path2(x, y) {
  7091. this._points = new Array();
  7092. this._length = 0.0;
  7093. this.closed = false;
  7094. this._points.push(new Vector2(x, y));
  7095. }
  7096. /**
  7097. * Adds a new segment until the given coordinates (x, y) to the current Path2.
  7098. * Returns the updated Path2.
  7099. */
  7100. Path2.prototype.addLineTo = function (x, y) {
  7101. if (this.closed) {
  7102. return this;
  7103. }
  7104. var newPoint = new Vector2(x, y);
  7105. var previousPoint = this._points[this._points.length - 1];
  7106. this._points.push(newPoint);
  7107. this._length += newPoint.subtract(previousPoint).length();
  7108. return this;
  7109. };
  7110. /**
  7111. * 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.
  7112. * Returns the updated Path2.
  7113. */
  7114. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  7115. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  7116. if (this.closed) {
  7117. return this;
  7118. }
  7119. var startPoint = this._points[this._points.length - 1];
  7120. var midPoint = new Vector2(midX, midY);
  7121. var endPoint = new Vector2(endX, endY);
  7122. var arc = new Arc2(startPoint, midPoint, endPoint);
  7123. var increment = arc.angle.radians() / numberOfSegments;
  7124. if (arc.orientation === Orientation.CW)
  7125. increment *= -1;
  7126. var currentAngle = arc.startAngle.radians() + increment;
  7127. for (var i = 0; i < numberOfSegments; i++) {
  7128. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  7129. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  7130. this.addLineTo(x, y);
  7131. currentAngle += increment;
  7132. }
  7133. return this;
  7134. };
  7135. /**
  7136. * Closes the Path2.
  7137. * Returns the Path2.
  7138. */
  7139. Path2.prototype.close = function () {
  7140. this.closed = true;
  7141. return this;
  7142. };
  7143. /**
  7144. * Returns the Path2 total length (float).
  7145. */
  7146. Path2.prototype.length = function () {
  7147. var result = this._length;
  7148. if (!this.closed) {
  7149. var lastPoint = this._points[this._points.length - 1];
  7150. var firstPoint = this._points[0];
  7151. result += (firstPoint.subtract(lastPoint).length());
  7152. }
  7153. return result;
  7154. };
  7155. /**
  7156. * Returns the Path2 internal array of points.
  7157. */
  7158. Path2.prototype.getPoints = function () {
  7159. return this._points;
  7160. };
  7161. /**
  7162. * Returns a new Vector2 located at a percentage of the Path2 total length on this path.
  7163. */
  7164. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  7165. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  7166. return Vector2.Zero();
  7167. }
  7168. var lengthPosition = normalizedLengthPosition * this.length();
  7169. var previousOffset = 0;
  7170. for (var i = 0; i < this._points.length; i++) {
  7171. var j = (i + 1) % this._points.length;
  7172. var a = this._points[i];
  7173. var b = this._points[j];
  7174. var bToA = b.subtract(a);
  7175. var nextOffset = (bToA.length() + previousOffset);
  7176. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  7177. var dir = bToA.normalize();
  7178. var localOffset = lengthPosition - previousOffset;
  7179. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  7180. }
  7181. previousOffset = nextOffset;
  7182. }
  7183. return Vector2.Zero();
  7184. };
  7185. /**
  7186. * Returns a new Path2 starting at the coordinates (x, y).
  7187. */
  7188. Path2.StartingAt = function (x, y) {
  7189. return new Path2(x, y);
  7190. };
  7191. return Path2;
  7192. }());
  7193. BABYLON.Path2 = Path2;
  7194. var Path3D = /** @class */ (function () {
  7195. /**
  7196. * new Path3D(path, normal, raw)
  7197. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  7198. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  7199. * path : an array of Vector3, the curve axis of the Path3D
  7200. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  7201. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  7202. */
  7203. function Path3D(path, firstNormal, raw) {
  7204. if (firstNormal === void 0) { firstNormal = null; }
  7205. this.path = path;
  7206. this._curve = new Array();
  7207. this._distances = new Array();
  7208. this._tangents = new Array();
  7209. this._normals = new Array();
  7210. this._binormals = new Array();
  7211. for (var p = 0; p < path.length; p++) {
  7212. this._curve[p] = path[p].clone(); // hard copy
  7213. }
  7214. this._raw = raw || false;
  7215. this._compute(firstNormal);
  7216. }
  7217. /**
  7218. * Returns the Path3D array of successive Vector3 designing its curve.
  7219. */
  7220. Path3D.prototype.getCurve = function () {
  7221. return this._curve;
  7222. };
  7223. /**
  7224. * Returns an array populated with tangent vectors on each Path3D curve point.
  7225. */
  7226. Path3D.prototype.getTangents = function () {
  7227. return this._tangents;
  7228. };
  7229. /**
  7230. * Returns an array populated with normal vectors on each Path3D curve point.
  7231. */
  7232. Path3D.prototype.getNormals = function () {
  7233. return this._normals;
  7234. };
  7235. /**
  7236. * Returns an array populated with binormal vectors on each Path3D curve point.
  7237. */
  7238. Path3D.prototype.getBinormals = function () {
  7239. return this._binormals;
  7240. };
  7241. /**
  7242. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  7243. */
  7244. Path3D.prototype.getDistances = function () {
  7245. return this._distances;
  7246. };
  7247. /**
  7248. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  7249. * Returns the same object updated.
  7250. */
  7251. Path3D.prototype.update = function (path, firstNormal) {
  7252. if (firstNormal === void 0) { firstNormal = null; }
  7253. for (var p = 0; p < path.length; p++) {
  7254. this._curve[p].x = path[p].x;
  7255. this._curve[p].y = path[p].y;
  7256. this._curve[p].z = path[p].z;
  7257. }
  7258. this._compute(firstNormal);
  7259. return this;
  7260. };
  7261. // private function compute() : computes tangents, normals and binormals
  7262. Path3D.prototype._compute = function (firstNormal) {
  7263. var l = this._curve.length;
  7264. // first and last tangents
  7265. this._tangents[0] = this._getFirstNonNullVector(0);
  7266. if (!this._raw) {
  7267. this._tangents[0].normalize();
  7268. }
  7269. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  7270. if (!this._raw) {
  7271. this._tangents[l - 1].normalize();
  7272. }
  7273. // normals and binormals at first point : arbitrary vector with _normalVector()
  7274. var tg0 = this._tangents[0];
  7275. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  7276. this._normals[0] = pp0;
  7277. if (!this._raw) {
  7278. this._normals[0].normalize();
  7279. }
  7280. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  7281. if (!this._raw) {
  7282. this._binormals[0].normalize();
  7283. }
  7284. this._distances[0] = 0.0;
  7285. // normals and binormals : next points
  7286. var prev; // previous vector (segment)
  7287. var cur; // current vector (segment)
  7288. var curTang; // current tangent
  7289. // previous normal
  7290. var prevBinor; // previous binormal
  7291. for (var i = 1; i < l; i++) {
  7292. // tangents
  7293. prev = this._getLastNonNullVector(i);
  7294. if (i < l - 1) {
  7295. cur = this._getFirstNonNullVector(i);
  7296. this._tangents[i] = prev.add(cur);
  7297. this._tangents[i].normalize();
  7298. }
  7299. this._distances[i] = this._distances[i - 1] + prev.length();
  7300. // normals and binormals
  7301. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  7302. curTang = this._tangents[i];
  7303. prevBinor = this._binormals[i - 1];
  7304. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  7305. if (!this._raw) {
  7306. this._normals[i].normalize();
  7307. }
  7308. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  7309. if (!this._raw) {
  7310. this._binormals[i].normalize();
  7311. }
  7312. }
  7313. };
  7314. // private function getFirstNonNullVector(index)
  7315. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  7316. Path3D.prototype._getFirstNonNullVector = function (index) {
  7317. var i = 1;
  7318. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  7319. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  7320. i++;
  7321. nNVector = this._curve[index + i].subtract(this._curve[index]);
  7322. }
  7323. return nNVector;
  7324. };
  7325. // private function getLastNonNullVector(index)
  7326. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  7327. Path3D.prototype._getLastNonNullVector = function (index) {
  7328. var i = 1;
  7329. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  7330. while (nLVector.length() === 0 && index > i + 1) {
  7331. i++;
  7332. nLVector = this._curve[index].subtract(this._curve[index - i]);
  7333. }
  7334. return nLVector;
  7335. };
  7336. // private function normalVector(v0, vt, va) :
  7337. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  7338. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  7339. Path3D.prototype._normalVector = function (v0, vt, va) {
  7340. var normal0;
  7341. var tgl = vt.length();
  7342. if (tgl === 0.0) {
  7343. tgl = 1.0;
  7344. }
  7345. if (va === undefined || va === null) {
  7346. var point;
  7347. if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) { // search for a point in the plane
  7348. point = new Vector3(0.0, -1.0, 0.0);
  7349. }
  7350. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  7351. point = new Vector3(1.0, 0.0, 0.0);
  7352. }
  7353. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  7354. point = new Vector3(0.0, 0.0, 1.0);
  7355. }
  7356. else {
  7357. point = Vector3.Zero();
  7358. }
  7359. normal0 = Vector3.Cross(vt, point);
  7360. }
  7361. else {
  7362. normal0 = Vector3.Cross(vt, va);
  7363. Vector3.CrossToRef(normal0, vt, normal0);
  7364. }
  7365. normal0.normalize();
  7366. return normal0;
  7367. };
  7368. return Path3D;
  7369. }());
  7370. BABYLON.Path3D = Path3D;
  7371. var Curve3 = /** @class */ (function () {
  7372. /**
  7373. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  7374. * A Curve3 is designed from a series of successive Vector3.
  7375. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  7376. */
  7377. function Curve3(points) {
  7378. this._length = 0.0;
  7379. this._points = points;
  7380. this._length = this._computeLength(points);
  7381. }
  7382. /**
  7383. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  7384. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  7385. * @param v1 (Vector3) the control point
  7386. * @param v2 (Vector3) the end point of the Quadratic Bezier
  7387. * @param nbPoints (integer) the wanted number of points in the curve
  7388. */
  7389. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  7390. nbPoints = nbPoints > 2 ? nbPoints : 3;
  7391. var bez = new Array();
  7392. var equation = function (t, val0, val1, val2) {
  7393. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  7394. return res;
  7395. };
  7396. for (var i = 0; i <= nbPoints; i++) {
  7397. 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)));
  7398. }
  7399. return new Curve3(bez);
  7400. };
  7401. /**
  7402. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  7403. * @param v0 (Vector3) the origin point of the Cubic Bezier
  7404. * @param v1 (Vector3) the first control point
  7405. * @param v2 (Vector3) the second control point
  7406. * @param v3 (Vector3) the end point of the Cubic Bezier
  7407. * @param nbPoints (integer) the wanted number of points in the curve
  7408. */
  7409. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  7410. nbPoints = nbPoints > 3 ? nbPoints : 4;
  7411. var bez = new Array();
  7412. var equation = function (t, val0, val1, val2, val3) {
  7413. 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;
  7414. return res;
  7415. };
  7416. for (var i = 0; i <= nbPoints; i++) {
  7417. 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)));
  7418. }
  7419. return new Curve3(bez);
  7420. };
  7421. /**
  7422. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  7423. * @param p1 (Vector3) the origin point of the Hermite Spline
  7424. * @param t1 (Vector3) the tangent vector at the origin point
  7425. * @param p2 (Vector3) the end point of the Hermite Spline
  7426. * @param t2 (Vector3) the tangent vector at the end point
  7427. * @param nbPoints (integer) the wanted number of points in the curve
  7428. */
  7429. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  7430. var hermite = new Array();
  7431. var step = 1.0 / nbPoints;
  7432. for (var i = 0; i <= nbPoints; i++) {
  7433. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  7434. }
  7435. return new Curve3(hermite);
  7436. };
  7437. /**
  7438. * Returns a Curve3 object along a CatmullRom Spline curve :
  7439. * @param points (array of Vector3) the points the spline must pass through. At least, four points required
  7440. * @param nbPoints (integer) the wanted number of points between each curve control points
  7441. * @param closed (boolean) optional with default false, when true forms a closed loop from the points
  7442. */
  7443. Curve3.CreateCatmullRomSpline = function (points, nbPoints, closed) {
  7444. var catmullRom = new Array();
  7445. var step = 1.0 / nbPoints;
  7446. var amount = 0.0;
  7447. if (closed) {
  7448. var pointsCount = points.length;
  7449. for (var i = 0; i < pointsCount; i++) {
  7450. amount = 0;
  7451. for (var c = 0; c < nbPoints; c++) {
  7452. catmullRom.push(Vector3.CatmullRom(points[i % pointsCount], points[(i + 1) % pointsCount], points[(i + 2) % pointsCount], points[(i + 3) % pointsCount], amount));
  7453. amount += step;
  7454. }
  7455. }
  7456. catmullRom.push(catmullRom[0]);
  7457. }
  7458. else {
  7459. var totalPoints = new Array();
  7460. totalPoints.push(points[0].clone());
  7461. Array.prototype.push.apply(totalPoints, points);
  7462. totalPoints.push(points[points.length - 1].clone());
  7463. for (var i = 0; i < totalPoints.length - 3; i++) {
  7464. amount = 0;
  7465. for (var c = 0; c < nbPoints; c++) {
  7466. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  7467. amount += step;
  7468. }
  7469. }
  7470. i--;
  7471. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  7472. }
  7473. return new Curve3(catmullRom);
  7474. };
  7475. /**
  7476. * Returns the Curve3 stored array of successive Vector3
  7477. */
  7478. Curve3.prototype.getPoints = function () {
  7479. return this._points;
  7480. };
  7481. /**
  7482. * Returns the computed length (float) of the curve.
  7483. */
  7484. Curve3.prototype.length = function () {
  7485. return this._length;
  7486. };
  7487. /**
  7488. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  7489. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  7490. * curveA and curveB keep unchanged.
  7491. */
  7492. Curve3.prototype.continue = function (curve) {
  7493. var lastPoint = this._points[this._points.length - 1];
  7494. var continuedPoints = this._points.slice();
  7495. var curvePoints = curve.getPoints();
  7496. for (var i = 1; i < curvePoints.length; i++) {
  7497. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  7498. }
  7499. var continuedCurve = new Curve3(continuedPoints);
  7500. return continuedCurve;
  7501. };
  7502. Curve3.prototype._computeLength = function (path) {
  7503. var l = 0;
  7504. for (var i = 1; i < path.length; i++) {
  7505. l += (path[i].subtract(path[i - 1])).length();
  7506. }
  7507. return l;
  7508. };
  7509. return Curve3;
  7510. }());
  7511. BABYLON.Curve3 = Curve3;
  7512. // Vertex formats
  7513. var PositionNormalVertex = /** @class */ (function () {
  7514. function PositionNormalVertex(position, normal) {
  7515. if (position === void 0) { position = Vector3.Zero(); }
  7516. if (normal === void 0) { normal = Vector3.Up(); }
  7517. this.position = position;
  7518. this.normal = normal;
  7519. }
  7520. PositionNormalVertex.prototype.clone = function () {
  7521. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  7522. };
  7523. return PositionNormalVertex;
  7524. }());
  7525. BABYLON.PositionNormalVertex = PositionNormalVertex;
  7526. var PositionNormalTextureVertex = /** @class */ (function () {
  7527. function PositionNormalTextureVertex(position, normal, uv) {
  7528. if (position === void 0) { position = Vector3.Zero(); }
  7529. if (normal === void 0) { normal = Vector3.Up(); }
  7530. if (uv === void 0) { uv = Vector2.Zero(); }
  7531. this.position = position;
  7532. this.normal = normal;
  7533. this.uv = uv;
  7534. }
  7535. PositionNormalTextureVertex.prototype.clone = function () {
  7536. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  7537. };
  7538. return PositionNormalTextureVertex;
  7539. }());
  7540. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  7541. // Temporary pre-allocated objects for engine internal use
  7542. // usage in any internal function :
  7543. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  7544. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  7545. var Tmp = /** @class */ (function () {
  7546. function Tmp() {
  7547. }
  7548. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  7549. Tmp.Color4 = [new Color4(0, 0, 0, 0), new Color4(0, 0, 0, 0)];
  7550. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  7551. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  7552. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  7553. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  7554. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  7555. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  7556. Matrix.Zero(), Matrix.Zero(),
  7557. Matrix.Zero(), Matrix.Zero(),
  7558. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  7559. return Tmp;
  7560. }());
  7561. BABYLON.Tmp = Tmp;
  7562. // Same as Tmp but not exported to keep it only for math functions to avoid conflicts
  7563. var MathTmp = /** @class */ (function () {
  7564. function MathTmp() {
  7565. }
  7566. MathTmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()];
  7567. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  7568. MathTmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero(), Quaternion.Zero()];
  7569. return MathTmp;
  7570. }());
  7571. })(BABYLON || (BABYLON = {}));
  7572. //# sourceMappingURL=babylon.math.js.map
  7573. var BABYLON;
  7574. (function (BABYLON) {
  7575. var Scalar = /** @class */ (function () {
  7576. function Scalar() {
  7577. }
  7578. /**
  7579. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  7580. */
  7581. Scalar.WithinEpsilon = function (a, b, epsilon) {
  7582. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  7583. var num = a - b;
  7584. return -epsilon <= num && num <= epsilon;
  7585. };
  7586. /**
  7587. * Returns a string : the upper case translation of the number i to hexadecimal.
  7588. */
  7589. Scalar.ToHex = function (i) {
  7590. var str = i.toString(16);
  7591. if (i <= 15) {
  7592. return ("0" + str).toUpperCase();
  7593. }
  7594. return str.toUpperCase();
  7595. };
  7596. /**
  7597. * Returns -1 if value is negative and +1 is value is positive.
  7598. * Returns the value itself if it's equal to zero.
  7599. */
  7600. Scalar.Sign = function (value) {
  7601. value = +value; // convert to a number
  7602. if (value === 0 || isNaN(value))
  7603. return value;
  7604. return value > 0 ? 1 : -1;
  7605. };
  7606. /**
  7607. * Returns the value itself if it's between min and max.
  7608. * Returns min if the value is lower than min.
  7609. * Returns max if the value is greater than max.
  7610. */
  7611. Scalar.Clamp = function (value, min, max) {
  7612. if (min === void 0) { min = 0; }
  7613. if (max === void 0) { max = 1; }
  7614. return Math.min(max, Math.max(min, value));
  7615. };
  7616. /**
  7617. * Returns the log2 of value.
  7618. */
  7619. Scalar.Log2 = function (value) {
  7620. return Math.log(value) * Math.LOG2E;
  7621. };
  7622. /**
  7623. * Loops the value, so that it is never larger than length and never smaller than 0.
  7624. *
  7625. * This is similar to the modulo operator but it works with floating point numbers.
  7626. * For example, using 3.0 for t and 2.5 for length, the result would be 0.5.
  7627. * With t = 5 and length = 2.5, the result would be 0.0.
  7628. * Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator
  7629. */
  7630. Scalar.Repeat = function (value, length) {
  7631. return value - Math.floor(value / length) * length;
  7632. };
  7633. /**
  7634. * Normalize the value between 0.0 and 1.0 using min and max values
  7635. */
  7636. Scalar.Normalize = function (value, min, max) {
  7637. return (value - min) / (max - min);
  7638. };
  7639. /**
  7640. * Denormalize the value from 0.0 and 1.0 using min and max values
  7641. */
  7642. Scalar.Denormalize = function (normalized, min, max) {
  7643. return (normalized * (max - min) + min);
  7644. };
  7645. /**
  7646. * Calculates the shortest difference between two given angles given in degrees.
  7647. */
  7648. Scalar.DeltaAngle = function (current, target) {
  7649. var num = Scalar.Repeat(target - current, 360.0);
  7650. if (num > 180.0) {
  7651. num -= 360.0;
  7652. }
  7653. return num;
  7654. };
  7655. /**
  7656. * PingPongs the value t, so that it is never larger than length and never smaller than 0.
  7657. *
  7658. * The returned value will move back and forth between 0 and length
  7659. */
  7660. Scalar.PingPong = function (tx, length) {
  7661. var t = Scalar.Repeat(tx, length * 2.0);
  7662. return length - Math.abs(t - length);
  7663. };
  7664. /**
  7665. * Interpolates between min and max with smoothing at the limits.
  7666. *
  7667. * This function interpolates between min and max in a similar way to Lerp. However, the interpolation will gradually speed up
  7668. * from the start and slow down toward the end. This is useful for creating natural-looking animation, fading and other transitions.
  7669. */
  7670. Scalar.SmoothStep = function (from, to, tx) {
  7671. var t = Scalar.Clamp(tx);
  7672. t = -2.0 * t * t * t + 3.0 * t * t;
  7673. return to * t + from * (1.0 - t);
  7674. };
  7675. /**
  7676. * Moves a value current towards target.
  7677. *
  7678. * This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta.
  7679. * Negative values of maxDelta pushes the value away from target.
  7680. */
  7681. Scalar.MoveTowards = function (current, target, maxDelta) {
  7682. var result = 0;
  7683. if (Math.abs(target - current) <= maxDelta) {
  7684. result = target;
  7685. }
  7686. else {
  7687. result = current + Scalar.Sign(target - current) * maxDelta;
  7688. }
  7689. return result;
  7690. };
  7691. /**
  7692. * Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees.
  7693. *
  7694. * Variables current and target are assumed to be in degrees. For optimization reasons, negative values of maxDelta
  7695. * are not supported and may cause oscillation. To push current away from a target angle, add 180 to that angle instead.
  7696. */
  7697. Scalar.MoveTowardsAngle = function (current, target, maxDelta) {
  7698. var num = Scalar.DeltaAngle(current, target);
  7699. var result = 0;
  7700. if (-maxDelta < num && num < maxDelta) {
  7701. result = target;
  7702. }
  7703. else {
  7704. target = current + num;
  7705. result = Scalar.MoveTowards(current, target, maxDelta);
  7706. }
  7707. return result;
  7708. };
  7709. /**
  7710. * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
  7711. */
  7712. Scalar.Lerp = function (start, end, amount) {
  7713. return start + ((end - start) * amount);
  7714. };
  7715. /**
  7716. * Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees.
  7717. * The parameter t is clamped to the range [0, 1]. Variables a and b are assumed to be in degrees.
  7718. */
  7719. Scalar.LerpAngle = function (start, end, amount) {
  7720. var num = Scalar.Repeat(end - start, 360.0);
  7721. if (num > 180.0) {
  7722. num -= 360.0;
  7723. }
  7724. return start + num * Scalar.Clamp(amount);
  7725. };
  7726. /**
  7727. * Calculates the linear parameter t that produces the interpolant value within the range [a, b].
  7728. */
  7729. Scalar.InverseLerp = function (a, b, value) {
  7730. var result = 0;
  7731. if (a != b) {
  7732. result = Scalar.Clamp((value - a) / (b - a));
  7733. }
  7734. else {
  7735. result = 0.0;
  7736. }
  7737. return result;
  7738. };
  7739. /**
  7740. * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
  7741. */
  7742. Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  7743. var squared = amount * amount;
  7744. var cubed = amount * squared;
  7745. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  7746. var part2 = (-2.0 * cubed) + (3.0 * squared);
  7747. var part3 = (cubed - (2.0 * squared)) + amount;
  7748. var part4 = cubed - squared;
  7749. return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
  7750. };
  7751. /**
  7752. * Returns a random float number between and min and max values
  7753. */
  7754. Scalar.RandomRange = function (min, max) {
  7755. if (min === max)
  7756. return min;
  7757. return ((Math.random() * (max - min)) + min);
  7758. };
  7759. /**
  7760. * This function returns percentage of a number in a given range.
  7761. *
  7762. * RangeToPercent(40,20,60) will return 0.5 (50%)
  7763. * RangeToPercent(34,0,100) will return 0.34 (34%)
  7764. */
  7765. Scalar.RangeToPercent = function (number, min, max) {
  7766. return ((number - min) / (max - min));
  7767. };
  7768. /**
  7769. * This function returns number that corresponds to the percentage in a given range.
  7770. *
  7771. * PercentToRange(0.34,0,100) will return 34.
  7772. */
  7773. Scalar.PercentToRange = function (percent, min, max) {
  7774. return ((max - min) * percent + min);
  7775. };
  7776. /**
  7777. * Returns the angle converted to equivalent value between -Math.PI and Math.PI radians.
  7778. * @param angle The angle to normalize in radian.
  7779. * @return The converted angle.
  7780. */
  7781. Scalar.NormalizeRadians = function (angle) {
  7782. // More precise but slower version kept for reference.
  7783. // angle = angle % Tools.TwoPi;
  7784. // angle = (angle + Tools.TwoPi) % Tools.TwoPi;
  7785. //if (angle > Math.PI) {
  7786. // angle -= Tools.TwoPi;
  7787. //}
  7788. angle -= (Scalar.TwoPi * Math.floor((angle + Math.PI) / Scalar.TwoPi));
  7789. return angle;
  7790. };
  7791. /**
  7792. * Two pi constants convenient for computation.
  7793. */
  7794. Scalar.TwoPi = Math.PI * 2;
  7795. return Scalar;
  7796. }());
  7797. BABYLON.Scalar = Scalar;
  7798. })(BABYLON || (BABYLON = {}));
  7799. //# sourceMappingURL=babylon.math.scalar.js.map
  7800. //# sourceMappingURL=babylon.mixins.js.map
  7801. // Type definitions for WebGL 2, Editor's Draft Fri Feb 24 16:10:18 2017 -0800
  7802. // Project: https://www.khronos.org/registry/webgl/specs/latest/2.0/
  7803. // Definitions by: Nico Kemnitz <https://github.com/nkemnitz/>
  7804. // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
  7805. //# sourceMappingURL=babylon.webgl2.js.map
  7806. var BABYLON;
  7807. (function (BABYLON) {
  7808. var __decoratorInitialStore = {};
  7809. var __mergedStore = {};
  7810. var _copySource = function (creationFunction, source, instanciate) {
  7811. var destination = creationFunction();
  7812. // Tags
  7813. if (BABYLON.Tags) {
  7814. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7815. }
  7816. var classStore = getMergedStore(destination);
  7817. // Properties
  7818. for (var property in classStore) {
  7819. var propertyDescriptor = classStore[property];
  7820. var sourceProperty = source[property];
  7821. var propertyType = propertyDescriptor.type;
  7822. if (sourceProperty !== undefined && sourceProperty !== null) {
  7823. switch (propertyType) {
  7824. case 0: // Value
  7825. case 6: // Mesh reference
  7826. case 11: // Camera reference
  7827. destination[property] = sourceProperty;
  7828. break;
  7829. case 1: // Texture
  7830. destination[property] = (instanciate || sourceProperty.isRenderTarget) ? sourceProperty : sourceProperty.clone();
  7831. break;
  7832. case 2: // Color3
  7833. case 3: // FresnelParameters
  7834. case 4: // Vector2
  7835. case 5: // Vector3
  7836. case 7: // Color Curves
  7837. case 10: // Quaternion
  7838. destination[property] = instanciate ? sourceProperty : sourceProperty.clone();
  7839. break;
  7840. }
  7841. }
  7842. }
  7843. return destination;
  7844. };
  7845. function getDirectStore(target) {
  7846. var classKey = target.getClassName();
  7847. if (!__decoratorInitialStore[classKey]) {
  7848. __decoratorInitialStore[classKey] = {};
  7849. }
  7850. return __decoratorInitialStore[classKey];
  7851. }
  7852. /**
  7853. * Return the list of properties flagged as serializable
  7854. * @param target: host object
  7855. */
  7856. function getMergedStore(target) {
  7857. var classKey = target.getClassName();
  7858. if (__mergedStore[classKey]) {
  7859. return __mergedStore[classKey];
  7860. }
  7861. __mergedStore[classKey] = {};
  7862. var store = __mergedStore[classKey];
  7863. var currentTarget = target;
  7864. var currentKey = classKey;
  7865. while (currentKey) {
  7866. var initialStore = __decoratorInitialStore[currentKey];
  7867. for (var property in initialStore) {
  7868. store[property] = initialStore[property];
  7869. }
  7870. var parent_1 = void 0;
  7871. var done = false;
  7872. do {
  7873. parent_1 = Object.getPrototypeOf(currentTarget);
  7874. if (!parent_1.getClassName) {
  7875. done = true;
  7876. break;
  7877. }
  7878. if (parent_1.getClassName() !== currentKey) {
  7879. break;
  7880. }
  7881. currentTarget = parent_1;
  7882. } while (parent_1);
  7883. if (done) {
  7884. break;
  7885. }
  7886. currentKey = parent_1.getClassName();
  7887. currentTarget = parent_1;
  7888. }
  7889. return store;
  7890. }
  7891. function generateSerializableMember(type, sourceName) {
  7892. return function (target, propertyKey) {
  7893. var classStore = getDirectStore(target);
  7894. if (!classStore[propertyKey]) {
  7895. classStore[propertyKey] = { type: type, sourceName: sourceName };
  7896. }
  7897. };
  7898. }
  7899. function generateExpandMember(setCallback, targetKey) {
  7900. if (targetKey === void 0) { targetKey = null; }
  7901. return function (target, propertyKey) {
  7902. var key = targetKey || ("_" + propertyKey);
  7903. Object.defineProperty(target, propertyKey, {
  7904. get: function () {
  7905. return this[key];
  7906. },
  7907. set: function (value) {
  7908. if (this[key] === value) {
  7909. return;
  7910. }
  7911. this[key] = value;
  7912. target[setCallback].apply(this);
  7913. },
  7914. enumerable: true,
  7915. configurable: true
  7916. });
  7917. };
  7918. }
  7919. function expandToProperty(callback, targetKey) {
  7920. if (targetKey === void 0) { targetKey = null; }
  7921. return generateExpandMember(callback, targetKey);
  7922. }
  7923. BABYLON.expandToProperty = expandToProperty;
  7924. function serialize(sourceName) {
  7925. return generateSerializableMember(0, sourceName); // value member
  7926. }
  7927. BABYLON.serialize = serialize;
  7928. function serializeAsTexture(sourceName) {
  7929. return generateSerializableMember(1, sourceName); // texture member
  7930. }
  7931. BABYLON.serializeAsTexture = serializeAsTexture;
  7932. function serializeAsColor3(sourceName) {
  7933. return generateSerializableMember(2, sourceName); // color3 member
  7934. }
  7935. BABYLON.serializeAsColor3 = serializeAsColor3;
  7936. function serializeAsFresnelParameters(sourceName) {
  7937. return generateSerializableMember(3, sourceName); // fresnel parameters member
  7938. }
  7939. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  7940. function serializeAsVector2(sourceName) {
  7941. return generateSerializableMember(4, sourceName); // vector2 member
  7942. }
  7943. BABYLON.serializeAsVector2 = serializeAsVector2;
  7944. function serializeAsVector3(sourceName) {
  7945. return generateSerializableMember(5, sourceName); // vector3 member
  7946. }
  7947. BABYLON.serializeAsVector3 = serializeAsVector3;
  7948. function serializeAsMeshReference(sourceName) {
  7949. return generateSerializableMember(6, sourceName); // mesh reference member
  7950. }
  7951. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  7952. function serializeAsColorCurves(sourceName) {
  7953. return generateSerializableMember(7, sourceName); // color curves
  7954. }
  7955. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  7956. function serializeAsColor4(sourceName) {
  7957. return generateSerializableMember(8, sourceName); // color 4
  7958. }
  7959. BABYLON.serializeAsColor4 = serializeAsColor4;
  7960. function serializeAsImageProcessingConfiguration(sourceName) {
  7961. return generateSerializableMember(9, sourceName); // image processing
  7962. }
  7963. BABYLON.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration;
  7964. function serializeAsQuaternion(sourceName) {
  7965. return generateSerializableMember(10, sourceName); // quaternion member
  7966. }
  7967. BABYLON.serializeAsQuaternion = serializeAsQuaternion;
  7968. /**
  7969. * Decorator used to define property that can be serialized as reference to a camera
  7970. * @param sourceName defines the name of the property to decorate
  7971. */
  7972. function serializeAsCameraReference(sourceName) {
  7973. return generateSerializableMember(11, sourceName); // camera reference member
  7974. }
  7975. BABYLON.serializeAsCameraReference = serializeAsCameraReference;
  7976. var SerializationHelper = /** @class */ (function () {
  7977. function SerializationHelper() {
  7978. }
  7979. SerializationHelper.Serialize = function (entity, serializationObject) {
  7980. if (!serializationObject) {
  7981. serializationObject = {};
  7982. }
  7983. // Tags
  7984. if (BABYLON.Tags) {
  7985. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  7986. }
  7987. var serializedProperties = getMergedStore(entity);
  7988. // Properties
  7989. for (var property in serializedProperties) {
  7990. var propertyDescriptor = serializedProperties[property];
  7991. var targetPropertyName = propertyDescriptor.sourceName || property;
  7992. var propertyType = propertyDescriptor.type;
  7993. var sourceProperty = entity[property];
  7994. if (sourceProperty !== undefined && sourceProperty !== null) {
  7995. switch (propertyType) {
  7996. case 0: // Value
  7997. serializationObject[targetPropertyName] = sourceProperty;
  7998. break;
  7999. case 1: // Texture
  8000. serializationObject[targetPropertyName] = sourceProperty.serialize();
  8001. break;
  8002. case 2: // Color3
  8003. serializationObject[targetPropertyName] = sourceProperty.asArray();
  8004. break;
  8005. case 3: // FresnelParameters
  8006. serializationObject[targetPropertyName] = sourceProperty.serialize();
  8007. break;
  8008. case 4: // Vector2
  8009. serializationObject[targetPropertyName] = sourceProperty.asArray();
  8010. break;
  8011. case 5: // Vector3
  8012. serializationObject[targetPropertyName] = sourceProperty.asArray();
  8013. break;
  8014. case 6: // Mesh reference
  8015. serializationObject[targetPropertyName] = sourceProperty.id;
  8016. break;
  8017. case 7: // Color Curves
  8018. serializationObject[targetPropertyName] = sourceProperty.serialize();
  8019. break;
  8020. case 8: // Color 4
  8021. serializationObject[targetPropertyName] = sourceProperty.asArray();
  8022. break;
  8023. case 9: // Image Processing
  8024. serializationObject[targetPropertyName] = sourceProperty.serialize();
  8025. break;
  8026. case 10: // Quaternion
  8027. serializationObject[targetPropertyName] = sourceProperty.asArray();
  8028. break;
  8029. case 11: // Camera reference
  8030. serializationObject[targetPropertyName] = sourceProperty.id;
  8031. break;
  8032. }
  8033. }
  8034. }
  8035. return serializationObject;
  8036. };
  8037. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  8038. if (rootUrl === void 0) { rootUrl = null; }
  8039. var destination = creationFunction();
  8040. if (!rootUrl) {
  8041. rootUrl = "";
  8042. }
  8043. // Tags
  8044. if (BABYLON.Tags) {
  8045. BABYLON.Tags.AddTagsTo(destination, source.tags);
  8046. }
  8047. var classStore = getMergedStore(destination);
  8048. // Properties
  8049. for (var property in classStore) {
  8050. var propertyDescriptor = classStore[property];
  8051. var sourceProperty = source[propertyDescriptor.sourceName || property];
  8052. var propertyType = propertyDescriptor.type;
  8053. if (sourceProperty !== undefined && sourceProperty !== null) {
  8054. var dest = destination;
  8055. switch (propertyType) {
  8056. case 0: // Value
  8057. dest[property] = sourceProperty;
  8058. break;
  8059. case 1: // Texture
  8060. if (scene) {
  8061. dest[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  8062. }
  8063. break;
  8064. case 2: // Color3
  8065. dest[property] = BABYLON.Color3.FromArray(sourceProperty);
  8066. break;
  8067. case 3: // FresnelParameters
  8068. dest[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  8069. break;
  8070. case 4: // Vector2
  8071. dest[property] = BABYLON.Vector2.FromArray(sourceProperty);
  8072. break;
  8073. case 5: // Vector3
  8074. dest[property] = BABYLON.Vector3.FromArray(sourceProperty);
  8075. break;
  8076. case 6: // Mesh reference
  8077. if (scene) {
  8078. dest[property] = scene.getLastMeshByID(sourceProperty);
  8079. }
  8080. break;
  8081. case 7: // Color Curves
  8082. dest[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  8083. break;
  8084. case 8: // Color 4
  8085. dest[property] = BABYLON.Color4.FromArray(sourceProperty);
  8086. break;
  8087. case 9: // Image Processing
  8088. dest[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty);
  8089. break;
  8090. case 10: // Quaternion
  8091. dest[property] = BABYLON.Quaternion.FromArray(sourceProperty);
  8092. break;
  8093. case 11: // Camera reference
  8094. if (scene) {
  8095. dest[property] = scene.getCameraByID(sourceProperty);
  8096. }
  8097. break;
  8098. }
  8099. }
  8100. }
  8101. return destination;
  8102. };
  8103. SerializationHelper.Clone = function (creationFunction, source) {
  8104. return _copySource(creationFunction, source, false);
  8105. };
  8106. SerializationHelper.Instanciate = function (creationFunction, source) {
  8107. return _copySource(creationFunction, source, true);
  8108. };
  8109. return SerializationHelper;
  8110. }());
  8111. BABYLON.SerializationHelper = SerializationHelper;
  8112. })(BABYLON || (BABYLON = {}));
  8113. //# sourceMappingURL=babylon.decorators.js.map
  8114. var BABYLON;
  8115. (function (BABYLON) {
  8116. /**
  8117. * Wrapper class for promise with external resolve and reject.
  8118. */
  8119. var Deferred = /** @class */ (function () {
  8120. /**
  8121. * Constructor for this deferred object.
  8122. */
  8123. function Deferred() {
  8124. var _this = this;
  8125. this.promise = new Promise(function (resolve, reject) {
  8126. _this._resolve = resolve;
  8127. _this._reject = reject;
  8128. });
  8129. }
  8130. Object.defineProperty(Deferred.prototype, "resolve", {
  8131. /**
  8132. * The resolve method of the promise associated with this deferred object.
  8133. */
  8134. get: function () {
  8135. return this._resolve;
  8136. },
  8137. enumerable: true,
  8138. configurable: true
  8139. });
  8140. Object.defineProperty(Deferred.prototype, "reject", {
  8141. /**
  8142. * The reject method of the promise associated with this deferred object.
  8143. */
  8144. get: function () {
  8145. return this._reject;
  8146. },
  8147. enumerable: true,
  8148. configurable: true
  8149. });
  8150. return Deferred;
  8151. }());
  8152. BABYLON.Deferred = Deferred;
  8153. })(BABYLON || (BABYLON = {}));
  8154. //# sourceMappingURL=babylon.deferred.js.map
  8155. var BABYLON;
  8156. (function (BABYLON) {
  8157. /**
  8158. * A class serves as a medium between the observable and its observers
  8159. */
  8160. var EventState = /** @class */ (function () {
  8161. /**
  8162. * Create a new EventState
  8163. * @param mask defines the mask associated with this state
  8164. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  8165. * @param target defines the original target of the state
  8166. * @param currentTarget defines the current target of the state
  8167. */
  8168. function EventState(mask, skipNextObservers, target, currentTarget) {
  8169. if (skipNextObservers === void 0) { skipNextObservers = false; }
  8170. this.initalize(mask, skipNextObservers, target, currentTarget);
  8171. }
  8172. /**
  8173. * Initialize the current event state
  8174. * @param mask defines the mask associated with this state
  8175. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  8176. * @param target defines the original target of the state
  8177. * @param currentTarget defines the current target of the state
  8178. * @returns the current event state
  8179. */
  8180. EventState.prototype.initalize = function (mask, skipNextObservers, target, currentTarget) {
  8181. if (skipNextObservers === void 0) { skipNextObservers = false; }
  8182. this.mask = mask;
  8183. this.skipNextObservers = skipNextObservers;
  8184. this.target = target;
  8185. this.currentTarget = currentTarget;
  8186. return this;
  8187. };
  8188. return EventState;
  8189. }());
  8190. BABYLON.EventState = EventState;
  8191. /**
  8192. * Represent an Observer registered to a given Observable object.
  8193. */
  8194. var Observer = /** @class */ (function () {
  8195. /**
  8196. * Creates a new observer
  8197. * @param callback defines the callback to call when the observer is notified
  8198. * @param mask defines the mask of the observer (used to filter notifications)
  8199. * @param scope defines the current scope used to restore the JS context
  8200. */
  8201. function Observer(
  8202. /**
  8203. * Defines the callback to call when the observer is notified
  8204. */
  8205. callback,
  8206. /**
  8207. * Defines the mask of the observer (used to filter notifications)
  8208. */
  8209. mask,
  8210. /**
  8211. * Defines the current scope used to restore the JS context
  8212. */
  8213. scope) {
  8214. if (scope === void 0) { scope = null; }
  8215. this.callback = callback;
  8216. this.mask = mask;
  8217. this.scope = scope;
  8218. /** @hidden */
  8219. this._willBeUnregistered = false;
  8220. /**
  8221. * Gets or sets a property defining that the observer as to be unregistered after the next notification
  8222. */
  8223. this.unregisterOnNextCall = false;
  8224. }
  8225. return Observer;
  8226. }());
  8227. BABYLON.Observer = Observer;
  8228. /**
  8229. * Represent a list of observers registered to multiple Observables object.
  8230. */
  8231. var MultiObserver = /** @class */ (function () {
  8232. function MultiObserver() {
  8233. }
  8234. /**
  8235. * Release associated resources
  8236. */
  8237. MultiObserver.prototype.dispose = function () {
  8238. if (this._observers && this._observables) {
  8239. for (var index = 0; index < this._observers.length; index++) {
  8240. this._observables[index].remove(this._observers[index]);
  8241. }
  8242. }
  8243. this._observers = null;
  8244. this._observables = null;
  8245. };
  8246. /**
  8247. * Raise a callback when one of the observable will notify
  8248. * @param observables defines a list of observables to watch
  8249. * @param callback defines the callback to call on notification
  8250. * @param mask defines the mask used to filter notifications
  8251. * @param scope defines the current scope used to restore the JS context
  8252. * @returns the new MultiObserver
  8253. */
  8254. MultiObserver.Watch = function (observables, callback, mask, scope) {
  8255. if (mask === void 0) { mask = -1; }
  8256. if (scope === void 0) { scope = null; }
  8257. var result = new MultiObserver();
  8258. result._observers = new Array();
  8259. result._observables = observables;
  8260. for (var _i = 0, observables_1 = observables; _i < observables_1.length; _i++) {
  8261. var observable = observables_1[_i];
  8262. var observer = observable.add(callback, mask, false, scope);
  8263. if (observer) {
  8264. result._observers.push(observer);
  8265. }
  8266. }
  8267. return result;
  8268. };
  8269. return MultiObserver;
  8270. }());
  8271. BABYLON.MultiObserver = MultiObserver;
  8272. /**
  8273. * The Observable class is a simple implementation of the Observable pattern.
  8274. *
  8275. * 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.
  8276. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  8277. * 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).
  8278. * 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.
  8279. */
  8280. var Observable = /** @class */ (function () {
  8281. /**
  8282. * Creates a new observable
  8283. * @param onObserverAdded defines a callback to call when a new observer is added
  8284. */
  8285. function Observable(onObserverAdded) {
  8286. this._observers = new Array();
  8287. this._eventState = new EventState(0);
  8288. if (onObserverAdded) {
  8289. this._onObserverAdded = onObserverAdded;
  8290. }
  8291. }
  8292. /**
  8293. * Create a new Observer with the specified callback
  8294. * @param callback the callback that will be executed for that Observer
  8295. * @param mask the mask used to filter observers
  8296. * @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.
  8297. * @param scope optional scope for the callback to be called from
  8298. * @param unregisterOnFirstCall defines if the observer as to be unregistered after the next notification
  8299. * @returns the new observer created for the callback
  8300. */
  8301. Observable.prototype.add = function (callback, mask, insertFirst, scope, unregisterOnFirstCall) {
  8302. if (mask === void 0) { mask = -1; }
  8303. if (insertFirst === void 0) { insertFirst = false; }
  8304. if (scope === void 0) { scope = null; }
  8305. if (unregisterOnFirstCall === void 0) { unregisterOnFirstCall = false; }
  8306. if (!callback) {
  8307. return null;
  8308. }
  8309. var observer = new Observer(callback, mask, scope);
  8310. observer.unregisterOnNextCall = unregisterOnFirstCall;
  8311. if (insertFirst) {
  8312. this._observers.unshift(observer);
  8313. }
  8314. else {
  8315. this._observers.push(observer);
  8316. }
  8317. if (this._onObserverAdded) {
  8318. this._onObserverAdded(observer);
  8319. }
  8320. return observer;
  8321. };
  8322. /**
  8323. * Create a new Observer with the specified callback and unregisters after the next notification
  8324. * @param callback the callback that will be executed for that Observer
  8325. * @returns the new observer created for the callback
  8326. */
  8327. Observable.prototype.addOnce = function (callback) {
  8328. return this.add(callback, undefined, undefined, undefined, true);
  8329. };
  8330. /**
  8331. * Remove an Observer from the Observable object
  8332. * @param observer the instance of the Observer to remove
  8333. * @returns false if it doesn't belong to this Observable
  8334. */
  8335. Observable.prototype.remove = function (observer) {
  8336. if (!observer) {
  8337. return false;
  8338. }
  8339. var index = this._observers.indexOf(observer);
  8340. if (index !== -1) {
  8341. this._deferUnregister(observer);
  8342. return true;
  8343. }
  8344. return false;
  8345. };
  8346. /**
  8347. * Remove a callback from the Observable object
  8348. * @param callback the callback to remove
  8349. * @param scope optional scope. If used only the callbacks with this scope will be removed
  8350. * @returns false if it doesn't belong to this Observable
  8351. */
  8352. Observable.prototype.removeCallback = function (callback, scope) {
  8353. for (var index = 0; index < this._observers.length; index++) {
  8354. if (this._observers[index].callback === callback && (!scope || scope === this._observers[index].scope)) {
  8355. this._deferUnregister(this._observers[index]);
  8356. return true;
  8357. }
  8358. }
  8359. return false;
  8360. };
  8361. Observable.prototype._deferUnregister = function (observer) {
  8362. var _this = this;
  8363. observer.unregisterOnNextCall = false;
  8364. observer._willBeUnregistered = true;
  8365. BABYLON.Tools.SetImmediate(function () {
  8366. _this._remove(observer);
  8367. });
  8368. };
  8369. // This should only be called when not iterating over _observers to avoid callback skipping.
  8370. // Removes an observer from the _observer Array.
  8371. Observable.prototype._remove = function (observer) {
  8372. if (!observer) {
  8373. return false;
  8374. }
  8375. var index = this._observers.indexOf(observer);
  8376. if (index !== -1) {
  8377. this._observers.splice(index, 1);
  8378. return true;
  8379. }
  8380. return false;
  8381. };
  8382. /**
  8383. * Notify all Observers by calling their respective callback with the given data
  8384. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  8385. * @param eventData defines the data to send to all observers
  8386. * @param mask defines the mask of the current notification (observers with incompatible mask (ie mask & observer.mask === 0) will not be notified)
  8387. * @param target defines the original target of the state
  8388. * @param currentTarget defines the current target of the state
  8389. * @returns false if the complete observer chain was not processed (because one observer set the skipNextObservers to true)
  8390. */
  8391. Observable.prototype.notifyObservers = function (eventData, mask, target, currentTarget) {
  8392. if (mask === void 0) { mask = -1; }
  8393. if (!this._observers.length) {
  8394. return true;
  8395. }
  8396. var state = this._eventState;
  8397. state.mask = mask;
  8398. state.target = target;
  8399. state.currentTarget = currentTarget;
  8400. state.skipNextObservers = false;
  8401. state.lastReturnValue = eventData;
  8402. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  8403. var obs = _a[_i];
  8404. if (obs._willBeUnregistered) {
  8405. continue;
  8406. }
  8407. if (obs.mask & mask) {
  8408. if (obs.scope) {
  8409. state.lastReturnValue = obs.callback.apply(obs.scope, [eventData, state]);
  8410. }
  8411. else {
  8412. state.lastReturnValue = obs.callback(eventData, state);
  8413. }
  8414. if (obs.unregisterOnNextCall) {
  8415. this._deferUnregister(obs);
  8416. }
  8417. }
  8418. if (state.skipNextObservers) {
  8419. return false;
  8420. }
  8421. }
  8422. return true;
  8423. };
  8424. /**
  8425. * Calling this will execute each callback, expecting it to be a promise or return a value.
  8426. * If at any point in the chain one function fails, the promise will fail and the execution will not continue.
  8427. * This is useful when a chain of events (sometimes async events) is needed to initialize a certain object
  8428. * and it is crucial that all callbacks will be executed.
  8429. * The order of the callbacks is kept, callbacks are not executed parallel.
  8430. *
  8431. * @param eventData The data to be sent to each callback
  8432. * @param mask is used to filter observers defaults to -1
  8433. * @param target defines the callback target (see EventState)
  8434. * @param currentTarget defines he current object in the bubbling phase
  8435. * @returns {Promise<T>} will return a Promise than resolves when all callbacks executed successfully.
  8436. */
  8437. Observable.prototype.notifyObserversWithPromise = function (eventData, mask, target, currentTarget) {
  8438. var _this = this;
  8439. if (mask === void 0) { mask = -1; }
  8440. // create an empty promise
  8441. var p = Promise.resolve(eventData);
  8442. // no observers? return this promise.
  8443. if (!this._observers.length) {
  8444. return p;
  8445. }
  8446. var state = this._eventState;
  8447. state.mask = mask;
  8448. state.target = target;
  8449. state.currentTarget = currentTarget;
  8450. state.skipNextObservers = false;
  8451. // execute one callback after another (not using Promise.all, the order is important)
  8452. this._observers.forEach(function (obs) {
  8453. if (state.skipNextObservers) {
  8454. return;
  8455. }
  8456. if (obs._willBeUnregistered) {
  8457. return;
  8458. }
  8459. if (obs.mask & mask) {
  8460. if (obs.scope) {
  8461. p = p.then(function (lastReturnedValue) {
  8462. state.lastReturnValue = lastReturnedValue;
  8463. return obs.callback.apply(obs.scope, [eventData, state]);
  8464. });
  8465. }
  8466. else {
  8467. p = p.then(function (lastReturnedValue) {
  8468. state.lastReturnValue = lastReturnedValue;
  8469. return obs.callback(eventData, state);
  8470. });
  8471. }
  8472. if (obs.unregisterOnNextCall) {
  8473. _this._deferUnregister(obs);
  8474. }
  8475. }
  8476. });
  8477. // return the eventData
  8478. return p.then(function () { return eventData; });
  8479. };
  8480. /**
  8481. * Notify a specific observer
  8482. * @param observer defines the observer to notify
  8483. * @param eventData defines the data to be sent to each callback
  8484. * @param mask is used to filter observers defaults to -1
  8485. */
  8486. Observable.prototype.notifyObserver = function (observer, eventData, mask) {
  8487. if (mask === void 0) { mask = -1; }
  8488. var state = this._eventState;
  8489. state.mask = mask;
  8490. state.skipNextObservers = false;
  8491. observer.callback(eventData, state);
  8492. };
  8493. /**
  8494. * Gets a boolean indicating if the observable has at least one observer
  8495. * @returns true is the Observable has at least one Observer registered
  8496. */
  8497. Observable.prototype.hasObservers = function () {
  8498. return this._observers.length > 0;
  8499. };
  8500. /**
  8501. * Clear the list of observers
  8502. */
  8503. Observable.prototype.clear = function () {
  8504. this._observers = new Array();
  8505. this._onObserverAdded = null;
  8506. };
  8507. /**
  8508. * Clone the current observable
  8509. * @returns a new observable
  8510. */
  8511. Observable.prototype.clone = function () {
  8512. var result = new Observable();
  8513. result._observers = this._observers.slice(0);
  8514. return result;
  8515. };
  8516. /**
  8517. * Does this observable handles observer registered with a given mask
  8518. * @param mask defines the mask to be tested
  8519. * @return whether or not one observer registered with the given mask is handeled
  8520. **/
  8521. Observable.prototype.hasSpecificMask = function (mask) {
  8522. if (mask === void 0) { mask = -1; }
  8523. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  8524. var obs = _a[_i];
  8525. if (obs.mask & mask || obs.mask === mask) {
  8526. return true;
  8527. }
  8528. }
  8529. return false;
  8530. };
  8531. return Observable;
  8532. }());
  8533. BABYLON.Observable = Observable;
  8534. })(BABYLON || (BABYLON = {}));
  8535. //# sourceMappingURL=babylon.observable.js.map
  8536. var BABYLON;
  8537. (function (BABYLON) {
  8538. /**
  8539. * Defines an GC Friendly array where the backfield array do not shrink to prevent over allocations.
  8540. */
  8541. var SmartArray = /** @class */ (function () {
  8542. /**
  8543. * Instantiates a Smart Array.
  8544. * @param capacity defines the default capacity of the array.
  8545. */
  8546. function SmartArray(capacity) {
  8547. /**
  8548. * The active length of the array.
  8549. */
  8550. this.length = 0;
  8551. this.data = new Array(capacity);
  8552. this._id = SmartArray._GlobalId++;
  8553. }
  8554. /**
  8555. * Pushes a value at the end of the active data.
  8556. * @param value defines the object to push in the array.
  8557. */
  8558. SmartArray.prototype.push = function (value) {
  8559. this.data[this.length++] = value;
  8560. if (this.length > this.data.length) {
  8561. this.data.length *= 2;
  8562. }
  8563. };
  8564. /**
  8565. * Iterates over the active data and apply the lambda to them.
  8566. * @param func defines the action to apply on each value.
  8567. */
  8568. SmartArray.prototype.forEach = function (func) {
  8569. for (var index = 0; index < this.length; index++) {
  8570. func(this.data[index]);
  8571. }
  8572. };
  8573. /**
  8574. * Sorts the full sets of data.
  8575. * @param compareFn defines the comparison function to apply.
  8576. */
  8577. SmartArray.prototype.sort = function (compareFn) {
  8578. this.data.sort(compareFn);
  8579. };
  8580. /**
  8581. * Resets the active data to an empty array.
  8582. */
  8583. SmartArray.prototype.reset = function () {
  8584. this.length = 0;
  8585. };
  8586. /**
  8587. * Releases all the data from the array as well as the array.
  8588. */
  8589. SmartArray.prototype.dispose = function () {
  8590. this.reset();
  8591. if (this.data) {
  8592. this.data.length = 0;
  8593. this.data = [];
  8594. }
  8595. };
  8596. /**
  8597. * Concats the active data with a given array.
  8598. * @param array defines the data to concatenate with.
  8599. */
  8600. SmartArray.prototype.concat = function (array) {
  8601. if (array.length === 0) {
  8602. return;
  8603. }
  8604. if (this.length + array.length > this.data.length) {
  8605. this.data.length = (this.length + array.length) * 2;
  8606. }
  8607. for (var index = 0; index < array.length; index++) {
  8608. this.data[this.length++] = (array.data || array)[index];
  8609. }
  8610. };
  8611. /**
  8612. * Returns the position of a value in the active data.
  8613. * @param value defines the value to find the index for
  8614. * @returns the index if found in the active data otherwise -1
  8615. */
  8616. SmartArray.prototype.indexOf = function (value) {
  8617. var position = this.data.indexOf(value);
  8618. if (position >= this.length) {
  8619. return -1;
  8620. }
  8621. return position;
  8622. };
  8623. /**
  8624. * Returns whether an element is part of the active data.
  8625. * @param value defines the value to look for
  8626. * @returns true if found in the active data otherwise false
  8627. */
  8628. SmartArray.prototype.contains = function (value) {
  8629. return this.indexOf(value) !== -1;
  8630. };
  8631. // Statics
  8632. SmartArray._GlobalId = 0;
  8633. return SmartArray;
  8634. }());
  8635. BABYLON.SmartArray = SmartArray;
  8636. /**
  8637. * Defines an GC Friendly array where the backfield array do not shrink to prevent over allocations.
  8638. * The data in this array can only be present once
  8639. */
  8640. var SmartArrayNoDuplicate = /** @class */ (function (_super) {
  8641. __extends(SmartArrayNoDuplicate, _super);
  8642. function SmartArrayNoDuplicate() {
  8643. var _this = _super !== null && _super.apply(this, arguments) || this;
  8644. _this._duplicateId = 0;
  8645. return _this;
  8646. }
  8647. /**
  8648. * Pushes a value at the end of the active data.
  8649. * THIS DOES NOT PREVENT DUPPLICATE DATA
  8650. * @param value defines the object to push in the array.
  8651. */
  8652. SmartArrayNoDuplicate.prototype.push = function (value) {
  8653. _super.prototype.push.call(this, value);
  8654. if (!value.__smartArrayFlags) {
  8655. value.__smartArrayFlags = {};
  8656. }
  8657. value.__smartArrayFlags[this._id] = this._duplicateId;
  8658. };
  8659. /**
  8660. * Pushes a value at the end of the active data.
  8661. * If the data is already present, it won t be added again
  8662. * @param value defines the object to push in the array.
  8663. * @returns true if added false if it was already present
  8664. */
  8665. SmartArrayNoDuplicate.prototype.pushNoDuplicate = function (value) {
  8666. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  8667. return false;
  8668. }
  8669. this.push(value);
  8670. return true;
  8671. };
  8672. /**
  8673. * Resets the active data to an empty array.
  8674. */
  8675. SmartArrayNoDuplicate.prototype.reset = function () {
  8676. _super.prototype.reset.call(this);
  8677. this._duplicateId++;
  8678. };
  8679. /**
  8680. * Concats the active data with a given array.
  8681. * This ensures no dupplicate will be present in the result.
  8682. * @param array defines the data to concatenate with.
  8683. */
  8684. SmartArrayNoDuplicate.prototype.concatWithNoDuplicate = function (array) {
  8685. if (array.length === 0) {
  8686. return;
  8687. }
  8688. if (this.length + array.length > this.data.length) {
  8689. this.data.length = (this.length + array.length) * 2;
  8690. }
  8691. for (var index = 0; index < array.length; index++) {
  8692. var item = (array.data || array)[index];
  8693. this.pushNoDuplicate(item);
  8694. }
  8695. };
  8696. return SmartArrayNoDuplicate;
  8697. }(SmartArray));
  8698. BABYLON.SmartArrayNoDuplicate = SmartArrayNoDuplicate;
  8699. })(BABYLON || (BABYLON = {}));
  8700. //# sourceMappingURL=babylon.smartArray.js.map
  8701. var BABYLON;
  8702. (function (BABYLON) {
  8703. /** Class used to store color4 gradient */
  8704. var ColorGradient = /** @class */ (function () {
  8705. function ColorGradient() {
  8706. }
  8707. /**
  8708. * Will get a color picked randomly between color1 and color2.
  8709. * If color2 is undefined then color1 will be used
  8710. * @param result defines the target Color4 to store the result in
  8711. */
  8712. ColorGradient.prototype.getColorToRef = function (result) {
  8713. if (!this.color2) {
  8714. result.copyFrom(this.color1);
  8715. return;
  8716. }
  8717. BABYLON.Color4.LerpToRef(this.color1, this.color2, Math.random(), result);
  8718. };
  8719. return ColorGradient;
  8720. }());
  8721. BABYLON.ColorGradient = ColorGradient;
  8722. /** Class used to store color 3 gradient */
  8723. var Color3Gradient = /** @class */ (function () {
  8724. function Color3Gradient() {
  8725. }
  8726. return Color3Gradient;
  8727. }());
  8728. BABYLON.Color3Gradient = Color3Gradient;
  8729. /** Class used to store factor gradient */
  8730. var FactorGradient = /** @class */ (function () {
  8731. function FactorGradient() {
  8732. }
  8733. /**
  8734. * Will get a number picked randomly between factor1 and factor2.
  8735. * If factor2 is undefined then factor1 will be used
  8736. * @returns the picked number
  8737. */
  8738. FactorGradient.prototype.getFactor = function () {
  8739. if (this.factor2 === undefined) {
  8740. return this.factor1;
  8741. }
  8742. return BABYLON.Scalar.Lerp(this.factor1, this.factor2, Math.random());
  8743. };
  8744. return FactorGradient;
  8745. }());
  8746. BABYLON.FactorGradient = FactorGradient;
  8747. // See https://stackoverflow.com/questions/12915412/how-do-i-extend-a-host-object-e-g-error-in-typescript
  8748. // and https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work
  8749. var LoadFileError = /** @class */ (function (_super) {
  8750. __extends(LoadFileError, _super);
  8751. function LoadFileError(message, request) {
  8752. var _this = _super.call(this, message) || this;
  8753. _this.request = request;
  8754. _this.name = "LoadFileError";
  8755. LoadFileError._setPrototypeOf(_this, LoadFileError.prototype);
  8756. return _this;
  8757. }
  8758. // Polyfill for Object.setPrototypeOf if necessary.
  8759. LoadFileError._setPrototypeOf = Object.setPrototypeOf || (function (o, proto) { o.__proto__ = proto; return o; });
  8760. return LoadFileError;
  8761. }(Error));
  8762. BABYLON.LoadFileError = LoadFileError;
  8763. var RetryStrategy = /** @class */ (function () {
  8764. function RetryStrategy() {
  8765. }
  8766. RetryStrategy.ExponentialBackoff = function (maxRetries, baseInterval) {
  8767. if (maxRetries === void 0) { maxRetries = 3; }
  8768. if (baseInterval === void 0) { baseInterval = 500; }
  8769. return function (url, request, retryIndex) {
  8770. if (request.status !== 0 || retryIndex >= maxRetries || url.indexOf("file:") !== -1) {
  8771. return -1;
  8772. }
  8773. return Math.pow(2, retryIndex) * baseInterval;
  8774. };
  8775. };
  8776. return RetryStrategy;
  8777. }());
  8778. BABYLON.RetryStrategy = RetryStrategy;
  8779. // Screenshots
  8780. var screenshotCanvas;
  8781. var cloneValue = function (source, destinationObject) {
  8782. if (!source)
  8783. return null;
  8784. if (source instanceof BABYLON.Mesh) {
  8785. return null;
  8786. }
  8787. if (source instanceof BABYLON.SubMesh) {
  8788. return source.clone(destinationObject);
  8789. }
  8790. else if (source.clone) {
  8791. return source.clone();
  8792. }
  8793. return null;
  8794. };
  8795. var Tools = /** @class */ (function () {
  8796. function Tools() {
  8797. }
  8798. /**
  8799. * Read the content of a byte array at a specified coordinates (taking in account wrapping)
  8800. * @param u defines the coordinate on X axis
  8801. * @param v defines the coordinate on Y axis
  8802. * @param width defines the width of the source data
  8803. * @param height defines the height of the source data
  8804. * @param pixels defines the source byte array
  8805. * @param color defines the output color
  8806. */
  8807. Tools.FetchToRef = function (u, v, width, height, pixels, color) {
  8808. var wrappedU = ((Math.abs(u) * width) % width) | 0;
  8809. var wrappedV = ((Math.abs(v) * height) % height) | 0;
  8810. var position = (wrappedU + wrappedV * width) * 4;
  8811. color.r = pixels[position] / 255;
  8812. color.g = pixels[position + 1] / 255;
  8813. color.b = pixels[position + 2] / 255;
  8814. color.a = pixels[position + 3] / 255;
  8815. };
  8816. /**
  8817. * Interpolates between a and b via alpha
  8818. * @param a The lower value (returned when alpha = 0)
  8819. * @param b The upper value (returned when alpha = 1)
  8820. * @param alpha The interpolation-factor
  8821. * @return The mixed value
  8822. */
  8823. Tools.Mix = function (a, b, alpha) {
  8824. return a * (1 - alpha) + b * alpha;
  8825. };
  8826. Tools.Instantiate = function (className) {
  8827. if (Tools.RegisteredExternalClasses && Tools.RegisteredExternalClasses[className]) {
  8828. return Tools.RegisteredExternalClasses[className];
  8829. }
  8830. var arr = className.split(".");
  8831. var fn = (window || this);
  8832. for (var i = 0, len = arr.length; i < len; i++) {
  8833. fn = fn[arr[i]];
  8834. }
  8835. if (typeof fn !== "function") {
  8836. return null;
  8837. }
  8838. return fn;
  8839. };
  8840. /**
  8841. * Provides a slice function that will work even on IE
  8842. * @param data defines the array to slice
  8843. * @param start defines the start of the data (optional)
  8844. * @param end defines the end of the data (optional)
  8845. * @returns the new sliced array
  8846. */
  8847. Tools.Slice = function (data, start, end) {
  8848. if (data.slice) {
  8849. return data.slice(start, end);
  8850. }
  8851. return Array.prototype.slice.call(data, start, end);
  8852. };
  8853. Tools.SetImmediate = function (action) {
  8854. if (Tools.IsWindowObjectExist() && window.setImmediate) {
  8855. window.setImmediate(action);
  8856. }
  8857. else {
  8858. setTimeout(action, 1);
  8859. }
  8860. };
  8861. Tools.IsExponentOfTwo = function (value) {
  8862. var count = 1;
  8863. do {
  8864. count *= 2;
  8865. } while (count < value);
  8866. return count === value;
  8867. };
  8868. /**
  8869. * Returns the nearest 32-bit single precision float representation of a Number
  8870. * @param value A Number. If the parameter is of a different type, it will get converted
  8871. * to a number or to NaN if it cannot be converted
  8872. * @returns number
  8873. */
  8874. Tools.FloatRound = function (value) {
  8875. if (Math.fround) {
  8876. return Math.fround(value);
  8877. }
  8878. return (Tools._tmpFloatArray[0] = value);
  8879. };
  8880. /**
  8881. * Find the next highest power of two.
  8882. * @param x Number to start search from.
  8883. * @return Next highest power of two.
  8884. */
  8885. Tools.CeilingPOT = function (x) {
  8886. x--;
  8887. x |= x >> 1;
  8888. x |= x >> 2;
  8889. x |= x >> 4;
  8890. x |= x >> 8;
  8891. x |= x >> 16;
  8892. x++;
  8893. return x;
  8894. };
  8895. /**
  8896. * Find the next lowest power of two.
  8897. * @param x Number to start search from.
  8898. * @return Next lowest power of two.
  8899. */
  8900. Tools.FloorPOT = function (x) {
  8901. x = x | (x >> 1);
  8902. x = x | (x >> 2);
  8903. x = x | (x >> 4);
  8904. x = x | (x >> 8);
  8905. x = x | (x >> 16);
  8906. return x - (x >> 1);
  8907. };
  8908. /**
  8909. * Find the nearest power of two.
  8910. * @param x Number to start search from.
  8911. * @return Next nearest power of two.
  8912. */
  8913. Tools.NearestPOT = function (x) {
  8914. var c = Tools.CeilingPOT(x);
  8915. var f = Tools.FloorPOT(x);
  8916. return (c - x) > (x - f) ? f : c;
  8917. };
  8918. Tools.GetExponentOfTwo = function (value, max, mode) {
  8919. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  8920. var pot;
  8921. switch (mode) {
  8922. case BABYLON.Engine.SCALEMODE_FLOOR:
  8923. pot = Tools.FloorPOT(value);
  8924. break;
  8925. case BABYLON.Engine.SCALEMODE_NEAREST:
  8926. pot = Tools.NearestPOT(value);
  8927. break;
  8928. case BABYLON.Engine.SCALEMODE_CEILING:
  8929. default:
  8930. pot = Tools.CeilingPOT(value);
  8931. break;
  8932. }
  8933. return Math.min(pot, max);
  8934. };
  8935. Tools.GetFilename = function (path) {
  8936. var index = path.lastIndexOf("/");
  8937. if (index < 0)
  8938. return path;
  8939. return path.substring(index + 1);
  8940. };
  8941. /**
  8942. * Extracts the "folder" part of a path (everything before the filename).
  8943. * @param uri The URI to extract the info from
  8944. * @param returnUnchangedIfNoSlash Do not touch the URI if no slashes are present
  8945. * @returns The "folder" part of the path
  8946. */
  8947. Tools.GetFolderPath = function (uri, returnUnchangedIfNoSlash) {
  8948. if (returnUnchangedIfNoSlash === void 0) { returnUnchangedIfNoSlash = false; }
  8949. var index = uri.lastIndexOf("/");
  8950. if (index < 0) {
  8951. if (returnUnchangedIfNoSlash) {
  8952. return uri;
  8953. }
  8954. return "";
  8955. }
  8956. return uri.substring(0, index + 1);
  8957. };
  8958. Tools.GetDOMTextContent = function (element) {
  8959. var result = "";
  8960. var child = element.firstChild;
  8961. while (child) {
  8962. if (child.nodeType === 3) {
  8963. result += child.textContent;
  8964. }
  8965. child = child.nextSibling;
  8966. }
  8967. return result;
  8968. };
  8969. Tools.ToDegrees = function (angle) {
  8970. return angle * 180 / Math.PI;
  8971. };
  8972. Tools.ToRadians = function (angle) {
  8973. return angle * Math.PI / 180;
  8974. };
  8975. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  8976. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  8977. var output = "";
  8978. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  8979. var i = 0;
  8980. var bytes = new Uint8Array(buffer);
  8981. while (i < bytes.length) {
  8982. chr1 = bytes[i++];
  8983. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  8984. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  8985. enc1 = chr1 >> 2;
  8986. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  8987. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  8988. enc4 = chr3 & 63;
  8989. if (isNaN(chr2)) {
  8990. enc3 = enc4 = 64;
  8991. }
  8992. else if (isNaN(chr3)) {
  8993. enc4 = 64;
  8994. }
  8995. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  8996. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  8997. }
  8998. return "data:image/png;base64," + output;
  8999. };
  9000. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  9001. if (bias === void 0) { bias = null; }
  9002. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  9003. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  9004. for (var index = indexStart; index < indexStart + indexCount; index++) {
  9005. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  9006. minimum = BABYLON.Vector3.Minimize(current, minimum);
  9007. maximum = BABYLON.Vector3.Maximize(current, maximum);
  9008. }
  9009. if (bias) {
  9010. minimum.x -= minimum.x * bias.x + bias.y;
  9011. minimum.y -= minimum.y * bias.x + bias.y;
  9012. minimum.z -= minimum.z * bias.x + bias.y;
  9013. maximum.x += maximum.x * bias.x + bias.y;
  9014. maximum.y += maximum.y * bias.x + bias.y;
  9015. maximum.z += maximum.z * bias.x + bias.y;
  9016. }
  9017. return {
  9018. minimum: minimum,
  9019. maximum: maximum
  9020. };
  9021. };
  9022. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  9023. if (bias === void 0) { bias = null; }
  9024. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  9025. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  9026. if (!stride) {
  9027. stride = 3;
  9028. }
  9029. for (var index = start; index < start + count; index++) {
  9030. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  9031. minimum = BABYLON.Vector3.Minimize(current, minimum);
  9032. maximum = BABYLON.Vector3.Maximize(current, maximum);
  9033. }
  9034. if (bias) {
  9035. minimum.x -= minimum.x * bias.x + bias.y;
  9036. minimum.y -= minimum.y * bias.x + bias.y;
  9037. minimum.z -= minimum.z * bias.x + bias.y;
  9038. maximum.x += maximum.x * bias.x + bias.y;
  9039. maximum.y += maximum.y * bias.x + bias.y;
  9040. maximum.z += maximum.z * bias.x + bias.y;
  9041. }
  9042. return {
  9043. minimum: minimum,
  9044. maximum: maximum
  9045. };
  9046. };
  9047. Tools.Vector2ArrayFeeder = function (array) {
  9048. return function (index) {
  9049. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  9050. var length = isFloatArray ? array.length / 2 : array.length;
  9051. if (index >= length) {
  9052. return null;
  9053. }
  9054. if (isFloatArray) {
  9055. var fa = array;
  9056. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  9057. }
  9058. var a = array;
  9059. return a[index];
  9060. };
  9061. };
  9062. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  9063. if (bias === void 0) { bias = null; }
  9064. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  9065. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  9066. var i = 0;
  9067. var cur = feeder(i++);
  9068. while (cur) {
  9069. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  9070. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  9071. cur = feeder(i++);
  9072. }
  9073. if (bias) {
  9074. minimum.x -= minimum.x * bias.x + bias.y;
  9075. minimum.y -= minimum.y * bias.x + bias.y;
  9076. maximum.x += maximum.x * bias.x + bias.y;
  9077. maximum.y += maximum.y * bias.x + bias.y;
  9078. }
  9079. return {
  9080. minimum: minimum,
  9081. maximum: maximum
  9082. };
  9083. };
  9084. Tools.MakeArray = function (obj, allowsNullUndefined) {
  9085. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  9086. return null;
  9087. return Array.isArray(obj) ? obj : [obj];
  9088. };
  9089. // Misc.
  9090. Tools.GetPointerPrefix = function () {
  9091. var eventPrefix = "pointer";
  9092. // Check if pointer events are supported
  9093. if (Tools.IsWindowObjectExist() && !window.PointerEvent && !navigator.pointerEnabled) {
  9094. eventPrefix = "mouse";
  9095. }
  9096. return eventPrefix;
  9097. };
  9098. /**
  9099. * @param func - the function to be called
  9100. * @param requester - the object that will request the next frame. Falls back to window.
  9101. */
  9102. Tools.QueueNewFrame = function (func, requester) {
  9103. if (!Tools.IsWindowObjectExist()) {
  9104. return setTimeout(func, 16);
  9105. }
  9106. if (!requester) {
  9107. requester = window;
  9108. }
  9109. if (requester.requestAnimationFrame) {
  9110. return requester.requestAnimationFrame(func);
  9111. }
  9112. else if (requester.msRequestAnimationFrame) {
  9113. return requester.msRequestAnimationFrame(func);
  9114. }
  9115. else if (requester.webkitRequestAnimationFrame) {
  9116. return requester.webkitRequestAnimationFrame(func);
  9117. }
  9118. else if (requester.mozRequestAnimationFrame) {
  9119. return requester.mozRequestAnimationFrame(func);
  9120. }
  9121. else if (requester.oRequestAnimationFrame) {
  9122. return requester.oRequestAnimationFrame(func);
  9123. }
  9124. else {
  9125. return window.setTimeout(func, 16);
  9126. }
  9127. };
  9128. Tools.RequestFullscreen = function (element) {
  9129. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  9130. if (!requestFunction)
  9131. return;
  9132. requestFunction.call(element);
  9133. };
  9134. Tools.ExitFullscreen = function () {
  9135. if (document.exitFullscreen) {
  9136. document.exitFullscreen();
  9137. }
  9138. else if (document.mozCancelFullScreen) {
  9139. document.mozCancelFullScreen();
  9140. }
  9141. else if (document.webkitCancelFullScreen) {
  9142. document.webkitCancelFullScreen();
  9143. }
  9144. else if (document.msCancelFullScreen) {
  9145. document.msCancelFullScreen();
  9146. }
  9147. };
  9148. /**
  9149. * Sets the cors behavior on a dom element. This will add the required Tools.CorsBehavior to the element.
  9150. * @param url define the url we are trying
  9151. * @param element define the dom element where to configure the cors policy
  9152. */
  9153. Tools.SetCorsBehavior = function (url, element) {
  9154. if (url && url.indexOf("data:") === 0) {
  9155. return;
  9156. }
  9157. if (Tools.CorsBehavior) {
  9158. if (typeof (Tools.CorsBehavior) === 'string' || Tools.CorsBehavior instanceof String) {
  9159. element.crossOrigin = Tools.CorsBehavior;
  9160. }
  9161. else {
  9162. var result = Tools.CorsBehavior(url);
  9163. if (result) {
  9164. element.crossOrigin = result;
  9165. }
  9166. }
  9167. }
  9168. };
  9169. // External files
  9170. Tools.CleanUrl = function (url) {
  9171. url = url.replace(/#/mg, "%23");
  9172. return url;
  9173. };
  9174. /**
  9175. * Loads an image as an HTMLImageElement.
  9176. * @param input url string, ArrayBuffer, or Blob to load
  9177. * @param onLoad callback called when the image successfully loads
  9178. * @param onError callback called when the image fails to load
  9179. * @param database database for caching
  9180. * @returns the HTMLImageElement of the loaded image
  9181. */
  9182. Tools.LoadImage = function (input, onLoad, onError, database) {
  9183. var url;
  9184. var usingObjectURL = false;
  9185. if (input instanceof ArrayBuffer) {
  9186. url = URL.createObjectURL(new Blob([input]));
  9187. usingObjectURL = true;
  9188. }
  9189. else if (input instanceof Blob) {
  9190. url = URL.createObjectURL(input);
  9191. usingObjectURL = true;
  9192. }
  9193. else {
  9194. url = Tools.CleanUrl(input);
  9195. url = Tools.PreprocessUrl(input);
  9196. }
  9197. var img = new Image();
  9198. Tools.SetCorsBehavior(url, img);
  9199. var loadHandler = function () {
  9200. if (usingObjectURL && img.src) {
  9201. URL.revokeObjectURL(img.src);
  9202. }
  9203. img.removeEventListener("load", loadHandler);
  9204. img.removeEventListener("error", errorHandler);
  9205. onLoad(img);
  9206. };
  9207. var errorHandler = function (err) {
  9208. if (usingObjectURL && img.src) {
  9209. URL.revokeObjectURL(img.src);
  9210. }
  9211. img.removeEventListener("load", loadHandler);
  9212. img.removeEventListener("error", errorHandler);
  9213. Tools.Error("Error while trying to load image: " + input);
  9214. if (onError) {
  9215. onError("Error while trying to load image: " + input, err);
  9216. }
  9217. };
  9218. img.addEventListener("load", loadHandler);
  9219. img.addEventListener("error", errorHandler);
  9220. var noIndexedDB = function () {
  9221. img.src = url;
  9222. };
  9223. var loadFromIndexedDB = function () {
  9224. if (database) {
  9225. database.loadImageFromDB(url, img);
  9226. }
  9227. };
  9228. //ANY database to do!
  9229. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  9230. database.openAsync(loadFromIndexedDB, noIndexedDB);
  9231. }
  9232. else {
  9233. if (url.indexOf("file:") !== -1) {
  9234. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  9235. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  9236. try {
  9237. var blobURL;
  9238. try {
  9239. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  9240. }
  9241. catch (ex) {
  9242. // Chrome doesn't support oneTimeOnly parameter
  9243. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  9244. }
  9245. img.src = blobURL;
  9246. usingObjectURL = true;
  9247. }
  9248. catch (e) {
  9249. img.src = "";
  9250. }
  9251. return img;
  9252. }
  9253. }
  9254. noIndexedDB();
  9255. }
  9256. return img;
  9257. };
  9258. Tools.LoadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  9259. url = Tools.CleanUrl(url);
  9260. url = Tools.PreprocessUrl(url);
  9261. // If file and file input are set
  9262. if (url.indexOf("file:") !== -1) {
  9263. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  9264. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  9265. return Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], onSuccess, onProgress, useArrayBuffer);
  9266. }
  9267. }
  9268. var loadUrl = Tools.BaseUrl + url;
  9269. var aborted = false;
  9270. var fileRequest = {
  9271. onCompleteObservable: new BABYLON.Observable(),
  9272. abort: function () { return aborted = true; },
  9273. };
  9274. var requestFile = function () {
  9275. var request = new XMLHttpRequest();
  9276. var retryHandle = null;
  9277. fileRequest.abort = function () {
  9278. aborted = true;
  9279. if (request.readyState !== (XMLHttpRequest.DONE || 4)) {
  9280. request.abort();
  9281. }
  9282. if (retryHandle !== null) {
  9283. clearTimeout(retryHandle);
  9284. retryHandle = null;
  9285. }
  9286. };
  9287. var retryLoop = function (retryIndex) {
  9288. request.open('GET', loadUrl, true);
  9289. if (useArrayBuffer) {
  9290. request.responseType = "arraybuffer";
  9291. }
  9292. if (onProgress) {
  9293. request.addEventListener("progress", onProgress);
  9294. }
  9295. var onLoadEnd = function () {
  9296. request.removeEventListener("loadend", onLoadEnd);
  9297. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  9298. fileRequest.onCompleteObservable.clear();
  9299. };
  9300. request.addEventListener("loadend", onLoadEnd);
  9301. var onReadyStateChange = function () {
  9302. if (aborted) {
  9303. return;
  9304. }
  9305. // In case of undefined state in some browsers.
  9306. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  9307. // Some browsers have issues where onreadystatechange can be called multiple times with the same value.
  9308. request.removeEventListener("readystatechange", onReadyStateChange);
  9309. if ((request.status >= 200 && request.status < 300) || (request.status === 0 && (!Tools.IsWindowObjectExist() || Tools.IsFileURL()))) {
  9310. onSuccess(!useArrayBuffer ? request.responseText : request.response, request.responseURL);
  9311. return;
  9312. }
  9313. var retryStrategy = Tools.DefaultRetryStrategy;
  9314. if (retryStrategy) {
  9315. var waitTime = retryStrategy(loadUrl, request, retryIndex);
  9316. if (waitTime !== -1) {
  9317. // Prevent the request from completing for retry.
  9318. request.removeEventListener("loadend", onLoadEnd);
  9319. request = new XMLHttpRequest();
  9320. retryHandle = setTimeout(function () { return retryLoop(retryIndex + 1); }, waitTime);
  9321. return;
  9322. }
  9323. }
  9324. var e = new LoadFileError("Error status: " + request.status + " " + request.statusText + " - Unable to load " + loadUrl, request);
  9325. if (onError) {
  9326. onError(request, e);
  9327. }
  9328. else {
  9329. throw e;
  9330. }
  9331. }
  9332. };
  9333. request.addEventListener("readystatechange", onReadyStateChange);
  9334. request.send();
  9335. };
  9336. retryLoop(0);
  9337. };
  9338. // Caching all files
  9339. if (database && database.enableSceneOffline) {
  9340. var noIndexedDB_1 = function (request) {
  9341. if (request && request.status > 400) {
  9342. if (onError) {
  9343. onError(request);
  9344. }
  9345. }
  9346. else {
  9347. if (!aborted) {
  9348. requestFile();
  9349. }
  9350. }
  9351. };
  9352. var loadFromIndexedDB = function () {
  9353. // TODO: database needs to support aborting and should return a IFileRequest
  9354. if (aborted) {
  9355. return;
  9356. }
  9357. if (database) {
  9358. database.loadFileFromDB(url, function (data) {
  9359. if (!aborted) {
  9360. onSuccess(data);
  9361. }
  9362. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  9363. }, onProgress ? function (event) {
  9364. if (!aborted) {
  9365. onProgress(event);
  9366. }
  9367. } : undefined, noIndexedDB_1, useArrayBuffer);
  9368. }
  9369. };
  9370. database.openAsync(loadFromIndexedDB, noIndexedDB_1);
  9371. }
  9372. else {
  9373. requestFile();
  9374. }
  9375. return fileRequest;
  9376. };
  9377. /**
  9378. * Load a script (identified by an url). When the url returns, the
  9379. * content of this file is added into a new script element, attached to the DOM (body element)
  9380. */
  9381. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  9382. if (!Tools.IsWindowObjectExist()) {
  9383. return;
  9384. }
  9385. var head = document.getElementsByTagName('head')[0];
  9386. var script = document.createElement('script');
  9387. script.type = 'text/javascript';
  9388. script.src = scriptUrl;
  9389. script.onload = function () {
  9390. if (onSuccess) {
  9391. onSuccess();
  9392. }
  9393. };
  9394. script.onerror = function (e) {
  9395. if (onError) {
  9396. onError("Unable to load script '" + scriptUrl + "'", e);
  9397. }
  9398. };
  9399. head.appendChild(script);
  9400. };
  9401. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  9402. var reader = new FileReader();
  9403. var request = {
  9404. onCompleteObservable: new BABYLON.Observable(),
  9405. abort: function () { return reader.abort(); },
  9406. };
  9407. reader.onloadend = function (e) {
  9408. request.onCompleteObservable.notifyObservers(request);
  9409. };
  9410. reader.onload = function (e) {
  9411. //target doesn't have result from ts 1.3
  9412. callback(e.target['result']);
  9413. };
  9414. reader.onprogress = progressCallback;
  9415. reader.readAsDataURL(fileToLoad);
  9416. return request;
  9417. };
  9418. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  9419. var reader = new FileReader();
  9420. var request = {
  9421. onCompleteObservable: new BABYLON.Observable(),
  9422. abort: function () { return reader.abort(); },
  9423. };
  9424. reader.onloadend = function (e) { return request.onCompleteObservable.notifyObservers(request); };
  9425. reader.onerror = function (e) {
  9426. Tools.Log("Error while reading file: " + fileToLoad.name);
  9427. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  9428. };
  9429. reader.onload = function (e) {
  9430. //target doesn't have result from ts 1.3
  9431. callback(e.target['result']);
  9432. };
  9433. if (progressCallBack) {
  9434. reader.onprogress = progressCallBack;
  9435. }
  9436. if (!useArrayBuffer) {
  9437. // Asynchronous read
  9438. reader.readAsText(fileToLoad);
  9439. }
  9440. else {
  9441. reader.readAsArrayBuffer(fileToLoad);
  9442. }
  9443. return request;
  9444. };
  9445. //returns a downloadable url to a file content.
  9446. Tools.FileAsURL = function (content) {
  9447. var fileBlob = new Blob([content]);
  9448. var url = window.URL || window.webkitURL;
  9449. var link = url.createObjectURL(fileBlob);
  9450. return link;
  9451. };
  9452. // Misc.
  9453. Tools.Format = function (value, decimals) {
  9454. if (decimals === void 0) { decimals = 2; }
  9455. return value.toFixed(decimals);
  9456. };
  9457. Tools.CheckExtends = function (v, min, max) {
  9458. if (v.x < min.x)
  9459. min.x = v.x;
  9460. if (v.y < min.y)
  9461. min.y = v.y;
  9462. if (v.z < min.z)
  9463. min.z = v.z;
  9464. if (v.x > max.x)
  9465. max.x = v.x;
  9466. if (v.y > max.y)
  9467. max.y = v.y;
  9468. if (v.z > max.z)
  9469. max.z = v.z;
  9470. };
  9471. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  9472. for (var prop in source) {
  9473. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  9474. continue;
  9475. }
  9476. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  9477. continue;
  9478. }
  9479. var sourceValue = source[prop];
  9480. var typeOfSourceValue = typeof sourceValue;
  9481. if (typeOfSourceValue === "function") {
  9482. continue;
  9483. }
  9484. try {
  9485. if (typeOfSourceValue === "object") {
  9486. if (sourceValue instanceof Array) {
  9487. destination[prop] = [];
  9488. if (sourceValue.length > 0) {
  9489. if (typeof sourceValue[0] == "object") {
  9490. for (var index = 0; index < sourceValue.length; index++) {
  9491. var clonedValue = cloneValue(sourceValue[index], destination);
  9492. if (destination[prop].indexOf(clonedValue) === -1) { // Test if auto inject was not done
  9493. destination[prop].push(clonedValue);
  9494. }
  9495. }
  9496. }
  9497. else {
  9498. destination[prop] = sourceValue.slice(0);
  9499. }
  9500. }
  9501. }
  9502. else {
  9503. destination[prop] = cloneValue(sourceValue, destination);
  9504. }
  9505. }
  9506. else {
  9507. destination[prop] = sourceValue;
  9508. }
  9509. }
  9510. catch (e) {
  9511. // Just ignore error (it could be because of a read-only property)
  9512. }
  9513. }
  9514. };
  9515. Tools.IsEmpty = function (obj) {
  9516. for (var i in obj) {
  9517. if (obj.hasOwnProperty(i)) {
  9518. return false;
  9519. }
  9520. }
  9521. return true;
  9522. };
  9523. Tools.RegisterTopRootEvents = function (events) {
  9524. for (var index = 0; index < events.length; index++) {
  9525. var event = events[index];
  9526. window.addEventListener(event.name, event.handler, false);
  9527. try {
  9528. if (window.parent) {
  9529. window.parent.addEventListener(event.name, event.handler, false);
  9530. }
  9531. }
  9532. catch (e) {
  9533. // Silently fails...
  9534. }
  9535. }
  9536. };
  9537. Tools.UnregisterTopRootEvents = function (events) {
  9538. for (var index = 0; index < events.length; index++) {
  9539. var event = events[index];
  9540. window.removeEventListener(event.name, event.handler);
  9541. try {
  9542. if (window.parent) {
  9543. window.parent.removeEventListener(event.name, event.handler);
  9544. }
  9545. }
  9546. catch (e) {
  9547. // Silently fails...
  9548. }
  9549. }
  9550. };
  9551. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType, fileName) {
  9552. if (mimeType === void 0) { mimeType = "image/png"; }
  9553. // Read the contents of the framebuffer
  9554. var numberOfChannelsByLine = width * 4;
  9555. var halfHeight = height / 2;
  9556. //Reading datas from WebGL
  9557. var data = engine.readPixels(0, 0, width, height);
  9558. //To flip image on Y axis.
  9559. for (var i = 0; i < halfHeight; i++) {
  9560. for (var j = 0; j < numberOfChannelsByLine; j++) {
  9561. var currentCell = j + i * numberOfChannelsByLine;
  9562. var targetLine = height - i - 1;
  9563. var targetCell = j + targetLine * numberOfChannelsByLine;
  9564. var temp = data[currentCell];
  9565. data[currentCell] = data[targetCell];
  9566. data[targetCell] = temp;
  9567. }
  9568. }
  9569. // Create a 2D canvas to store the result
  9570. if (!screenshotCanvas) {
  9571. screenshotCanvas = document.createElement('canvas');
  9572. }
  9573. screenshotCanvas.width = width;
  9574. screenshotCanvas.height = height;
  9575. var context = screenshotCanvas.getContext('2d');
  9576. if (context) {
  9577. // Copy the pixels to a 2D canvas
  9578. var imageData = context.createImageData(width, height);
  9579. var castData = (imageData.data);
  9580. castData.set(data);
  9581. context.putImageData(imageData, 0, 0);
  9582. Tools.EncodeScreenshotCanvasData(successCallback, mimeType, fileName);
  9583. }
  9584. };
  9585. /**
  9586. * Converts the canvas data to blob.
  9587. * This acts as a polyfill for browsers not supporting the to blob function.
  9588. * @param canvas Defines the canvas to extract the data from
  9589. * @param successCallback Defines the callback triggered once the data are available
  9590. * @param mimeType Defines the mime type of the result
  9591. */
  9592. Tools.ToBlob = function (canvas, successCallback, mimeType) {
  9593. if (mimeType === void 0) { mimeType = "image/png"; }
  9594. // We need HTMLCanvasElement.toBlob for HD screenshots
  9595. if (!canvas.toBlob) {
  9596. // low performance polyfill based on toDataURL (https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob)
  9597. canvas.toBlob = function (callback, type, quality) {
  9598. var _this = this;
  9599. setTimeout(function () {
  9600. var binStr = atob(_this.toDataURL(type, quality).split(',')[1]), len = binStr.length, arr = new Uint8Array(len);
  9601. for (var i = 0; i < len; i++) {
  9602. arr[i] = binStr.charCodeAt(i);
  9603. }
  9604. callback(new Blob([arr]));
  9605. });
  9606. };
  9607. }
  9608. canvas.toBlob(function (blob) {
  9609. successCallback(blob);
  9610. }, mimeType);
  9611. };
  9612. /**
  9613. * Encodes the canvas data to base 64 or automatically download the result if filename is defined
  9614. * @param successCallback Defines the callback triggered once the data are available
  9615. * @param mimeType Defines the mime type of the result
  9616. * @param fileName The filename to download. If present, the result will automatically be downloaded
  9617. */
  9618. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType, fileName) {
  9619. if (mimeType === void 0) { mimeType = "image/png"; }
  9620. if (successCallback) {
  9621. var base64Image = screenshotCanvas.toDataURL(mimeType);
  9622. successCallback(base64Image);
  9623. }
  9624. else {
  9625. this.ToBlob(screenshotCanvas, function (blob) {
  9626. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  9627. if (("download" in document.createElement("a"))) {
  9628. if (!fileName) {
  9629. var date = new Date();
  9630. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  9631. fileName = "screenshot_" + stringDate + ".png";
  9632. }
  9633. Tools.Download(blob, fileName);
  9634. }
  9635. else {
  9636. var url = URL.createObjectURL(blob);
  9637. var newWindow = window.open("");
  9638. if (!newWindow)
  9639. return;
  9640. var img = newWindow.document.createElement("img");
  9641. img.onload = function () {
  9642. // no longer need to read the blob so it's revoked
  9643. URL.revokeObjectURL(url);
  9644. };
  9645. img.src = url;
  9646. newWindow.document.body.appendChild(img);
  9647. }
  9648. }, mimeType);
  9649. }
  9650. };
  9651. /**
  9652. * Downloads a blob in the browser
  9653. * @param blob defines the blob to download
  9654. * @param fileName defines the name of the downloaded file
  9655. */
  9656. Tools.Download = function (blob, fileName) {
  9657. if (navigator && navigator.msSaveBlob) {
  9658. navigator.msSaveBlob(blob, fileName);
  9659. return;
  9660. }
  9661. var url = window.URL.createObjectURL(blob);
  9662. var a = document.createElement("a");
  9663. document.body.appendChild(a);
  9664. a.style.display = "none";
  9665. a.href = url;
  9666. a.download = fileName;
  9667. a.addEventListener("click", function () {
  9668. if (a.parentElement) {
  9669. a.parentElement.removeChild(a);
  9670. }
  9671. });
  9672. a.click();
  9673. window.URL.revokeObjectURL(url);
  9674. };
  9675. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  9676. if (mimeType === void 0) { mimeType = "image/png"; }
  9677. var width;
  9678. var height;
  9679. // If a precision value is specified
  9680. if (size.precision) {
  9681. width = Math.round(engine.getRenderWidth() * size.precision);
  9682. height = Math.round(width / engine.getAspectRatio(camera));
  9683. }
  9684. else if (size.width && size.height) {
  9685. width = size.width;
  9686. height = size.height;
  9687. }
  9688. //If passing only width, computing height to keep display canvas ratio.
  9689. else if (size.width && !size.height) {
  9690. width = size.width;
  9691. height = Math.round(width / engine.getAspectRatio(camera));
  9692. }
  9693. //If passing only height, computing width to keep display canvas ratio.
  9694. else if (size.height && !size.width) {
  9695. height = size.height;
  9696. width = Math.round(height * engine.getAspectRatio(camera));
  9697. }
  9698. //Assuming here that "size" parameter is a number
  9699. else if (!isNaN(size)) {
  9700. height = size;
  9701. width = size;
  9702. }
  9703. else {
  9704. Tools.Error("Invalid 'size' parameter !");
  9705. return;
  9706. }
  9707. if (!screenshotCanvas) {
  9708. screenshotCanvas = document.createElement('canvas');
  9709. }
  9710. screenshotCanvas.width = width;
  9711. screenshotCanvas.height = height;
  9712. var renderContext = screenshotCanvas.getContext("2d");
  9713. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  9714. var newWidth = width;
  9715. var newHeight = newWidth / ratio;
  9716. if (newHeight > height) {
  9717. newHeight = height;
  9718. newWidth = newHeight * ratio;
  9719. }
  9720. var offsetX = Math.max(0, width - newWidth) / 2;
  9721. var offsetY = Math.max(0, height - newHeight) / 2;
  9722. var renderingCanvas = engine.getRenderingCanvas();
  9723. if (renderContext && renderingCanvas) {
  9724. renderContext.drawImage(renderingCanvas, offsetX, offsetY, newWidth, newHeight);
  9725. }
  9726. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  9727. };
  9728. /**
  9729. * Generates an image screenshot from the specified camera.
  9730. *
  9731. * @param engine The engine to use for rendering
  9732. * @param camera The camera to use for rendering
  9733. * @param size This parameter can be set to a single number or to an object with the
  9734. * following (optional) properties: precision, width, height. If a single number is passed,
  9735. * it will be used for both width and height. If an object is passed, the screenshot size
  9736. * will be derived from the parameters. The precision property is a multiplier allowing
  9737. * rendering at a higher or lower resolution.
  9738. * @param successCallback The callback receives a single parameter which contains the
  9739. * screenshot as a string of base64-encoded characters. This string can be assigned to the
  9740. * src parameter of an <img> to display it.
  9741. * @param mimeType The MIME type of the screenshot image (default: image/png).
  9742. * Check your browser for supported MIME types.
  9743. * @param samples Texture samples (default: 1)
  9744. * @param antialiasing Whether antialiasing should be turned on or not (default: false)
  9745. * @param fileName A name for for the downloaded file.
  9746. * @constructor
  9747. */
  9748. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples, antialiasing, fileName) {
  9749. if (mimeType === void 0) { mimeType = "image/png"; }
  9750. if (samples === void 0) { samples = 1; }
  9751. if (antialiasing === void 0) { antialiasing = false; }
  9752. var width;
  9753. var height;
  9754. //If a precision value is specified
  9755. if (size.precision) {
  9756. width = Math.round(engine.getRenderWidth() * size.precision);
  9757. height = Math.round(width / engine.getAspectRatio(camera));
  9758. size = { width: width, height: height };
  9759. }
  9760. else if (size.width && size.height) {
  9761. width = size.width;
  9762. height = size.height;
  9763. }
  9764. //If passing only width, computing height to keep display canvas ratio.
  9765. else if (size.width && !size.height) {
  9766. width = size.width;
  9767. height = Math.round(width / engine.getAspectRatio(camera));
  9768. size = { width: width, height: height };
  9769. }
  9770. //If passing only height, computing width to keep display canvas ratio.
  9771. else if (size.height && !size.width) {
  9772. height = size.height;
  9773. width = Math.round(height * engine.getAspectRatio(camera));
  9774. size = { width: width, height: height };
  9775. }
  9776. //Assuming here that "size" parameter is a number
  9777. else if (!isNaN(size)) {
  9778. height = size;
  9779. width = size;
  9780. }
  9781. else {
  9782. Tools.Error("Invalid 'size' parameter !");
  9783. return;
  9784. }
  9785. var scene = camera.getScene();
  9786. var previousCamera = null;
  9787. if (scene.activeCamera !== camera) {
  9788. previousCamera = scene.activeCamera;
  9789. scene.activeCamera = camera;
  9790. }
  9791. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  9792. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  9793. texture.renderList = null;
  9794. texture.samples = samples;
  9795. if (antialiasing) {
  9796. texture.addPostProcess(new BABYLON.FxaaPostProcess('antialiasing', 1.0, scene.activeCamera));
  9797. }
  9798. texture.onAfterRenderObservable.add(function () {
  9799. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType, fileName);
  9800. });
  9801. scene.incrementRenderId();
  9802. scene.resetCachedMaterial();
  9803. texture.render(true);
  9804. texture.dispose();
  9805. if (previousCamera) {
  9806. scene.activeCamera = previousCamera;
  9807. }
  9808. camera.getProjectionMatrix(true); // Force cache refresh;
  9809. };
  9810. // XHR response validator for local file scenario
  9811. Tools.ValidateXHRData = function (xhr, dataType) {
  9812. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  9813. if (dataType === void 0) { dataType = 7; }
  9814. try {
  9815. if (dataType & 1) {
  9816. if (xhr.responseText && xhr.responseText.length > 0) {
  9817. return true;
  9818. }
  9819. else if (dataType === 1) {
  9820. return false;
  9821. }
  9822. }
  9823. if (dataType & 2) {
  9824. // Check header width and height since there is no "TGA" magic number
  9825. var tgaHeader = BABYLON.TGATools.GetTGAHeader(xhr.response);
  9826. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  9827. return true;
  9828. }
  9829. else if (dataType === 2) {
  9830. return false;
  9831. }
  9832. }
  9833. if (dataType & 4) {
  9834. // Check for the "DDS" magic number
  9835. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  9836. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  9837. return true;
  9838. }
  9839. else {
  9840. return false;
  9841. }
  9842. }
  9843. }
  9844. catch (e) {
  9845. // Global protection
  9846. }
  9847. return false;
  9848. };
  9849. /**
  9850. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  9851. * Be aware Math.random() could cause collisions, but:
  9852. * "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"
  9853. */
  9854. Tools.RandomId = function () {
  9855. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  9856. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  9857. return v.toString(16);
  9858. });
  9859. };
  9860. /**
  9861. * Test if the given uri is a base64 string.
  9862. * @param uri The uri to test
  9863. * @return True if the uri is a base64 string or false otherwise.
  9864. */
  9865. Tools.IsBase64 = function (uri) {
  9866. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  9867. };
  9868. /**
  9869. * Decode the given base64 uri.
  9870. * @param uri The uri to decode
  9871. * @return The decoded base64 data.
  9872. */
  9873. Tools.DecodeBase64 = function (uri) {
  9874. var decodedString = atob(uri.split(",")[1]);
  9875. var bufferLength = decodedString.length;
  9876. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  9877. for (var i = 0; i < bufferLength; i++) {
  9878. bufferView[i] = decodedString.charCodeAt(i);
  9879. }
  9880. return bufferView.buffer;
  9881. };
  9882. Object.defineProperty(Tools, "NoneLogLevel", {
  9883. get: function () {
  9884. return Tools._NoneLogLevel;
  9885. },
  9886. enumerable: true,
  9887. configurable: true
  9888. });
  9889. Object.defineProperty(Tools, "MessageLogLevel", {
  9890. get: function () {
  9891. return Tools._MessageLogLevel;
  9892. },
  9893. enumerable: true,
  9894. configurable: true
  9895. });
  9896. Object.defineProperty(Tools, "WarningLogLevel", {
  9897. get: function () {
  9898. return Tools._WarningLogLevel;
  9899. },
  9900. enumerable: true,
  9901. configurable: true
  9902. });
  9903. Object.defineProperty(Tools, "ErrorLogLevel", {
  9904. get: function () {
  9905. return Tools._ErrorLogLevel;
  9906. },
  9907. enumerable: true,
  9908. configurable: true
  9909. });
  9910. Object.defineProperty(Tools, "AllLogLevel", {
  9911. get: function () {
  9912. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  9913. },
  9914. enumerable: true,
  9915. configurable: true
  9916. });
  9917. Tools._AddLogEntry = function (entry) {
  9918. Tools._LogCache = entry + Tools._LogCache;
  9919. if (Tools.OnNewCacheEntry) {
  9920. Tools.OnNewCacheEntry(entry);
  9921. }
  9922. };
  9923. Tools._FormatMessage = function (message) {
  9924. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  9925. var date = new Date();
  9926. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  9927. };
  9928. Tools._LogDisabled = function (message) {
  9929. // nothing to do
  9930. };
  9931. Tools._LogEnabled = function (message) {
  9932. var formattedMessage = Tools._FormatMessage(message);
  9933. console.log("BJS - " + formattedMessage);
  9934. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  9935. Tools._AddLogEntry(entry);
  9936. };
  9937. Tools._WarnDisabled = function (message) {
  9938. // nothing to do
  9939. };
  9940. Tools._WarnEnabled = function (message) {
  9941. var formattedMessage = Tools._FormatMessage(message);
  9942. console.warn("BJS - " + formattedMessage);
  9943. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  9944. Tools._AddLogEntry(entry);
  9945. };
  9946. Tools._ErrorDisabled = function (message) {
  9947. // nothing to do
  9948. };
  9949. Tools._ErrorEnabled = function (message) {
  9950. Tools.errorsCount++;
  9951. var formattedMessage = Tools._FormatMessage(message);
  9952. console.error("BJS - " + formattedMessage);
  9953. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  9954. Tools._AddLogEntry(entry);
  9955. };
  9956. Object.defineProperty(Tools, "LogCache", {
  9957. get: function () {
  9958. return Tools._LogCache;
  9959. },
  9960. enumerable: true,
  9961. configurable: true
  9962. });
  9963. Tools.ClearLogCache = function () {
  9964. Tools._LogCache = "";
  9965. Tools.errorsCount = 0;
  9966. };
  9967. Object.defineProperty(Tools, "LogLevels", {
  9968. set: function (level) {
  9969. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  9970. Tools.Log = Tools._LogEnabled;
  9971. }
  9972. else {
  9973. Tools.Log = Tools._LogDisabled;
  9974. }
  9975. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  9976. Tools.Warn = Tools._WarnEnabled;
  9977. }
  9978. else {
  9979. Tools.Warn = Tools._WarnDisabled;
  9980. }
  9981. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  9982. Tools.Error = Tools._ErrorEnabled;
  9983. }
  9984. else {
  9985. Tools.Error = Tools._ErrorDisabled;
  9986. }
  9987. },
  9988. enumerable: true,
  9989. configurable: true
  9990. });
  9991. /**
  9992. * Check if the loaded document was accessed via `file:`-Protocol.
  9993. * @returns boolean
  9994. */
  9995. Tools.IsFileURL = function () {
  9996. return location.protocol === "file:";
  9997. };
  9998. Tools.IsWindowObjectExist = function () {
  9999. return (typeof window) !== "undefined";
  10000. };
  10001. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  10002. get: function () {
  10003. return Tools._PerformanceNoneLogLevel;
  10004. },
  10005. enumerable: true,
  10006. configurable: true
  10007. });
  10008. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  10009. get: function () {
  10010. return Tools._PerformanceUserMarkLogLevel;
  10011. },
  10012. enumerable: true,
  10013. configurable: true
  10014. });
  10015. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  10016. get: function () {
  10017. return Tools._PerformanceConsoleLogLevel;
  10018. },
  10019. enumerable: true,
  10020. configurable: true
  10021. });
  10022. Object.defineProperty(Tools, "PerformanceLogLevel", {
  10023. set: function (level) {
  10024. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  10025. Tools.StartPerformanceCounter = Tools._StartUserMark;
  10026. Tools.EndPerformanceCounter = Tools._EndUserMark;
  10027. return;
  10028. }
  10029. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  10030. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  10031. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  10032. return;
  10033. }
  10034. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  10035. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  10036. },
  10037. enumerable: true,
  10038. configurable: true
  10039. });
  10040. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  10041. };
  10042. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  10043. };
  10044. Tools._StartUserMark = function (counterName, condition) {
  10045. if (condition === void 0) { condition = true; }
  10046. if (!Tools._performance) {
  10047. if (!Tools.IsWindowObjectExist()) {
  10048. return;
  10049. }
  10050. Tools._performance = window.performance;
  10051. }
  10052. if (!condition || !Tools._performance.mark) {
  10053. return;
  10054. }
  10055. Tools._performance.mark(counterName + "-Begin");
  10056. };
  10057. Tools._EndUserMark = function (counterName, condition) {
  10058. if (condition === void 0) { condition = true; }
  10059. if (!condition || !Tools._performance.mark) {
  10060. return;
  10061. }
  10062. Tools._performance.mark(counterName + "-End");
  10063. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  10064. };
  10065. Tools._StartPerformanceConsole = function (counterName, condition) {
  10066. if (condition === void 0) { condition = true; }
  10067. if (!condition) {
  10068. return;
  10069. }
  10070. Tools._StartUserMark(counterName, condition);
  10071. if (console.time) {
  10072. console.time(counterName);
  10073. }
  10074. };
  10075. Tools._EndPerformanceConsole = function (counterName, condition) {
  10076. if (condition === void 0) { condition = true; }
  10077. if (!condition) {
  10078. return;
  10079. }
  10080. Tools._EndUserMark(counterName, condition);
  10081. if (console.time) {
  10082. console.timeEnd(counterName);
  10083. }
  10084. };
  10085. Object.defineProperty(Tools, "Now", {
  10086. get: function () {
  10087. if (Tools.IsWindowObjectExist() && window.performance && window.performance.now) {
  10088. return window.performance.now();
  10089. }
  10090. return Date.now();
  10091. },
  10092. enumerable: true,
  10093. configurable: true
  10094. });
  10095. /**
  10096. * This method will return the name of the class used to create the instance of the given object.
  10097. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  10098. * @param object the object to get the class name from
  10099. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  10100. */
  10101. Tools.GetClassName = function (object, isType) {
  10102. if (isType === void 0) { isType = false; }
  10103. var name = null;
  10104. if (!isType && object.getClassName) {
  10105. name = object.getClassName();
  10106. }
  10107. else {
  10108. if (object instanceof Object) {
  10109. var classObj = isType ? object : Object.getPrototypeOf(object);
  10110. name = classObj.constructor["__bjsclassName__"];
  10111. }
  10112. if (!name) {
  10113. name = typeof object;
  10114. }
  10115. }
  10116. return name;
  10117. };
  10118. Tools.First = function (array, predicate) {
  10119. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  10120. var el = array_1[_i];
  10121. if (predicate(el)) {
  10122. return el;
  10123. }
  10124. }
  10125. return null;
  10126. };
  10127. /**
  10128. * This method will return the name of the full name of the class, including its owning module (if any).
  10129. * 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).
  10130. * @param object the object to get the class name from
  10131. * @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.
  10132. */
  10133. Tools.getFullClassName = function (object, isType) {
  10134. if (isType === void 0) { isType = false; }
  10135. var className = null;
  10136. var moduleName = null;
  10137. if (!isType && object.getClassName) {
  10138. className = object.getClassName();
  10139. }
  10140. else {
  10141. if (object instanceof Object) {
  10142. var classObj = isType ? object : Object.getPrototypeOf(object);
  10143. className = classObj.constructor["__bjsclassName__"];
  10144. moduleName = classObj.constructor["__bjsmoduleName__"];
  10145. }
  10146. if (!className) {
  10147. className = typeof object;
  10148. }
  10149. }
  10150. if (!className) {
  10151. return null;
  10152. }
  10153. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  10154. };
  10155. /**
  10156. * 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.
  10157. * @param array
  10158. */
  10159. Tools.arrayOrStringFeeder = function (array) {
  10160. return function (index) {
  10161. if (index >= array.length) {
  10162. return null;
  10163. }
  10164. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  10165. if (val && val.getHashCode) {
  10166. val = val.getHashCode();
  10167. }
  10168. if (typeof val === "string") {
  10169. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  10170. }
  10171. return val;
  10172. };
  10173. };
  10174. /**
  10175. * Compute the hashCode of a stream of number
  10176. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  10177. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  10178. * @return the hash code computed
  10179. */
  10180. Tools.hashCodeFromStream = function (feeder) {
  10181. // Based from here: http://stackoverflow.com/a/7616484/802124
  10182. var hash = 0;
  10183. var index = 0;
  10184. var chr = feeder(index++);
  10185. while (chr != null) {
  10186. hash = ((hash << 5) - hash) + chr;
  10187. hash |= 0; // Convert to 32bit integer
  10188. chr = feeder(index++);
  10189. }
  10190. return hash;
  10191. };
  10192. /**
  10193. * Returns a promise that resolves after the given amount of time.
  10194. * @param delay Number of milliseconds to delay
  10195. * @returns Promise that resolves after the given amount of time
  10196. */
  10197. Tools.DelayAsync = function (delay) {
  10198. return new Promise(function (resolve) {
  10199. setTimeout(function () {
  10200. resolve();
  10201. }, delay);
  10202. });
  10203. };
  10204. /**
  10205. * Gets the current gradient from an array of IValueGradient
  10206. * @param ratio defines the current ratio to get
  10207. * @param gradients defines the array of IValueGradient
  10208. * @param updateFunc defines the callback function used to get the final value from the selected gradients
  10209. */
  10210. Tools.GetCurrentGradient = function (ratio, gradients, updateFunc) {
  10211. for (var gradientIndex = 0; gradientIndex < gradients.length - 1; gradientIndex++) {
  10212. var currentGradient = gradients[gradientIndex];
  10213. var nextGradient = gradients[gradientIndex + 1];
  10214. if (ratio >= currentGradient.gradient && ratio <= nextGradient.gradient) {
  10215. var scale = (ratio - currentGradient.gradient) / (nextGradient.gradient - currentGradient.gradient);
  10216. updateFunc(currentGradient, nextGradient, scale);
  10217. return;
  10218. }
  10219. }
  10220. // Use last index if over
  10221. var lastIndex = gradients.length - 1;
  10222. updateFunc(gradients[lastIndex], gradients[lastIndex], 1.0);
  10223. };
  10224. Tools.BaseUrl = "";
  10225. Tools.DefaultRetryStrategy = RetryStrategy.ExponentialBackoff();
  10226. /**
  10227. * Default behaviour for cors in the application.
  10228. * It can be a string if the expected behavior is identical in the entire app.
  10229. * Or a callback to be able to set it per url or on a group of them (in case of Video source for instance)
  10230. */
  10231. Tools.CorsBehavior = "anonymous";
  10232. Tools.UseFallbackTexture = true;
  10233. /**
  10234. * Use this object to register external classes like custom textures or material
  10235. * to allow the laoders to instantiate them
  10236. */
  10237. Tools.RegisteredExternalClasses = {};
  10238. // Used in case of a texture loading problem
  10239. 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";
  10240. Tools._tmpFloatArray = new Float32Array(1);
  10241. Tools.PreprocessUrl = function (url) {
  10242. return url;
  10243. };
  10244. // Logs
  10245. Tools._NoneLogLevel = 0;
  10246. Tools._MessageLogLevel = 1;
  10247. Tools._WarningLogLevel = 2;
  10248. Tools._ErrorLogLevel = 4;
  10249. Tools._LogCache = "";
  10250. Tools.errorsCount = 0;
  10251. Tools.Log = Tools._LogEnabled;
  10252. Tools.Warn = Tools._WarnEnabled;
  10253. Tools.Error = Tools._ErrorEnabled;
  10254. // Performances
  10255. Tools._PerformanceNoneLogLevel = 0;
  10256. Tools._PerformanceUserMarkLogLevel = 1;
  10257. Tools._PerformanceConsoleLogLevel = 2;
  10258. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  10259. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  10260. return Tools;
  10261. }());
  10262. BABYLON.Tools = Tools;
  10263. /**
  10264. * This class is used to track a performance counter which is number based.
  10265. * The user has access to many properties which give statistics of different nature
  10266. *
  10267. * The implementer can track two kinds of Performance Counter: time and count
  10268. * 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.
  10269. * 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.
  10270. */
  10271. var PerfCounter = /** @class */ (function () {
  10272. function PerfCounter() {
  10273. this._startMonitoringTime = 0;
  10274. this._min = 0;
  10275. this._max = 0;
  10276. this._average = 0;
  10277. this._lastSecAverage = 0;
  10278. this._current = 0;
  10279. this._totalValueCount = 0;
  10280. this._totalAccumulated = 0;
  10281. this._lastSecAccumulated = 0;
  10282. this._lastSecTime = 0;
  10283. this._lastSecValueCount = 0;
  10284. }
  10285. Object.defineProperty(PerfCounter.prototype, "min", {
  10286. /**
  10287. * Returns the smallest value ever
  10288. */
  10289. get: function () {
  10290. return this._min;
  10291. },
  10292. enumerable: true,
  10293. configurable: true
  10294. });
  10295. Object.defineProperty(PerfCounter.prototype, "max", {
  10296. /**
  10297. * Returns the biggest value ever
  10298. */
  10299. get: function () {
  10300. return this._max;
  10301. },
  10302. enumerable: true,
  10303. configurable: true
  10304. });
  10305. Object.defineProperty(PerfCounter.prototype, "average", {
  10306. /**
  10307. * Returns the average value since the performance counter is running
  10308. */
  10309. get: function () {
  10310. return this._average;
  10311. },
  10312. enumerable: true,
  10313. configurable: true
  10314. });
  10315. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  10316. /**
  10317. * Returns the average value of the last second the counter was monitored
  10318. */
  10319. get: function () {
  10320. return this._lastSecAverage;
  10321. },
  10322. enumerable: true,
  10323. configurable: true
  10324. });
  10325. Object.defineProperty(PerfCounter.prototype, "current", {
  10326. /**
  10327. * Returns the current value
  10328. */
  10329. get: function () {
  10330. return this._current;
  10331. },
  10332. enumerable: true,
  10333. configurable: true
  10334. });
  10335. Object.defineProperty(PerfCounter.prototype, "total", {
  10336. get: function () {
  10337. return this._totalAccumulated;
  10338. },
  10339. enumerable: true,
  10340. configurable: true
  10341. });
  10342. Object.defineProperty(PerfCounter.prototype, "count", {
  10343. get: function () {
  10344. return this._totalValueCount;
  10345. },
  10346. enumerable: true,
  10347. configurable: true
  10348. });
  10349. /**
  10350. * Call this method to start monitoring a new frame.
  10351. * 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.
  10352. */
  10353. PerfCounter.prototype.fetchNewFrame = function () {
  10354. this._totalValueCount++;
  10355. this._current = 0;
  10356. this._lastSecValueCount++;
  10357. };
  10358. /**
  10359. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  10360. * @param newCount the count value to add to the monitored count
  10361. * @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.
  10362. */
  10363. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  10364. if (!PerfCounter.Enabled) {
  10365. return;
  10366. }
  10367. this._current += newCount;
  10368. if (fetchResult) {
  10369. this._fetchResult();
  10370. }
  10371. };
  10372. /**
  10373. * Start monitoring this performance counter
  10374. */
  10375. PerfCounter.prototype.beginMonitoring = function () {
  10376. if (!PerfCounter.Enabled) {
  10377. return;
  10378. }
  10379. this._startMonitoringTime = Tools.Now;
  10380. };
  10381. /**
  10382. * Compute the time lapsed since the previous beginMonitoring() call.
  10383. * @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
  10384. */
  10385. PerfCounter.prototype.endMonitoring = function (newFrame) {
  10386. if (newFrame === void 0) { newFrame = true; }
  10387. if (!PerfCounter.Enabled) {
  10388. return;
  10389. }
  10390. if (newFrame) {
  10391. this.fetchNewFrame();
  10392. }
  10393. var currentTime = Tools.Now;
  10394. this._current = currentTime - this._startMonitoringTime;
  10395. if (newFrame) {
  10396. this._fetchResult();
  10397. }
  10398. };
  10399. PerfCounter.prototype._fetchResult = function () {
  10400. this._totalAccumulated += this._current;
  10401. this._lastSecAccumulated += this._current;
  10402. // Min/Max update
  10403. this._min = Math.min(this._min, this._current);
  10404. this._max = Math.max(this._max, this._current);
  10405. this._average = this._totalAccumulated / this._totalValueCount;
  10406. // Reset last sec?
  10407. var now = Tools.Now;
  10408. if ((now - this._lastSecTime) > 1000) {
  10409. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  10410. this._lastSecTime = now;
  10411. this._lastSecAccumulated = 0;
  10412. this._lastSecValueCount = 0;
  10413. }
  10414. };
  10415. PerfCounter.Enabled = true;
  10416. return PerfCounter;
  10417. }());
  10418. BABYLON.PerfCounter = PerfCounter;
  10419. /**
  10420. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  10421. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  10422. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  10423. * @param name The name of the class, case should be preserved
  10424. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  10425. */
  10426. function className(name, module) {
  10427. return function (target) {
  10428. target["__bjsclassName__"] = name;
  10429. target["__bjsmoduleName__"] = (module != null) ? module : null;
  10430. };
  10431. }
  10432. BABYLON.className = className;
  10433. /**
  10434. * An implementation of a loop for asynchronous functions.
  10435. */
  10436. var AsyncLoop = /** @class */ (function () {
  10437. /**
  10438. * Constructor.
  10439. * @param iterations the number of iterations.
  10440. * @param func the function to run each iteration
  10441. * @param successCallback the callback that will be called upon succesful execution
  10442. * @param offset starting offset.
  10443. */
  10444. function AsyncLoop(
  10445. /**
  10446. * Defines the number of iterations for the loop
  10447. */
  10448. iterations, func, successCallback, offset) {
  10449. if (offset === void 0) { offset = 0; }
  10450. this.iterations = iterations;
  10451. this.index = offset - 1;
  10452. this._done = false;
  10453. this._fn = func;
  10454. this._successCallback = successCallback;
  10455. }
  10456. /**
  10457. * Execute the next iteration. Must be called after the last iteration was finished.
  10458. */
  10459. AsyncLoop.prototype.executeNext = function () {
  10460. if (!this._done) {
  10461. if (this.index + 1 < this.iterations) {
  10462. ++this.index;
  10463. this._fn(this);
  10464. }
  10465. else {
  10466. this.breakLoop();
  10467. }
  10468. }
  10469. };
  10470. /**
  10471. * Break the loop and run the success callback.
  10472. */
  10473. AsyncLoop.prototype.breakLoop = function () {
  10474. this._done = true;
  10475. this._successCallback();
  10476. };
  10477. /**
  10478. * Create and run an async loop.
  10479. * @param iterations the number of iterations.
  10480. * @param fn the function to run each iteration
  10481. * @param successCallback the callback that will be called upon succesful execution
  10482. * @param offset starting offset.
  10483. * @returns the created async loop object
  10484. */
  10485. AsyncLoop.Run = function (iterations, fn, successCallback, offset) {
  10486. if (offset === void 0) { offset = 0; }
  10487. var loop = new AsyncLoop(iterations, fn, successCallback, offset);
  10488. loop.executeNext();
  10489. return loop;
  10490. };
  10491. /**
  10492. * A for-loop that will run a given number of iterations synchronous and the rest async.
  10493. * @param iterations total number of iterations
  10494. * @param syncedIterations number of synchronous iterations in each async iteration.
  10495. * @param fn the function to call each iteration.
  10496. * @param callback a success call back that will be called when iterating stops.
  10497. * @param breakFunction a break condition (optional)
  10498. * @param timeout timeout settings for the setTimeout function. default - 0.
  10499. * @returns the created async loop object
  10500. */
  10501. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  10502. if (timeout === void 0) { timeout = 0; }
  10503. return AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  10504. if (breakFunction && breakFunction())
  10505. loop.breakLoop();
  10506. else {
  10507. setTimeout(function () {
  10508. for (var i = 0; i < syncedIterations; ++i) {
  10509. var iteration = (loop.index * syncedIterations) + i;
  10510. if (iteration >= iterations)
  10511. break;
  10512. fn(iteration);
  10513. if (breakFunction && breakFunction()) {
  10514. loop.breakLoop();
  10515. break;
  10516. }
  10517. }
  10518. loop.executeNext();
  10519. }, timeout);
  10520. }
  10521. }, callback);
  10522. };
  10523. return AsyncLoop;
  10524. }());
  10525. BABYLON.AsyncLoop = AsyncLoop;
  10526. })(BABYLON || (BABYLON = {}));
  10527. //# sourceMappingURL=babylon.tools.js.map
  10528. var BABYLON;
  10529. (function (BABYLON) {
  10530. var PromiseStates;
  10531. (function (PromiseStates) {
  10532. PromiseStates[PromiseStates["Pending"] = 0] = "Pending";
  10533. PromiseStates[PromiseStates["Fulfilled"] = 1] = "Fulfilled";
  10534. PromiseStates[PromiseStates["Rejected"] = 2] = "Rejected";
  10535. })(PromiseStates || (PromiseStates = {}));
  10536. var FulFillmentAgregator = /** @class */ (function () {
  10537. function FulFillmentAgregator() {
  10538. this.count = 0;
  10539. this.target = 0;
  10540. this.results = [];
  10541. }
  10542. return FulFillmentAgregator;
  10543. }());
  10544. var InternalPromise = /** @class */ (function () {
  10545. function InternalPromise(resolver) {
  10546. var _this = this;
  10547. this._state = PromiseStates.Pending;
  10548. this._children = new Array();
  10549. this._rejectWasConsumed = false;
  10550. if (!resolver) {
  10551. return;
  10552. }
  10553. try {
  10554. resolver(function (value) {
  10555. _this._resolve(value);
  10556. }, function (reason) {
  10557. _this._reject(reason);
  10558. });
  10559. }
  10560. catch (e) {
  10561. this._reject(e);
  10562. }
  10563. }
  10564. Object.defineProperty(InternalPromise.prototype, "_result", {
  10565. get: function () {
  10566. return this._resultValue;
  10567. },
  10568. set: function (value) {
  10569. this._resultValue = value;
  10570. if (this._parent && this._parent._result === undefined) {
  10571. this._parent._result = value;
  10572. }
  10573. },
  10574. enumerable: true,
  10575. configurable: true
  10576. });
  10577. InternalPromise.prototype.catch = function (onRejected) {
  10578. return this.then(undefined, onRejected);
  10579. };
  10580. InternalPromise.prototype.then = function (onFulfilled, onRejected) {
  10581. var _this = this;
  10582. var newPromise = new InternalPromise();
  10583. newPromise._onFulfilled = onFulfilled;
  10584. newPromise._onRejected = onRejected;
  10585. // Composition
  10586. this._children.push(newPromise);
  10587. newPromise._parent = this;
  10588. if (this._state !== PromiseStates.Pending) {
  10589. BABYLON.Tools.SetImmediate(function () {
  10590. if (_this._state === PromiseStates.Fulfilled || _this._rejectWasConsumed) {
  10591. var returnedValue = newPromise._resolve(_this._result);
  10592. if (returnedValue !== undefined && returnedValue !== null) {
  10593. if (returnedValue._state !== undefined) {
  10594. var returnedPromise = returnedValue;
  10595. newPromise._children.push(returnedPromise);
  10596. returnedPromise._parent = newPromise;
  10597. newPromise = returnedPromise;
  10598. }
  10599. else {
  10600. newPromise._result = returnedValue;
  10601. }
  10602. }
  10603. }
  10604. else {
  10605. newPromise._reject(_this._reason);
  10606. }
  10607. });
  10608. }
  10609. return newPromise;
  10610. };
  10611. InternalPromise.prototype._moveChildren = function (children) {
  10612. var _this = this;
  10613. var _a;
  10614. (_a = this._children).push.apply(_a, children.splice(0, children.length));
  10615. this._children.forEach(function (child) {
  10616. child._parent = _this;
  10617. });
  10618. if (this._state === PromiseStates.Fulfilled) {
  10619. for (var _i = 0, _b = this._children; _i < _b.length; _i++) {
  10620. var child = _b[_i];
  10621. child._resolve(this._result);
  10622. }
  10623. }
  10624. else if (this._state === PromiseStates.Rejected) {
  10625. for (var _c = 0, _d = this._children; _c < _d.length; _c++) {
  10626. var child = _d[_c];
  10627. child._reject(this._reason);
  10628. }
  10629. }
  10630. };
  10631. InternalPromise.prototype._resolve = function (value) {
  10632. try {
  10633. this._state = PromiseStates.Fulfilled;
  10634. var returnedValue = null;
  10635. if (this._onFulfilled) {
  10636. returnedValue = this._onFulfilled(value);
  10637. }
  10638. if (returnedValue !== undefined && returnedValue !== null) {
  10639. if (returnedValue._state !== undefined) {
  10640. // Transmit children
  10641. var returnedPromise = returnedValue;
  10642. returnedPromise._parent = this;
  10643. returnedPromise._moveChildren(this._children);
  10644. value = returnedPromise._result;
  10645. }
  10646. else {
  10647. value = returnedValue;
  10648. }
  10649. }
  10650. this._result = value;
  10651. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  10652. var child = _a[_i];
  10653. child._resolve(value);
  10654. }
  10655. this._children.length = 0;
  10656. delete this._onFulfilled;
  10657. delete this._onRejected;
  10658. }
  10659. catch (e) {
  10660. this._reject(e, true);
  10661. }
  10662. };
  10663. InternalPromise.prototype._reject = function (reason, onLocalThrow) {
  10664. if (onLocalThrow === void 0) { onLocalThrow = false; }
  10665. this._state = PromiseStates.Rejected;
  10666. this._reason = reason;
  10667. if (this._onRejected && !onLocalThrow) {
  10668. try {
  10669. this._onRejected(reason);
  10670. this._rejectWasConsumed = true;
  10671. }
  10672. catch (e) {
  10673. reason = e;
  10674. }
  10675. }
  10676. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  10677. var child = _a[_i];
  10678. if (this._rejectWasConsumed) {
  10679. child._resolve(null);
  10680. }
  10681. else {
  10682. child._reject(reason);
  10683. }
  10684. }
  10685. this._children.length = 0;
  10686. delete this._onFulfilled;
  10687. delete this._onRejected;
  10688. };
  10689. InternalPromise.resolve = function (value) {
  10690. var newPromise = new InternalPromise();
  10691. newPromise._resolve(value);
  10692. return newPromise;
  10693. };
  10694. InternalPromise._RegisterForFulfillment = function (promise, agregator, index) {
  10695. promise.then(function (value) {
  10696. agregator.results[index] = value;
  10697. agregator.count++;
  10698. if (agregator.count === agregator.target) {
  10699. agregator.rootPromise._resolve(agregator.results);
  10700. }
  10701. return null;
  10702. }, function (reason) {
  10703. if (agregator.rootPromise._state !== PromiseStates.Rejected) {
  10704. agregator.rootPromise._reject(reason);
  10705. }
  10706. });
  10707. };
  10708. InternalPromise.all = function (promises) {
  10709. var newPromise = new InternalPromise();
  10710. var agregator = new FulFillmentAgregator();
  10711. agregator.target = promises.length;
  10712. agregator.rootPromise = newPromise;
  10713. if (promises.length) {
  10714. for (var index = 0; index < promises.length; index++) {
  10715. InternalPromise._RegisterForFulfillment(promises[index], agregator, index);
  10716. }
  10717. }
  10718. else {
  10719. newPromise._resolve([]);
  10720. }
  10721. return newPromise;
  10722. };
  10723. InternalPromise.race = function (promises) {
  10724. var newPromise = new InternalPromise();
  10725. if (promises.length) {
  10726. for (var _i = 0, promises_1 = promises; _i < promises_1.length; _i++) {
  10727. var promise = promises_1[_i];
  10728. promise.then(function (value) {
  10729. if (newPromise) {
  10730. newPromise._resolve(value);
  10731. newPromise = null;
  10732. }
  10733. return null;
  10734. }, function (reason) {
  10735. if (newPromise) {
  10736. newPromise._reject(reason);
  10737. newPromise = null;
  10738. }
  10739. });
  10740. }
  10741. }
  10742. return newPromise;
  10743. };
  10744. return InternalPromise;
  10745. }());
  10746. /**
  10747. * Helper class that provides a small promise polyfill
  10748. */
  10749. var PromisePolyfill = /** @class */ (function () {
  10750. function PromisePolyfill() {
  10751. }
  10752. /**
  10753. * Static function used to check if the polyfill is required
  10754. * If this is the case then the function will inject the polyfill to window.Promise
  10755. * @param force defines a boolean used to force the injection (mostly for testing purposes)
  10756. */
  10757. PromisePolyfill.Apply = function (force) {
  10758. if (force === void 0) { force = false; }
  10759. if (force || typeof Promise === 'undefined') {
  10760. var root = window;
  10761. root.Promise = InternalPromise;
  10762. }
  10763. };
  10764. return PromisePolyfill;
  10765. }());
  10766. BABYLON.PromisePolyfill = PromisePolyfill;
  10767. })(BABYLON || (BABYLON = {}));
  10768. //# sourceMappingURL=babylon.promise.js.map
  10769. /// <reference path="../../../dist/preview release/babylon.d.ts" />
  10770. var BABYLON;
  10771. (function (BABYLON) {
  10772. /**
  10773. * Helper class to push actions to a pool of workers.
  10774. */
  10775. var WorkerPool = /** @class */ (function () {
  10776. /**
  10777. * Constructor
  10778. * @param workers Array of workers to use for actions
  10779. */
  10780. function WorkerPool(workers) {
  10781. this._pendingActions = new Array();
  10782. this._workerInfos = workers.map(function (worker) { return ({
  10783. worker: worker,
  10784. active: false
  10785. }); });
  10786. }
  10787. /**
  10788. * Terminates all workers and clears any pending actions.
  10789. */
  10790. WorkerPool.prototype.dispose = function () {
  10791. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  10792. var workerInfo = _a[_i];
  10793. workerInfo.worker.terminate();
  10794. }
  10795. delete this._workerInfos;
  10796. delete this._pendingActions;
  10797. };
  10798. /**
  10799. * Pushes an action to the worker pool. If all the workers are active, the action will be
  10800. * pended until a worker has completed its action.
  10801. * @param action The action to perform. Call onComplete when the action is complete.
  10802. */
  10803. WorkerPool.prototype.push = function (action) {
  10804. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  10805. var workerInfo = _a[_i];
  10806. if (!workerInfo.active) {
  10807. this._execute(workerInfo, action);
  10808. return;
  10809. }
  10810. }
  10811. this._pendingActions.push(action);
  10812. };
  10813. WorkerPool.prototype._execute = function (workerInfo, action) {
  10814. var _this = this;
  10815. workerInfo.active = true;
  10816. action(workerInfo.worker, function () {
  10817. workerInfo.active = false;
  10818. var nextAction = _this._pendingActions.shift();
  10819. if (nextAction) {
  10820. _this._execute(workerInfo, nextAction);
  10821. }
  10822. });
  10823. };
  10824. return WorkerPool;
  10825. }());
  10826. BABYLON.WorkerPool = WorkerPool;
  10827. })(BABYLON || (BABYLON = {}));
  10828. //# sourceMappingURL=babylon.workerPool.js.map
  10829. var BABYLON;
  10830. (function (BABYLON) {
  10831. /**
  10832. * @hidden
  10833. **/
  10834. var _AlphaState = /** @class */ (function () {
  10835. /**
  10836. * Initializes the state.
  10837. */
  10838. function _AlphaState() {
  10839. this._isAlphaBlendDirty = false;
  10840. this._isBlendFunctionParametersDirty = false;
  10841. this._isBlendEquationParametersDirty = false;
  10842. this._isBlendConstantsDirty = false;
  10843. this._alphaBlend = false;
  10844. this._blendFunctionParameters = new Array(4);
  10845. this._blendEquationParameters = new Array(2);
  10846. this._blendConstants = new Array(4);
  10847. this.reset();
  10848. }
  10849. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  10850. get: function () {
  10851. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  10852. },
  10853. enumerable: true,
  10854. configurable: true
  10855. });
  10856. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  10857. get: function () {
  10858. return this._alphaBlend;
  10859. },
  10860. set: function (value) {
  10861. if (this._alphaBlend === value) {
  10862. return;
  10863. }
  10864. this._alphaBlend = value;
  10865. this._isAlphaBlendDirty = true;
  10866. },
  10867. enumerable: true,
  10868. configurable: true
  10869. });
  10870. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  10871. if (this._blendConstants[0] === r &&
  10872. this._blendConstants[1] === g &&
  10873. this._blendConstants[2] === b &&
  10874. this._blendConstants[3] === a) {
  10875. return;
  10876. }
  10877. this._blendConstants[0] = r;
  10878. this._blendConstants[1] = g;
  10879. this._blendConstants[2] = b;
  10880. this._blendConstants[3] = a;
  10881. this._isBlendConstantsDirty = true;
  10882. };
  10883. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  10884. if (this._blendFunctionParameters[0] === value0 &&
  10885. this._blendFunctionParameters[1] === value1 &&
  10886. this._blendFunctionParameters[2] === value2 &&
  10887. this._blendFunctionParameters[3] === value3) {
  10888. return;
  10889. }
  10890. this._blendFunctionParameters[0] = value0;
  10891. this._blendFunctionParameters[1] = value1;
  10892. this._blendFunctionParameters[2] = value2;
  10893. this._blendFunctionParameters[3] = value3;
  10894. this._isBlendFunctionParametersDirty = true;
  10895. };
  10896. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  10897. if (this._blendEquationParameters[0] === rgb &&
  10898. this._blendEquationParameters[1] === alpha) {
  10899. return;
  10900. }
  10901. this._blendEquationParameters[0] = rgb;
  10902. this._blendEquationParameters[1] = alpha;
  10903. this._isBlendEquationParametersDirty = true;
  10904. };
  10905. _AlphaState.prototype.reset = function () {
  10906. this._alphaBlend = false;
  10907. this._blendFunctionParameters[0] = null;
  10908. this._blendFunctionParameters[1] = null;
  10909. this._blendFunctionParameters[2] = null;
  10910. this._blendFunctionParameters[3] = null;
  10911. this._blendEquationParameters[0] = null;
  10912. this._blendEquationParameters[1] = null;
  10913. this._blendConstants[0] = null;
  10914. this._blendConstants[1] = null;
  10915. this._blendConstants[2] = null;
  10916. this._blendConstants[3] = null;
  10917. this._isAlphaBlendDirty = true;
  10918. this._isBlendFunctionParametersDirty = false;
  10919. this._isBlendEquationParametersDirty = false;
  10920. this._isBlendConstantsDirty = false;
  10921. };
  10922. _AlphaState.prototype.apply = function (gl) {
  10923. if (!this.isDirty) {
  10924. return;
  10925. }
  10926. // Alpha blend
  10927. if (this._isAlphaBlendDirty) {
  10928. if (this._alphaBlend) {
  10929. gl.enable(gl.BLEND);
  10930. }
  10931. else {
  10932. gl.disable(gl.BLEND);
  10933. }
  10934. this._isAlphaBlendDirty = false;
  10935. }
  10936. // Alpha function
  10937. if (this._isBlendFunctionParametersDirty) {
  10938. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  10939. this._isBlendFunctionParametersDirty = false;
  10940. }
  10941. // Alpha equation
  10942. if (this._isBlendEquationParametersDirty) {
  10943. gl.blendEquationSeparate(this._blendEquationParameters[0], this._blendEquationParameters[1]);
  10944. this._isBlendEquationParametersDirty = false;
  10945. }
  10946. // Constants
  10947. if (this._isBlendConstantsDirty) {
  10948. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  10949. this._isBlendConstantsDirty = false;
  10950. }
  10951. };
  10952. return _AlphaState;
  10953. }());
  10954. BABYLON._AlphaState = _AlphaState;
  10955. })(BABYLON || (BABYLON = {}));
  10956. //# sourceMappingURL=babylon.alphaCullingState.js.map
  10957. var BABYLON;
  10958. (function (BABYLON) {
  10959. /**
  10960. * @hidden
  10961. **/
  10962. var _DepthCullingState = /** @class */ (function () {
  10963. /**
  10964. * Initializes the state.
  10965. */
  10966. function _DepthCullingState() {
  10967. this._isDepthTestDirty = false;
  10968. this._isDepthMaskDirty = false;
  10969. this._isDepthFuncDirty = false;
  10970. this._isCullFaceDirty = false;
  10971. this._isCullDirty = false;
  10972. this._isZOffsetDirty = false;
  10973. this._isFrontFaceDirty = false;
  10974. this.reset();
  10975. }
  10976. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  10977. get: function () {
  10978. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty || this._isFrontFaceDirty;
  10979. },
  10980. enumerable: true,
  10981. configurable: true
  10982. });
  10983. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  10984. get: function () {
  10985. return this._zOffset;
  10986. },
  10987. set: function (value) {
  10988. if (this._zOffset === value) {
  10989. return;
  10990. }
  10991. this._zOffset = value;
  10992. this._isZOffsetDirty = true;
  10993. },
  10994. enumerable: true,
  10995. configurable: true
  10996. });
  10997. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  10998. get: function () {
  10999. return this._cullFace;
  11000. },
  11001. set: function (value) {
  11002. if (this._cullFace === value) {
  11003. return;
  11004. }
  11005. this._cullFace = value;
  11006. this._isCullFaceDirty = true;
  11007. },
  11008. enumerable: true,
  11009. configurable: true
  11010. });
  11011. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  11012. get: function () {
  11013. return this._cull;
  11014. },
  11015. set: function (value) {
  11016. if (this._cull === value) {
  11017. return;
  11018. }
  11019. this._cull = value;
  11020. this._isCullDirty = true;
  11021. },
  11022. enumerable: true,
  11023. configurable: true
  11024. });
  11025. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  11026. get: function () {
  11027. return this._depthFunc;
  11028. },
  11029. set: function (value) {
  11030. if (this._depthFunc === value) {
  11031. return;
  11032. }
  11033. this._depthFunc = value;
  11034. this._isDepthFuncDirty = true;
  11035. },
  11036. enumerable: true,
  11037. configurable: true
  11038. });
  11039. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  11040. get: function () {
  11041. return this._depthMask;
  11042. },
  11043. set: function (value) {
  11044. if (this._depthMask === value) {
  11045. return;
  11046. }
  11047. this._depthMask = value;
  11048. this._isDepthMaskDirty = true;
  11049. },
  11050. enumerable: true,
  11051. configurable: true
  11052. });
  11053. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  11054. get: function () {
  11055. return this._depthTest;
  11056. },
  11057. set: function (value) {
  11058. if (this._depthTest === value) {
  11059. return;
  11060. }
  11061. this._depthTest = value;
  11062. this._isDepthTestDirty = true;
  11063. },
  11064. enumerable: true,
  11065. configurable: true
  11066. });
  11067. Object.defineProperty(_DepthCullingState.prototype, "frontFace", {
  11068. get: function () {
  11069. return this._frontFace;
  11070. },
  11071. set: function (value) {
  11072. if (this._frontFace === value) {
  11073. return;
  11074. }
  11075. this._frontFace = value;
  11076. this._isFrontFaceDirty = true;
  11077. },
  11078. enumerable: true,
  11079. configurable: true
  11080. });
  11081. _DepthCullingState.prototype.reset = function () {
  11082. this._depthMask = true;
  11083. this._depthTest = true;
  11084. this._depthFunc = null;
  11085. this._cullFace = null;
  11086. this._cull = null;
  11087. this._zOffset = 0;
  11088. this._frontFace = null;
  11089. this._isDepthTestDirty = true;
  11090. this._isDepthMaskDirty = true;
  11091. this._isDepthFuncDirty = false;
  11092. this._isCullFaceDirty = false;
  11093. this._isCullDirty = false;
  11094. this._isZOffsetDirty = false;
  11095. this._isFrontFaceDirty = false;
  11096. };
  11097. _DepthCullingState.prototype.apply = function (gl) {
  11098. if (!this.isDirty) {
  11099. return;
  11100. }
  11101. // Cull
  11102. if (this._isCullDirty) {
  11103. if (this.cull) {
  11104. gl.enable(gl.CULL_FACE);
  11105. }
  11106. else {
  11107. gl.disable(gl.CULL_FACE);
  11108. }
  11109. this._isCullDirty = false;
  11110. }
  11111. // Cull face
  11112. if (this._isCullFaceDirty) {
  11113. gl.cullFace(this.cullFace);
  11114. this._isCullFaceDirty = false;
  11115. }
  11116. // Depth mask
  11117. if (this._isDepthMaskDirty) {
  11118. gl.depthMask(this.depthMask);
  11119. this._isDepthMaskDirty = false;
  11120. }
  11121. // Depth test
  11122. if (this._isDepthTestDirty) {
  11123. if (this.depthTest) {
  11124. gl.enable(gl.DEPTH_TEST);
  11125. }
  11126. else {
  11127. gl.disable(gl.DEPTH_TEST);
  11128. }
  11129. this._isDepthTestDirty = false;
  11130. }
  11131. // Depth func
  11132. if (this._isDepthFuncDirty) {
  11133. gl.depthFunc(this.depthFunc);
  11134. this._isDepthFuncDirty = false;
  11135. }
  11136. // zOffset
  11137. if (this._isZOffsetDirty) {
  11138. if (this.zOffset) {
  11139. gl.enable(gl.POLYGON_OFFSET_FILL);
  11140. gl.polygonOffset(this.zOffset, 0);
  11141. }
  11142. else {
  11143. gl.disable(gl.POLYGON_OFFSET_FILL);
  11144. }
  11145. this._isZOffsetDirty = false;
  11146. }
  11147. // Front face
  11148. if (this._isFrontFaceDirty) {
  11149. gl.frontFace(this.frontFace);
  11150. this._isFrontFaceDirty = false;
  11151. }
  11152. };
  11153. return _DepthCullingState;
  11154. }());
  11155. BABYLON._DepthCullingState = _DepthCullingState;
  11156. })(BABYLON || (BABYLON = {}));
  11157. //# sourceMappingURL=babylon.depthCullingState.js.map
  11158. var BABYLON;
  11159. (function (BABYLON) {
  11160. /**
  11161. * @hidden
  11162. **/
  11163. var _StencilState = /** @class */ (function () {
  11164. function _StencilState() {
  11165. this._isStencilTestDirty = false;
  11166. this._isStencilMaskDirty = false;
  11167. this._isStencilFuncDirty = false;
  11168. this._isStencilOpDirty = false;
  11169. this.reset();
  11170. }
  11171. Object.defineProperty(_StencilState.prototype, "isDirty", {
  11172. get: function () {
  11173. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  11174. },
  11175. enumerable: true,
  11176. configurable: true
  11177. });
  11178. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  11179. get: function () {
  11180. return this._stencilFunc;
  11181. },
  11182. set: function (value) {
  11183. if (this._stencilFunc === value) {
  11184. return;
  11185. }
  11186. this._stencilFunc = value;
  11187. this._isStencilFuncDirty = true;
  11188. },
  11189. enumerable: true,
  11190. configurable: true
  11191. });
  11192. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  11193. get: function () {
  11194. return this._stencilFuncRef;
  11195. },
  11196. set: function (value) {
  11197. if (this._stencilFuncRef === value) {
  11198. return;
  11199. }
  11200. this._stencilFuncRef = value;
  11201. this._isStencilFuncDirty = true;
  11202. },
  11203. enumerable: true,
  11204. configurable: true
  11205. });
  11206. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  11207. get: function () {
  11208. return this._stencilFuncMask;
  11209. },
  11210. set: function (value) {
  11211. if (this._stencilFuncMask === value) {
  11212. return;
  11213. }
  11214. this._stencilFuncMask = value;
  11215. this._isStencilFuncDirty = true;
  11216. },
  11217. enumerable: true,
  11218. configurable: true
  11219. });
  11220. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  11221. get: function () {
  11222. return this._stencilOpStencilFail;
  11223. },
  11224. set: function (value) {
  11225. if (this._stencilOpStencilFail === value) {
  11226. return;
  11227. }
  11228. this._stencilOpStencilFail = value;
  11229. this._isStencilOpDirty = true;
  11230. },
  11231. enumerable: true,
  11232. configurable: true
  11233. });
  11234. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  11235. get: function () {
  11236. return this._stencilOpDepthFail;
  11237. },
  11238. set: function (value) {
  11239. if (this._stencilOpDepthFail === value) {
  11240. return;
  11241. }
  11242. this._stencilOpDepthFail = value;
  11243. this._isStencilOpDirty = true;
  11244. },
  11245. enumerable: true,
  11246. configurable: true
  11247. });
  11248. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  11249. get: function () {
  11250. return this._stencilOpStencilDepthPass;
  11251. },
  11252. set: function (value) {
  11253. if (this._stencilOpStencilDepthPass === value) {
  11254. return;
  11255. }
  11256. this._stencilOpStencilDepthPass = value;
  11257. this._isStencilOpDirty = true;
  11258. },
  11259. enumerable: true,
  11260. configurable: true
  11261. });
  11262. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  11263. get: function () {
  11264. return this._stencilMask;
  11265. },
  11266. set: function (value) {
  11267. if (this._stencilMask === value) {
  11268. return;
  11269. }
  11270. this._stencilMask = value;
  11271. this._isStencilMaskDirty = true;
  11272. },
  11273. enumerable: true,
  11274. configurable: true
  11275. });
  11276. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  11277. get: function () {
  11278. return this._stencilTest;
  11279. },
  11280. set: function (value) {
  11281. if (this._stencilTest === value) {
  11282. return;
  11283. }
  11284. this._stencilTest = value;
  11285. this._isStencilTestDirty = true;
  11286. },
  11287. enumerable: true,
  11288. configurable: true
  11289. });
  11290. _StencilState.prototype.reset = function () {
  11291. this._stencilTest = false;
  11292. this._stencilMask = 0xFF;
  11293. this._stencilFunc = BABYLON.Engine.ALWAYS;
  11294. this._stencilFuncRef = 1;
  11295. this._stencilFuncMask = 0xFF;
  11296. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  11297. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  11298. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  11299. this._isStencilTestDirty = true;
  11300. this._isStencilMaskDirty = true;
  11301. this._isStencilFuncDirty = true;
  11302. this._isStencilOpDirty = true;
  11303. };
  11304. _StencilState.prototype.apply = function (gl) {
  11305. if (!this.isDirty) {
  11306. return;
  11307. }
  11308. // Stencil test
  11309. if (this._isStencilTestDirty) {
  11310. if (this.stencilTest) {
  11311. gl.enable(gl.STENCIL_TEST);
  11312. }
  11313. else {
  11314. gl.disable(gl.STENCIL_TEST);
  11315. }
  11316. this._isStencilTestDirty = false;
  11317. }
  11318. // Stencil mask
  11319. if (this._isStencilMaskDirty) {
  11320. gl.stencilMask(this.stencilMask);
  11321. this._isStencilMaskDirty = false;
  11322. }
  11323. // Stencil func
  11324. if (this._isStencilFuncDirty) {
  11325. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  11326. this._isStencilFuncDirty = false;
  11327. }
  11328. // Stencil op
  11329. if (this._isStencilOpDirty) {
  11330. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  11331. this._isStencilOpDirty = false;
  11332. }
  11333. };
  11334. return _StencilState;
  11335. }());
  11336. BABYLON._StencilState = _StencilState;
  11337. })(BABYLON || (BABYLON = {}));
  11338. //# sourceMappingURL=babylon.stencilState.js.map
  11339. var __assign = (this && this.__assign) || function () {
  11340. __assign = Object.assign || function(t) {
  11341. for (var s, i = 1, n = arguments.length; i < n; i++) {
  11342. s = arguments[i];
  11343. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  11344. t[p] = s[p];
  11345. }
  11346. return t;
  11347. };
  11348. return __assign.apply(this, arguments);
  11349. };
  11350. var BABYLON;
  11351. (function (BABYLON) {
  11352. /**
  11353. * Keeps track of all the buffer info used in engine.
  11354. */
  11355. var BufferPointer = /** @class */ (function () {
  11356. function BufferPointer() {
  11357. }
  11358. return BufferPointer;
  11359. }());
  11360. /**
  11361. * Interface for attribute information associated with buffer instanciation
  11362. */
  11363. var InstancingAttributeInfo = /** @class */ (function () {
  11364. function InstancingAttributeInfo() {
  11365. }
  11366. return InstancingAttributeInfo;
  11367. }());
  11368. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  11369. /**
  11370. * Define options used to create a render target texture
  11371. */
  11372. var RenderTargetCreationOptions = /** @class */ (function () {
  11373. function RenderTargetCreationOptions() {
  11374. }
  11375. return RenderTargetCreationOptions;
  11376. }());
  11377. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  11378. /**
  11379. * Define options used to create a depth texture
  11380. */
  11381. var DepthTextureCreationOptions = /** @class */ (function () {
  11382. function DepthTextureCreationOptions() {
  11383. }
  11384. return DepthTextureCreationOptions;
  11385. }());
  11386. BABYLON.DepthTextureCreationOptions = DepthTextureCreationOptions;
  11387. /**
  11388. * Class used to describe the capabilities of the engine relatively to the current browser
  11389. */
  11390. var EngineCapabilities = /** @class */ (function () {
  11391. function EngineCapabilities() {
  11392. }
  11393. return EngineCapabilities;
  11394. }());
  11395. BABYLON.EngineCapabilities = EngineCapabilities;
  11396. /**
  11397. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio
  11398. */
  11399. var Engine = /** @class */ (function () {
  11400. /**
  11401. * Creates a new engine
  11402. * @param canvasOrContext defines the canvas or WebGL context to use for rendering. If you provide a WebGL context, Babylon.js will not hook events on the canvas (like pointers, keyboards, etc...) so no event observables will be available. This is mostly used when Babylon.js is used as a plugin on a system which alreay used the WebGL context
  11403. * @param antialias defines enable antialiasing (default: false)
  11404. * @param options defines further options to be sent to the getContext() function
  11405. * @param adaptToDeviceRatio defines whether to adapt to the device's viewport characteristics (default: false)
  11406. */
  11407. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  11408. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  11409. var _this = this;
  11410. // Public members
  11411. /**
  11412. * Gets or sets a boolean that indicates if textures must be forced to power of 2 size even if not required
  11413. */
  11414. this.forcePOTTextures = false;
  11415. /**
  11416. * Gets a boolean indicating if the engine is currently rendering in fullscreen mode
  11417. */
  11418. this.isFullscreen = false;
  11419. /**
  11420. * Gets a boolean indicating if the pointer is currently locked
  11421. */
  11422. this.isPointerLock = false;
  11423. /**
  11424. * Gets or sets a boolean indicating if back faces must be culled (true by default)
  11425. */
  11426. this.cullBackFaces = true;
  11427. /**
  11428. * Gets or sets a boolean indicating if the engine must keep rendering even if the window is not in foregroun
  11429. */
  11430. this.renderEvenInBackground = true;
  11431. /**
  11432. * Gets or sets a boolean indicating that cache can be kept between frames
  11433. */
  11434. this.preventCacheWipeBetweenFrames = false;
  11435. /**
  11436. * Gets or sets a boolean to enable/disable IndexedDB support and avoid XHR on .manifest
  11437. **/
  11438. this.enableOfflineSupport = false;
  11439. /**
  11440. * 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)
  11441. **/
  11442. this.disableManifestCheck = false;
  11443. /**
  11444. * Gets the list of created scenes
  11445. */
  11446. this.scenes = new Array();
  11447. /**
  11448. * Gets the list of created postprocesses
  11449. */
  11450. this.postProcesses = new Array();
  11451. /** Gets or sets a boolean indicating if the engine should validate programs after compilation */
  11452. this.validateShaderPrograms = false;
  11453. // Observables
  11454. /**
  11455. * Observable event triggered each time the rendering canvas is resized
  11456. */
  11457. this.onResizeObservable = new BABYLON.Observable();
  11458. /**
  11459. * Observable event triggered each time the canvas loses focus
  11460. */
  11461. this.onCanvasBlurObservable = new BABYLON.Observable();
  11462. /**
  11463. * Observable event triggered each time the canvas gains focus
  11464. */
  11465. this.onCanvasFocusObservable = new BABYLON.Observable();
  11466. /**
  11467. * Observable event triggered each time the canvas receives pointerout event
  11468. */
  11469. this.onCanvasPointerOutObservable = new BABYLON.Observable();
  11470. /**
  11471. * Observable event triggered before each texture is initialized
  11472. */
  11473. this.onBeforeTextureInitObservable = new BABYLON.Observable();
  11474. //WebVR
  11475. this._vrDisplay = undefined;
  11476. this._vrSupported = false;
  11477. this._vrExclusivePointerMode = false;
  11478. // Uniform buffers list
  11479. /**
  11480. * Gets or sets a boolean indicating that uniform buffers must be disabled even if they are supported
  11481. */
  11482. this.disableUniformBuffers = false;
  11483. /** @hidden */
  11484. this._uniformBuffers = new Array();
  11485. // Observables
  11486. /**
  11487. * Observable raised when the engine begins a new frame
  11488. */
  11489. this.onBeginFrameObservable = new BABYLON.Observable();
  11490. /**
  11491. * Observable raised when the engine ends the current frame
  11492. */
  11493. this.onEndFrameObservable = new BABYLON.Observable();
  11494. /**
  11495. * Observable raised when the engine is about to compile a shader
  11496. */
  11497. this.onBeforeShaderCompilationObservable = new BABYLON.Observable();
  11498. /**
  11499. * Observable raised when the engine has jsut compiled a shader
  11500. */
  11501. this.onAfterShaderCompilationObservable = new BABYLON.Observable();
  11502. this._windowIsBackground = false;
  11503. this._webGLVersion = 1.0;
  11504. /** @hidden */
  11505. this._badOS = false;
  11506. /** @hidden */
  11507. this._badDesktopOS = false;
  11508. /**
  11509. * Gets or sets a value indicating if we want to disable texture binding optmization.
  11510. * This could be required on some buggy drivers which wants to have textures bound in a progressive order.
  11511. * By default Babylon.js will try to let textures bound where they are and only update the samplers to point where the texture is
  11512. */
  11513. this.disableTextureBindingOptimization = false;
  11514. /**
  11515. * Observable signaled when VR display mode changes
  11516. */
  11517. this.onVRDisplayChangedObservable = new BABYLON.Observable();
  11518. /**
  11519. * Observable signaled when VR request present is complete
  11520. */
  11521. this.onVRRequestPresentComplete = new BABYLON.Observable();
  11522. /**
  11523. * Observable signaled when VR request present starts
  11524. */
  11525. this.onVRRequestPresentStart = new BABYLON.Observable();
  11526. this._colorWrite = true;
  11527. /** @hidden */
  11528. this._drawCalls = new BABYLON.PerfCounter();
  11529. /** @hidden */
  11530. this._textureCollisions = new BABYLON.PerfCounter();
  11531. this._renderingQueueLaunched = false;
  11532. this._activeRenderLoops = new Array();
  11533. // Deterministic lockstepMaxSteps
  11534. this._deterministicLockstep = false;
  11535. this._lockstepMaxSteps = 4;
  11536. // Lost context
  11537. /**
  11538. * Observable signaled when a context lost event is raised
  11539. */
  11540. this.onContextLostObservable = new BABYLON.Observable();
  11541. /**
  11542. * Observable signaled when a context restored event is raised
  11543. */
  11544. this.onContextRestoredObservable = new BABYLON.Observable();
  11545. this._contextWasLost = false;
  11546. this._doNotHandleContextLost = false;
  11547. // FPS
  11548. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  11549. this._fps = 60;
  11550. this._deltaTime = 0;
  11551. /**
  11552. * Turn this value on if you want to pause FPS computation when in background
  11553. */
  11554. this.disablePerformanceMonitorInBackground = false;
  11555. // States
  11556. /** @hidden */
  11557. this._depthCullingState = new BABYLON._DepthCullingState();
  11558. /** @hidden */
  11559. this._stencilState = new BABYLON._StencilState();
  11560. /** @hidden */
  11561. this._alphaState = new BABYLON._AlphaState();
  11562. /** @hidden */
  11563. this._alphaMode = Engine.ALPHA_DISABLE;
  11564. // Cache
  11565. this._internalTexturesCache = new Array();
  11566. /** @hidden */
  11567. this._activeChannel = 0;
  11568. this._currentTextureChannel = -1;
  11569. /** @hidden */
  11570. this._boundTexturesCache = {};
  11571. this._compiledEffects = {};
  11572. this._vertexAttribArraysEnabled = [];
  11573. this._uintIndicesCurrentlySet = false;
  11574. this._currentBoundBuffer = new Array();
  11575. /** @hidden */
  11576. this._currentFramebuffer = null;
  11577. this._currentBufferPointers = new Array();
  11578. this._currentInstanceLocations = new Array();
  11579. this._currentInstanceBuffers = new Array();
  11580. this._firstBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  11581. this._lastBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  11582. this._vaoRecordInProgress = false;
  11583. this._mustWipeVertexAttributes = false;
  11584. this._nextFreeTextureSlots = new Array();
  11585. this._maxSimultaneousTextures = 0;
  11586. this._activeRequests = new Array();
  11587. // Hardware supported Compressed Textures
  11588. this._texturesSupported = new Array();
  11589. /**
  11590. * Defines whether the engine has been created with the premultipliedAlpha option on or not.
  11591. */
  11592. this.premultipliedAlpha = true;
  11593. this._viewportCached = new BABYLON.Vector4(0, 0, 0, 0);
  11594. this._onVRFullScreenTriggered = function () {
  11595. if (_this._vrDisplay && _this._vrDisplay.isPresenting) {
  11596. //get the old size before we change
  11597. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  11598. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  11599. //get the width and height, change the render size
  11600. var leftEye = _this._vrDisplay.getEyeParameters('left');
  11601. _this.setHardwareScalingLevel(1);
  11602. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  11603. }
  11604. else {
  11605. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  11606. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  11607. }
  11608. };
  11609. this._unpackFlipYCached = null;
  11610. /**
  11611. * In case you are sharing the context with other applications, it might
  11612. * be interested to not cache the unpack flip y state to ensure a consistent
  11613. * value would be set.
  11614. */
  11615. this.enableUnpackFlipYCached = true;
  11616. this._boundUniforms = {};
  11617. // Register promises
  11618. BABYLON.PromisePolyfill.Apply();
  11619. var canvas = null;
  11620. Engine.Instances.push(this);
  11621. if (!canvasOrContext) {
  11622. return;
  11623. }
  11624. options = options || {};
  11625. if (canvasOrContext.getContext) {
  11626. canvas = canvasOrContext;
  11627. this._renderingCanvas = canvas;
  11628. if (antialias != null) {
  11629. options.antialias = antialias;
  11630. }
  11631. if (options.deterministicLockstep === undefined) {
  11632. options.deterministicLockstep = false;
  11633. }
  11634. if (options.lockstepMaxSteps === undefined) {
  11635. options.lockstepMaxSteps = 4;
  11636. }
  11637. if (options.preserveDrawingBuffer === undefined) {
  11638. options.preserveDrawingBuffer = false;
  11639. }
  11640. if (options.audioEngine === undefined) {
  11641. options.audioEngine = true;
  11642. }
  11643. if (options.stencil === undefined) {
  11644. options.stencil = true;
  11645. }
  11646. if (options.premultipliedAlpha === false) {
  11647. this.premultipliedAlpha = false;
  11648. }
  11649. this._deterministicLockstep = options.deterministicLockstep;
  11650. this._lockstepMaxSteps = options.lockstepMaxSteps;
  11651. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  11652. // Exceptions
  11653. if (navigator && navigator.userAgent) {
  11654. var ua = navigator.userAgent;
  11655. for (var _i = 0, _a = Engine.ExceptionList; _i < _a.length; _i++) {
  11656. var exception = _a[_i];
  11657. var key = exception.key;
  11658. var targets = exception.targets;
  11659. if (ua.indexOf(key) > -1) {
  11660. if (exception.capture && exception.captureConstraint) {
  11661. var capture = exception.capture;
  11662. var constraint = exception.captureConstraint;
  11663. var regex = new RegExp(capture);
  11664. var matches = regex.exec(ua);
  11665. if (matches && matches.length > 0) {
  11666. var capturedValue = parseInt(matches[matches.length - 1]);
  11667. if (capturedValue >= constraint) {
  11668. continue;
  11669. }
  11670. }
  11671. }
  11672. for (var _b = 0, targets_1 = targets; _b < targets_1.length; _b++) {
  11673. var target = targets_1[_b];
  11674. switch (target) {
  11675. case "uniformBuffer":
  11676. this.disableUniformBuffers = true;
  11677. break;
  11678. case "textureBindingOptimization":
  11679. this.disableTextureBindingOptimization = true;
  11680. break;
  11681. }
  11682. }
  11683. }
  11684. }
  11685. }
  11686. // GL
  11687. if (!options.disableWebGL2Support) {
  11688. try {
  11689. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  11690. if (this._gl) {
  11691. this._webGLVersion = 2.0;
  11692. }
  11693. }
  11694. catch (e) {
  11695. // Do nothing
  11696. }
  11697. }
  11698. if (!this._gl) {
  11699. if (!canvas) {
  11700. throw new Error("The provided canvas is null or undefined.");
  11701. }
  11702. try {
  11703. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  11704. }
  11705. catch (e) {
  11706. throw new Error("WebGL not supported");
  11707. }
  11708. }
  11709. if (!this._gl) {
  11710. throw new Error("WebGL not supported");
  11711. }
  11712. this._onCanvasFocus = function () {
  11713. _this.onCanvasFocusObservable.notifyObservers(_this);
  11714. };
  11715. this._onCanvasBlur = function () {
  11716. _this.onCanvasBlurObservable.notifyObservers(_this);
  11717. };
  11718. canvas.addEventListener("focus", this._onCanvasFocus);
  11719. canvas.addEventListener("blur", this._onCanvasBlur);
  11720. this._onBlur = function () {
  11721. if (_this.disablePerformanceMonitorInBackground) {
  11722. _this._performanceMonitor.disable();
  11723. }
  11724. _this._windowIsBackground = true;
  11725. };
  11726. this._onFocus = function () {
  11727. if (_this.disablePerformanceMonitorInBackground) {
  11728. _this._performanceMonitor.enable();
  11729. }
  11730. _this._windowIsBackground = false;
  11731. };
  11732. this._onCanvasPointerOut = function (ev) {
  11733. _this.onCanvasPointerOutObservable.notifyObservers(ev);
  11734. };
  11735. window.addEventListener("blur", this._onBlur);
  11736. window.addEventListener("focus", this._onFocus);
  11737. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  11738. // Context lost
  11739. if (!this._doNotHandleContextLost) {
  11740. this._onContextLost = function (evt) {
  11741. evt.preventDefault();
  11742. _this._contextWasLost = true;
  11743. BABYLON.Tools.Warn("WebGL context lost.");
  11744. _this.onContextLostObservable.notifyObservers(_this);
  11745. };
  11746. this._onContextRestored = function (evt) {
  11747. // Adding a timeout to avoid race condition at browser level
  11748. setTimeout(function () {
  11749. // Rebuild gl context
  11750. _this._initGLContext();
  11751. // Rebuild effects
  11752. _this._rebuildEffects();
  11753. // Rebuild textures
  11754. _this._rebuildInternalTextures();
  11755. // Rebuild buffers
  11756. _this._rebuildBuffers();
  11757. // Cache
  11758. _this.wipeCaches(true);
  11759. BABYLON.Tools.Warn("WebGL context successfully restored.");
  11760. _this.onContextRestoredObservable.notifyObservers(_this);
  11761. _this._contextWasLost = false;
  11762. }, 0);
  11763. };
  11764. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  11765. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  11766. }
  11767. }
  11768. else {
  11769. this._gl = canvasOrContext;
  11770. this._renderingCanvas = this._gl.canvas;
  11771. if (this._gl.renderbufferStorageMultisample) {
  11772. this._webGLVersion = 2.0;
  11773. }
  11774. options.stencil = this._gl.getContextAttributes().stencil;
  11775. }
  11776. // Viewport
  11777. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  11778. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  11779. this.resize();
  11780. this._isStencilEnable = options.stencil ? true : false;
  11781. this._initGLContext();
  11782. if (canvas) {
  11783. // Fullscreen
  11784. this._onFullscreenChange = function () {
  11785. if (document.fullscreen !== undefined) {
  11786. _this.isFullscreen = document.fullscreen;
  11787. }
  11788. else if (document.mozFullScreen !== undefined) {
  11789. _this.isFullscreen = document.mozFullScreen;
  11790. }
  11791. else if (document.webkitIsFullScreen !== undefined) {
  11792. _this.isFullscreen = document.webkitIsFullScreen;
  11793. }
  11794. else if (document.msIsFullScreen !== undefined) {
  11795. _this.isFullscreen = document.msIsFullScreen;
  11796. }
  11797. // Pointer lock
  11798. if (_this.isFullscreen && _this._pointerLockRequested && canvas) {
  11799. canvas.requestPointerLock = canvas.requestPointerLock ||
  11800. canvas.msRequestPointerLock ||
  11801. canvas.mozRequestPointerLock ||
  11802. canvas.webkitRequestPointerLock;
  11803. if (canvas.requestPointerLock) {
  11804. canvas.requestPointerLock();
  11805. }
  11806. }
  11807. };
  11808. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  11809. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  11810. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  11811. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  11812. // Pointer lock
  11813. this._onPointerLockChange = function () {
  11814. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  11815. document.webkitPointerLockElement === canvas ||
  11816. document.msPointerLockElement === canvas ||
  11817. document.pointerLockElement === canvas);
  11818. };
  11819. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  11820. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  11821. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  11822. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  11823. this._onVRDisplayPointerRestricted = function () {
  11824. if (canvas) {
  11825. canvas.requestPointerLock();
  11826. }
  11827. };
  11828. this._onVRDisplayPointerUnrestricted = function () {
  11829. document.exitPointerLock();
  11830. };
  11831. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  11832. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  11833. }
  11834. // Create Audio Engine if needed.
  11835. if (!Engine.audioEngine && options.audioEngine && Engine.AudioEngineFactory) {
  11836. Engine.audioEngine = Engine.AudioEngineFactory(this);
  11837. }
  11838. // Prepare buffer pointers
  11839. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  11840. this._currentBufferPointers[i] = new BufferPointer();
  11841. }
  11842. this._linkTrackers(this._firstBoundInternalTextureTracker, this._lastBoundInternalTextureTracker);
  11843. // Load WebVR Devices
  11844. if (options.autoEnableWebVR) {
  11845. this.initWebVR();
  11846. }
  11847. // Detect if we are running on a faulty buggy OS.
  11848. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  11849. // Detect if we are running on a faulty buggy desktop OS.
  11850. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  11851. console.log("Babylon.js engine (v" + Engine.Version + ") launched");
  11852. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  11853. }
  11854. Object.defineProperty(Engine, "LastCreatedEngine", {
  11855. /**
  11856. * Gets the latest created engine
  11857. */
  11858. get: function () {
  11859. if (Engine.Instances.length === 0) {
  11860. return null;
  11861. }
  11862. return Engine.Instances[Engine.Instances.length - 1];
  11863. },
  11864. enumerable: true,
  11865. configurable: true
  11866. });
  11867. Object.defineProperty(Engine, "LastCreatedScene", {
  11868. /**
  11869. * Gets the latest created scene
  11870. */
  11871. get: function () {
  11872. var lastCreatedEngine = Engine.LastCreatedEngine;
  11873. if (!lastCreatedEngine) {
  11874. return null;
  11875. }
  11876. if (lastCreatedEngine.scenes.length === 0) {
  11877. return null;
  11878. }
  11879. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  11880. },
  11881. enumerable: true,
  11882. configurable: true
  11883. });
  11884. /**
  11885. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  11886. * @param flag defines which part of the materials must be marked as dirty
  11887. * @param predicate defines a predicate used to filter which materials should be affected
  11888. */
  11889. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  11890. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  11891. var engine = Engine.Instances[engineIndex];
  11892. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  11893. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  11894. }
  11895. }
  11896. };
  11897. Object.defineProperty(Engine, "Version", {
  11898. /**
  11899. * Returns the current version of the framework
  11900. */
  11901. get: function () {
  11902. return "3.3.0-rc.0";
  11903. },
  11904. enumerable: true,
  11905. configurable: true
  11906. });
  11907. Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", {
  11908. /**
  11909. * Gets a boolean indicating that the engine is currently in VR exclusive mode for the pointers
  11910. * @see https://docs.microsoft.com/en-us/microsoft-edge/webvr/essentials#mouse-input
  11911. */
  11912. get: function () {
  11913. return this._vrExclusivePointerMode;
  11914. },
  11915. enumerable: true,
  11916. configurable: true
  11917. });
  11918. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  11919. /**
  11920. * Gets a boolean indicating that the engine supports uniform buffers
  11921. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  11922. */
  11923. get: function () {
  11924. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  11925. },
  11926. enumerable: true,
  11927. configurable: true
  11928. });
  11929. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  11930. /**
  11931. * Gets a boolean indicating that only power of 2 textures are supported
  11932. * Please note that you can still use non power of 2 textures but in this case the engine will forcefully convert them
  11933. */
  11934. get: function () {
  11935. return this._webGLVersion < 2 || this.forcePOTTextures;
  11936. },
  11937. enumerable: true,
  11938. configurable: true
  11939. });
  11940. Object.defineProperty(Engine.prototype, "doNotHandleContextLost", {
  11941. /**
  11942. * Gets or sets a boolean indicating if resources should be retained to be able to handle context lost events
  11943. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#handling-webgl-context-lost
  11944. */
  11945. get: function () {
  11946. return this._doNotHandleContextLost;
  11947. },
  11948. set: function (value) {
  11949. this._doNotHandleContextLost = value;
  11950. },
  11951. enumerable: true,
  11952. configurable: true
  11953. });
  11954. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  11955. /**
  11956. * Gets the performance monitor attached to this engine
  11957. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#engineinstrumentation
  11958. */
  11959. get: function () {
  11960. return this._performanceMonitor;
  11961. },
  11962. enumerable: true,
  11963. configurable: true
  11964. });
  11965. Object.defineProperty(Engine.prototype, "texturesSupported", {
  11966. /**
  11967. * Gets the list of texture formats supported
  11968. */
  11969. get: function () {
  11970. return this._texturesSupported;
  11971. },
  11972. enumerable: true,
  11973. configurable: true
  11974. });
  11975. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  11976. /**
  11977. * Gets the list of texture formats in use
  11978. */
  11979. get: function () {
  11980. return this._textureFormatInUse;
  11981. },
  11982. enumerable: true,
  11983. configurable: true
  11984. });
  11985. Object.defineProperty(Engine.prototype, "currentViewport", {
  11986. /**
  11987. * Gets the current viewport
  11988. */
  11989. get: function () {
  11990. return this._cachedViewport;
  11991. },
  11992. enumerable: true,
  11993. configurable: true
  11994. });
  11995. Object.defineProperty(Engine.prototype, "emptyTexture", {
  11996. /**
  11997. * Gets the default empty texture
  11998. */
  11999. get: function () {
  12000. if (!this._emptyTexture) {
  12001. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, Engine.TEXTURE_NEAREST_SAMPLINGMODE);
  12002. }
  12003. return this._emptyTexture;
  12004. },
  12005. enumerable: true,
  12006. configurable: true
  12007. });
  12008. Object.defineProperty(Engine.prototype, "emptyTexture3D", {
  12009. /**
  12010. * Gets the default empty 3D texture
  12011. */
  12012. get: function () {
  12013. if (!this._emptyTexture3D) {
  12014. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, Engine.TEXTURE_NEAREST_SAMPLINGMODE);
  12015. }
  12016. return this._emptyTexture3D;
  12017. },
  12018. enumerable: true,
  12019. configurable: true
  12020. });
  12021. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  12022. /**
  12023. * Gets the default empty cube texture
  12024. */
  12025. get: function () {
  12026. if (!this._emptyCubeTexture) {
  12027. var faceData = new Uint8Array(4);
  12028. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  12029. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, Engine.TEXTUREFORMAT_RGBA, Engine.TEXTURETYPE_UNSIGNED_INT, false, false, Engine.TEXTURE_NEAREST_SAMPLINGMODE);
  12030. }
  12031. return this._emptyCubeTexture;
  12032. },
  12033. enumerable: true,
  12034. configurable: true
  12035. });
  12036. Engine.prototype._rebuildInternalTextures = function () {
  12037. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  12038. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  12039. var internalTexture = currentState_1[_i];
  12040. internalTexture._rebuild();
  12041. }
  12042. };
  12043. Engine.prototype._rebuildEffects = function () {
  12044. for (var key in this._compiledEffects) {
  12045. var effect = this._compiledEffects[key];
  12046. effect._prepareEffect();
  12047. }
  12048. BABYLON.Effect.ResetCache();
  12049. };
  12050. Engine.prototype._rebuildBuffers = function () {
  12051. // Index / Vertex
  12052. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  12053. var scene = _a[_i];
  12054. scene.resetCachedMaterial();
  12055. scene._rebuildGeometries();
  12056. scene._rebuildTextures();
  12057. }
  12058. // Uniforms
  12059. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  12060. var uniformBuffer = _c[_b];
  12061. uniformBuffer._rebuild();
  12062. }
  12063. };
  12064. Engine.prototype._initGLContext = function () {
  12065. // Caps
  12066. this._caps = new EngineCapabilities();
  12067. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  12068. this._caps.maxCombinedTexturesImageUnits = this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  12069. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  12070. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  12071. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  12072. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  12073. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  12074. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  12075. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  12076. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  12077. // Infos
  12078. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  12079. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  12080. if (rendererInfo != null) {
  12081. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  12082. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  12083. }
  12084. if (!this._glVendor) {
  12085. this._glVendor = "Unknown vendor";
  12086. }
  12087. if (!this._glRenderer) {
  12088. this._glRenderer = "Unknown renderer";
  12089. }
  12090. // Constants
  12091. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  12092. if (this._gl.RGBA16F !== 0x881A) {
  12093. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  12094. }
  12095. if (this._gl.RGBA32F !== 0x8814) {
  12096. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  12097. }
  12098. if (this._gl.DEPTH24_STENCIL8 !== 35056) {
  12099. this._gl.DEPTH24_STENCIL8 = 35056;
  12100. }
  12101. // Extensions
  12102. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  12103. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  12104. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  12105. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  12106. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  12107. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  12108. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  12109. 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');
  12110. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  12111. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  12112. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  12113. this._caps.highPrecisionShaderSupported = true;
  12114. this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
  12115. if (this._caps.timerQuery) {
  12116. if (this._webGLVersion === 1) {
  12117. this._gl.getQuery = this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery);
  12118. }
  12119. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  12120. }
  12121. // Checks if some of the format renders first to allow the use of webgl inspector.
  12122. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  12123. this._caps.textureFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float')) ? true : false;
  12124. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear') ? true : false;
  12125. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer() ? true : false;
  12126. this._caps.textureHalfFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float')) ? true : false;
  12127. this._caps.textureHalfFloatLinearFiltering = (this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'))) ? true : false;
  12128. if (this._webGLVersion > 1) {
  12129. this._gl.HALF_FLOAT_OES = 0x140B;
  12130. }
  12131. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  12132. this._caps.textureLOD = (this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod')) ? true : false;
  12133. // Draw buffers
  12134. if (this._webGLVersion > 1) {
  12135. this._caps.drawBuffersExtension = true;
  12136. }
  12137. else {
  12138. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  12139. if (drawBuffersExtension !== null) {
  12140. this._caps.drawBuffersExtension = true;
  12141. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  12142. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  12143. for (var i = 0; i < 16; i++) {
  12144. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  12145. }
  12146. }
  12147. else {
  12148. this._caps.drawBuffersExtension = false;
  12149. }
  12150. }
  12151. // Depth Texture
  12152. if (this._webGLVersion > 1) {
  12153. this._caps.depthTextureExtension = true;
  12154. }
  12155. else {
  12156. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  12157. if (depthTextureExtension != null) {
  12158. this._caps.depthTextureExtension = true;
  12159. this._gl.UNSIGNED_INT_24_8 = depthTextureExtension.UNSIGNED_INT_24_8_WEBGL;
  12160. }
  12161. }
  12162. // Vertex array object
  12163. if (this._webGLVersion > 1) {
  12164. this._caps.vertexArrayObject = true;
  12165. }
  12166. else {
  12167. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  12168. if (vertexArrayObjectExtension != null) {
  12169. this._caps.vertexArrayObject = true;
  12170. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  12171. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  12172. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  12173. }
  12174. else {
  12175. this._caps.vertexArrayObject = false;
  12176. }
  12177. }
  12178. // Instances count
  12179. if (this._webGLVersion > 1) {
  12180. this._caps.instancedArrays = true;
  12181. }
  12182. else {
  12183. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  12184. if (instanceExtension != null) {
  12185. this._caps.instancedArrays = true;
  12186. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  12187. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  12188. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  12189. }
  12190. else {
  12191. this._caps.instancedArrays = false;
  12192. }
  12193. }
  12194. // Intelligently add supported compressed formats in order to check for.
  12195. // Check for ASTC support first as it is most powerful and to be very cross platform.
  12196. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  12197. // Likely no hardware which supports both PVR & DXT, so order matters little.
  12198. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  12199. if (this._caps.astc)
  12200. this.texturesSupported.push('-astc.ktx');
  12201. if (this._caps.s3tc)
  12202. this.texturesSupported.push('-dxt.ktx');
  12203. if (this._caps.pvrtc)
  12204. this.texturesSupported.push('-pvrtc.ktx');
  12205. if (this._caps.etc2)
  12206. this.texturesSupported.push('-etc2.ktx');
  12207. if (this._caps.etc1)
  12208. this.texturesSupported.push('-etc1.ktx');
  12209. if (this._gl.getShaderPrecisionFormat) {
  12210. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  12211. if (highp) {
  12212. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  12213. }
  12214. }
  12215. // Depth buffer
  12216. this.setDepthBuffer(true);
  12217. this.setDepthFunctionToLessOrEqual();
  12218. this.setDepthWrite(true);
  12219. // Texture maps
  12220. this._maxSimultaneousTextures = this._caps.maxCombinedTexturesImageUnits;
  12221. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  12222. this._nextFreeTextureSlots.push(slot);
  12223. }
  12224. };
  12225. Object.defineProperty(Engine.prototype, "webGLVersion", {
  12226. /**
  12227. * Gets version of the current webGL context
  12228. */
  12229. get: function () {
  12230. return this._webGLVersion;
  12231. },
  12232. enumerable: true,
  12233. configurable: true
  12234. });
  12235. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  12236. /**
  12237. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  12238. */
  12239. get: function () {
  12240. return this._isStencilEnable;
  12241. },
  12242. enumerable: true,
  12243. configurable: true
  12244. });
  12245. Engine.prototype._prepareWorkingCanvas = function () {
  12246. if (this._workingCanvas) {
  12247. return;
  12248. }
  12249. this._workingCanvas = document.createElement("canvas");
  12250. var context = this._workingCanvas.getContext("2d");
  12251. if (context) {
  12252. this._workingContext = context;
  12253. }
  12254. };
  12255. /**
  12256. * Reset the texture cache to empty state
  12257. */
  12258. Engine.prototype.resetTextureCache = function () {
  12259. for (var key in this._boundTexturesCache) {
  12260. if (!this._boundTexturesCache.hasOwnProperty(key)) {
  12261. continue;
  12262. }
  12263. var boundTexture = this._boundTexturesCache[key];
  12264. if (boundTexture) {
  12265. this._removeDesignatedSlot(boundTexture);
  12266. }
  12267. this._boundTexturesCache[key] = null;
  12268. }
  12269. if (!this.disableTextureBindingOptimization) {
  12270. this._nextFreeTextureSlots = [];
  12271. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  12272. this._nextFreeTextureSlots.push(slot);
  12273. }
  12274. }
  12275. this._currentTextureChannel = -1;
  12276. };
  12277. /**
  12278. * Gets a boolean indicating that the engine is running in deterministic lock step mode
  12279. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  12280. * @returns true if engine is in deterministic lock step mode
  12281. */
  12282. Engine.prototype.isDeterministicLockStep = function () {
  12283. return this._deterministicLockstep;
  12284. };
  12285. /**
  12286. * Gets the max steps when engine is running in deterministic lock step
  12287. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  12288. * @returns the max steps
  12289. */
  12290. Engine.prototype.getLockstepMaxSteps = function () {
  12291. return this._lockstepMaxSteps;
  12292. };
  12293. /**
  12294. * Gets an object containing information about the current webGL context
  12295. * @returns an object containing the vender, the renderer and the version of the current webGL context
  12296. */
  12297. Engine.prototype.getGlInfo = function () {
  12298. return {
  12299. vendor: this._glVendor,
  12300. renderer: this._glRenderer,
  12301. version: this._glVersion
  12302. };
  12303. };
  12304. /**
  12305. * Gets current aspect ratio
  12306. * @param camera defines the camera to use to get the aspect ratio
  12307. * @param useScreen defines if screen size must be used (or the current render target if any)
  12308. * @returns a number defining the aspect ratio
  12309. */
  12310. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  12311. if (useScreen === void 0) { useScreen = false; }
  12312. var viewport = camera.viewport;
  12313. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  12314. };
  12315. /**
  12316. * Gets current screen aspect ratio
  12317. * @returns a number defining the aspect ratio
  12318. */
  12319. Engine.prototype.getScreenAspectRatio = function () {
  12320. return (this.getRenderWidth(true)) / (this.getRenderHeight(true));
  12321. };
  12322. /**
  12323. * Gets the current render width
  12324. * @param useScreen defines if screen size must be used (or the current render target if any)
  12325. * @returns a number defining the current render width
  12326. */
  12327. Engine.prototype.getRenderWidth = function (useScreen) {
  12328. if (useScreen === void 0) { useScreen = false; }
  12329. if (!useScreen && this._currentRenderTarget) {
  12330. return this._currentRenderTarget.width;
  12331. }
  12332. return this._gl.drawingBufferWidth;
  12333. };
  12334. /**
  12335. * Gets the current render height
  12336. * @param useScreen defines if screen size must be used (or the current render target if any)
  12337. * @returns a number defining the current render height
  12338. */
  12339. Engine.prototype.getRenderHeight = function (useScreen) {
  12340. if (useScreen === void 0) { useScreen = false; }
  12341. if (!useScreen && this._currentRenderTarget) {
  12342. return this._currentRenderTarget.height;
  12343. }
  12344. return this._gl.drawingBufferHeight;
  12345. };
  12346. /**
  12347. * Gets the HTML canvas attached with the current webGL context
  12348. * @returns a HTML canvas
  12349. */
  12350. Engine.prototype.getRenderingCanvas = function () {
  12351. return this._renderingCanvas;
  12352. };
  12353. /**
  12354. * Gets the client rect of the HTML canvas attached with the current webGL context
  12355. * @returns a client rectanglee
  12356. */
  12357. Engine.prototype.getRenderingCanvasClientRect = function () {
  12358. if (!this._renderingCanvas) {
  12359. return null;
  12360. }
  12361. return this._renderingCanvas.getBoundingClientRect();
  12362. };
  12363. /**
  12364. * Defines the hardware scaling level.
  12365. * By default the hardware scaling level is computed from the window device ratio.
  12366. * 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.
  12367. * @param level defines the level to use
  12368. */
  12369. Engine.prototype.setHardwareScalingLevel = function (level) {
  12370. this._hardwareScalingLevel = level;
  12371. this.resize();
  12372. };
  12373. /**
  12374. * Gets the current hardware scaling level.
  12375. * By default the hardware scaling level is computed from the window device ratio.
  12376. * 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.
  12377. * @returns a number indicating the current hardware scaling level
  12378. */
  12379. Engine.prototype.getHardwareScalingLevel = function () {
  12380. return this._hardwareScalingLevel;
  12381. };
  12382. /**
  12383. * Gets the list of loaded textures
  12384. * @returns an array containing all loaded textures
  12385. */
  12386. Engine.prototype.getLoadedTexturesCache = function () {
  12387. return this._internalTexturesCache;
  12388. };
  12389. /**
  12390. * Gets the object containing all engine capabilities
  12391. * @returns the EngineCapabilities object
  12392. */
  12393. Engine.prototype.getCaps = function () {
  12394. return this._caps;
  12395. };
  12396. Object.defineProperty(Engine.prototype, "drawCalls", {
  12397. /** @hidden */
  12398. get: function () {
  12399. BABYLON.Tools.Warn("drawCalls is deprecated. Please use SceneInstrumentation class");
  12400. return 0;
  12401. },
  12402. enumerable: true,
  12403. configurable: true
  12404. });
  12405. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  12406. /** @hidden */
  12407. get: function () {
  12408. BABYLON.Tools.Warn("drawCallsPerfCounter is deprecated. Please use SceneInstrumentation class");
  12409. return null;
  12410. },
  12411. enumerable: true,
  12412. configurable: true
  12413. });
  12414. /**
  12415. * Gets the current depth function
  12416. * @returns a number defining the depth function
  12417. */
  12418. Engine.prototype.getDepthFunction = function () {
  12419. return this._depthCullingState.depthFunc;
  12420. };
  12421. /**
  12422. * Sets the current depth function
  12423. * @param depthFunc defines the function to use
  12424. */
  12425. Engine.prototype.setDepthFunction = function (depthFunc) {
  12426. this._depthCullingState.depthFunc = depthFunc;
  12427. };
  12428. /**
  12429. * Sets the current depth function to GREATER
  12430. */
  12431. Engine.prototype.setDepthFunctionToGreater = function () {
  12432. this._depthCullingState.depthFunc = this._gl.GREATER;
  12433. };
  12434. /**
  12435. * Sets the current depth function to GEQUAL
  12436. */
  12437. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  12438. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  12439. };
  12440. /**
  12441. * Sets the current depth function to LESS
  12442. */
  12443. Engine.prototype.setDepthFunctionToLess = function () {
  12444. this._depthCullingState.depthFunc = this._gl.LESS;
  12445. };
  12446. /**
  12447. * Sets the current depth function to LEQUAL
  12448. */
  12449. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  12450. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  12451. };
  12452. /**
  12453. * Gets a boolean indicating if stencil buffer is enabled
  12454. * @returns the current stencil buffer state
  12455. */
  12456. Engine.prototype.getStencilBuffer = function () {
  12457. return this._stencilState.stencilTest;
  12458. };
  12459. /**
  12460. * Enable or disable the stencil buffer
  12461. * @param enable defines if the stencil buffer must be enabled or disabled
  12462. */
  12463. Engine.prototype.setStencilBuffer = function (enable) {
  12464. this._stencilState.stencilTest = enable;
  12465. };
  12466. /**
  12467. * Gets the current stencil mask
  12468. * @returns a number defining the new stencil mask to use
  12469. */
  12470. Engine.prototype.getStencilMask = function () {
  12471. return this._stencilState.stencilMask;
  12472. };
  12473. /**
  12474. * Sets the current stencil mask
  12475. * @param mask defines the new stencil mask to use
  12476. */
  12477. Engine.prototype.setStencilMask = function (mask) {
  12478. this._stencilState.stencilMask = mask;
  12479. };
  12480. /**
  12481. * Gets the current stencil function
  12482. * @returns a number defining the stencil function to use
  12483. */
  12484. Engine.prototype.getStencilFunction = function () {
  12485. return this._stencilState.stencilFunc;
  12486. };
  12487. /**
  12488. * Gets the current stencil reference value
  12489. * @returns a number defining the stencil reference value to use
  12490. */
  12491. Engine.prototype.getStencilFunctionReference = function () {
  12492. return this._stencilState.stencilFuncRef;
  12493. };
  12494. /**
  12495. * Gets the current stencil mask
  12496. * @returns a number defining the stencil mask to use
  12497. */
  12498. Engine.prototype.getStencilFunctionMask = function () {
  12499. return this._stencilState.stencilFuncMask;
  12500. };
  12501. /**
  12502. * Sets the current stencil function
  12503. * @param stencilFunc defines the new stencil function to use
  12504. */
  12505. Engine.prototype.setStencilFunction = function (stencilFunc) {
  12506. this._stencilState.stencilFunc = stencilFunc;
  12507. };
  12508. /**
  12509. * Sets the current stencil reference
  12510. * @param reference defines the new stencil reference to use
  12511. */
  12512. Engine.prototype.setStencilFunctionReference = function (reference) {
  12513. this._stencilState.stencilFuncRef = reference;
  12514. };
  12515. /**
  12516. * Sets the current stencil mask
  12517. * @param mask defines the new stencil mask to use
  12518. */
  12519. Engine.prototype.setStencilFunctionMask = function (mask) {
  12520. this._stencilState.stencilFuncMask = mask;
  12521. };
  12522. /**
  12523. * Gets the current stencil operation when stencil fails
  12524. * @returns a number defining stencil operation to use when stencil fails
  12525. */
  12526. Engine.prototype.getStencilOperationFail = function () {
  12527. return this._stencilState.stencilOpStencilFail;
  12528. };
  12529. /**
  12530. * Gets the current stencil operation when depth fails
  12531. * @returns a number defining stencil operation to use when depth fails
  12532. */
  12533. Engine.prototype.getStencilOperationDepthFail = function () {
  12534. return this._stencilState.stencilOpDepthFail;
  12535. };
  12536. /**
  12537. * Gets the current stencil operation when stencil passes
  12538. * @returns a number defining stencil operation to use when stencil passes
  12539. */
  12540. Engine.prototype.getStencilOperationPass = function () {
  12541. return this._stencilState.stencilOpStencilDepthPass;
  12542. };
  12543. /**
  12544. * Sets the stencil operation to use when stencil fails
  12545. * @param operation defines the stencil operation to use when stencil fails
  12546. */
  12547. Engine.prototype.setStencilOperationFail = function (operation) {
  12548. this._stencilState.stencilOpStencilFail = operation;
  12549. };
  12550. /**
  12551. * Sets the stencil operation to use when depth fails
  12552. * @param operation defines the stencil operation to use when depth fails
  12553. */
  12554. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  12555. this._stencilState.stencilOpDepthFail = operation;
  12556. };
  12557. /**
  12558. * Sets the stencil operation to use when stencil passes
  12559. * @param operation defines the stencil operation to use when stencil passes
  12560. */
  12561. Engine.prototype.setStencilOperationPass = function (operation) {
  12562. this._stencilState.stencilOpStencilDepthPass = operation;
  12563. };
  12564. /**
  12565. * Sets a boolean indicating if the dithering state is enabled or disabled
  12566. * @param value defines the dithering state
  12567. */
  12568. Engine.prototype.setDitheringState = function (value) {
  12569. if (value) {
  12570. this._gl.enable(this._gl.DITHER);
  12571. }
  12572. else {
  12573. this._gl.disable(this._gl.DITHER);
  12574. }
  12575. };
  12576. /**
  12577. * Sets a boolean indicating if the rasterizer state is enabled or disabled
  12578. * @param value defines the rasterizer state
  12579. */
  12580. Engine.prototype.setRasterizerState = function (value) {
  12581. if (value) {
  12582. this._gl.disable(this._gl.RASTERIZER_DISCARD);
  12583. }
  12584. else {
  12585. this._gl.enable(this._gl.RASTERIZER_DISCARD);
  12586. }
  12587. };
  12588. /**
  12589. * stop executing a render loop function and remove it from the execution array
  12590. * @param renderFunction defines the function to be removed. If not provided all functions will be removed.
  12591. */
  12592. Engine.prototype.stopRenderLoop = function (renderFunction) {
  12593. if (!renderFunction) {
  12594. this._activeRenderLoops = [];
  12595. return;
  12596. }
  12597. var index = this._activeRenderLoops.indexOf(renderFunction);
  12598. if (index >= 0) {
  12599. this._activeRenderLoops.splice(index, 1);
  12600. }
  12601. };
  12602. /** @hidden */
  12603. Engine.prototype._renderLoop = function () {
  12604. if (!this._contextWasLost) {
  12605. var shouldRender = true;
  12606. if (!this.renderEvenInBackground && this._windowIsBackground) {
  12607. shouldRender = false;
  12608. }
  12609. if (shouldRender) {
  12610. // Start new frame
  12611. this.beginFrame();
  12612. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  12613. var renderFunction = this._activeRenderLoops[index];
  12614. renderFunction();
  12615. }
  12616. // Present
  12617. this.endFrame();
  12618. }
  12619. }
  12620. if (this._activeRenderLoops.length > 0) {
  12621. // Register new frame
  12622. var requester = null;
  12623. if (this._vrDisplay && this._vrDisplay.isPresenting)
  12624. requester = this._vrDisplay;
  12625. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, requester);
  12626. }
  12627. else {
  12628. this._renderingQueueLaunched = false;
  12629. }
  12630. };
  12631. /**
  12632. * Register and execute a render loop. The engine can have more than one render function
  12633. * @param renderFunction defines the function to continuously execute
  12634. */
  12635. Engine.prototype.runRenderLoop = function (renderFunction) {
  12636. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  12637. return;
  12638. }
  12639. this._activeRenderLoops.push(renderFunction);
  12640. if (!this._renderingQueueLaunched) {
  12641. this._renderingQueueLaunched = true;
  12642. this._bindedRenderFunction = this._renderLoop.bind(this);
  12643. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  12644. }
  12645. };
  12646. /**
  12647. * Toggle full screen mode
  12648. * @param requestPointerLock defines if a pointer lock should be requested from the user
  12649. * @param options defines an option object to be sent to the requestFullscreen function
  12650. */
  12651. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  12652. if (this.isFullscreen) {
  12653. BABYLON.Tools.ExitFullscreen();
  12654. }
  12655. else {
  12656. this._pointerLockRequested = requestPointerLock;
  12657. if (this._renderingCanvas) {
  12658. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  12659. }
  12660. }
  12661. };
  12662. /**
  12663. * Clear the current render buffer or the current render target (if any is set up)
  12664. * @param color defines the color to use
  12665. * @param backBuffer defines if the back buffer must be cleared
  12666. * @param depth defines if the depth buffer must be cleared
  12667. * @param stencil defines if the stencil buffer must be cleared
  12668. */
  12669. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  12670. if (stencil === void 0) { stencil = false; }
  12671. this.applyStates();
  12672. var mode = 0;
  12673. if (backBuffer && color) {
  12674. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  12675. mode |= this._gl.COLOR_BUFFER_BIT;
  12676. }
  12677. if (depth) {
  12678. this._gl.clearDepth(1.0);
  12679. mode |= this._gl.DEPTH_BUFFER_BIT;
  12680. }
  12681. if (stencil) {
  12682. this._gl.clearStencil(0);
  12683. mode |= this._gl.STENCIL_BUFFER_BIT;
  12684. }
  12685. this._gl.clear(mode);
  12686. };
  12687. /**
  12688. * Executes a scissor clear (ie. a clear on a specific portion of the screen)
  12689. * @param x defines the x-coordinate of the top left corner of the clear rectangle
  12690. * @param y defines the y-coordinate of the corner of the clear rectangle
  12691. * @param width defines the width of the clear rectangle
  12692. * @param height defines the height of the clear rectangle
  12693. * @param clearColor defines the clear color
  12694. */
  12695. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  12696. var gl = this._gl;
  12697. // Save state
  12698. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  12699. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  12700. // Change state
  12701. gl.enable(gl.SCISSOR_TEST);
  12702. gl.scissor(x, y, width, height);
  12703. // Clear
  12704. this.clear(clearColor, true, true, true);
  12705. // Restore state
  12706. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  12707. if (curScissor === true) {
  12708. gl.enable(gl.SCISSOR_TEST);
  12709. }
  12710. else {
  12711. gl.disable(gl.SCISSOR_TEST);
  12712. }
  12713. };
  12714. /** @hidden */
  12715. Engine.prototype._viewport = function (x, y, width, height) {
  12716. if (x !== this._viewportCached.x ||
  12717. y !== this._viewportCached.y ||
  12718. width !== this._viewportCached.z ||
  12719. height !== this._viewportCached.w) {
  12720. this._viewportCached.x = x;
  12721. this._viewportCached.y = y;
  12722. this._viewportCached.z = width;
  12723. this._viewportCached.w = height;
  12724. this._gl.viewport(x, y, width, height);
  12725. }
  12726. };
  12727. /**
  12728. * Set the WebGL's viewport
  12729. * @param viewport defines the viewport element to be used
  12730. * @param requiredWidth defines the width required for rendering. If not provided the rendering canvas' width is used
  12731. * @param requiredHeight defines the height required for rendering. If not provided the rendering canvas' height is used
  12732. */
  12733. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  12734. var width = requiredWidth || this.getRenderWidth();
  12735. var height = requiredHeight || this.getRenderHeight();
  12736. var x = viewport.x || 0;
  12737. var y = viewport.y || 0;
  12738. this._cachedViewport = viewport;
  12739. this._viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  12740. };
  12741. /**
  12742. * Directly set the WebGL Viewport
  12743. * @param x defines the x coordinate of the viewport (in screen space)
  12744. * @param y defines the y coordinate of the viewport (in screen space)
  12745. * @param width defines the width of the viewport (in screen space)
  12746. * @param height defines the height of the viewport (in screen space)
  12747. * @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
  12748. */
  12749. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  12750. var currentViewport = this._cachedViewport;
  12751. this._cachedViewport = null;
  12752. this._viewport(x, y, width, height);
  12753. return currentViewport;
  12754. };
  12755. /**
  12756. * Begin a new frame
  12757. */
  12758. Engine.prototype.beginFrame = function () {
  12759. this.onBeginFrameObservable.notifyObservers(this);
  12760. this._measureFps();
  12761. };
  12762. /**
  12763. * Enf the current frame
  12764. */
  12765. Engine.prototype.endFrame = function () {
  12766. // Force a flush in case we are using a bad OS.
  12767. if (this._badOS) {
  12768. this.flushFramebuffer();
  12769. }
  12770. // Submit frame to the vr device, if enabled
  12771. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  12772. // TODO: We should only submit the frame if we read frameData successfully.
  12773. this._vrDisplay.submitFrame();
  12774. }
  12775. this.onEndFrameObservable.notifyObservers(this);
  12776. };
  12777. /**
  12778. * Resize the view according to the canvas' size
  12779. */
  12780. Engine.prototype.resize = function () {
  12781. // We're not resizing the size of the canvas while in VR mode & presenting
  12782. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  12783. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  12784. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  12785. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  12786. }
  12787. };
  12788. /**
  12789. * Force a specific size of the canvas
  12790. * @param width defines the new canvas' width
  12791. * @param height defines the new canvas' height
  12792. */
  12793. Engine.prototype.setSize = function (width, height) {
  12794. if (!this._renderingCanvas) {
  12795. return;
  12796. }
  12797. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  12798. return;
  12799. }
  12800. this._renderingCanvas.width = width;
  12801. this._renderingCanvas.height = height;
  12802. for (var index = 0; index < this.scenes.length; index++) {
  12803. var scene = this.scenes[index];
  12804. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  12805. var cam = scene.cameras[camIndex];
  12806. cam._currentRenderId = 0;
  12807. }
  12808. }
  12809. if (this.onResizeObservable.hasObservers) {
  12810. this.onResizeObservable.notifyObservers(this);
  12811. }
  12812. };
  12813. // WebVR functions
  12814. /**
  12815. * Gets a boolean indicating if a webVR device was detected
  12816. * @returns true if a webVR device was detected
  12817. */
  12818. Engine.prototype.isVRDevicePresent = function () {
  12819. return !!this._vrDisplay;
  12820. };
  12821. /**
  12822. * Gets the current webVR device
  12823. * @returns the current webVR device (or null)
  12824. */
  12825. Engine.prototype.getVRDevice = function () {
  12826. return this._vrDisplay;
  12827. };
  12828. /**
  12829. * Initializes a webVR display and starts listening to display change events
  12830. * The onVRDisplayChangedObservable will be notified upon these changes
  12831. * @returns The onVRDisplayChangedObservable
  12832. */
  12833. Engine.prototype.initWebVR = function () {
  12834. this.initWebVRAsync();
  12835. return this.onVRDisplayChangedObservable;
  12836. };
  12837. /**
  12838. * Initializes a webVR display and starts listening to display change events
  12839. * The onVRDisplayChangedObservable will be notified upon these changes
  12840. * @returns A promise containing a VRDisplay and if vr is supported
  12841. */
  12842. Engine.prototype.initWebVRAsync = function () {
  12843. var _this = this;
  12844. var notifyObservers = function () {
  12845. var eventArgs = {
  12846. vrDisplay: _this._vrDisplay,
  12847. vrSupported: _this._vrSupported
  12848. };
  12849. _this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  12850. _this._webVRInitPromise = new Promise(function (res) { res(eventArgs); });
  12851. };
  12852. if (!this._onVrDisplayConnect) {
  12853. this._onVrDisplayConnect = function (event) {
  12854. _this._vrDisplay = event.display;
  12855. notifyObservers();
  12856. };
  12857. this._onVrDisplayDisconnect = function () {
  12858. _this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
  12859. _this._vrDisplay = undefined;
  12860. _this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);
  12861. notifyObservers();
  12862. };
  12863. this._onVrDisplayPresentChange = function () {
  12864. _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
  12865. };
  12866. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  12867. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  12868. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  12869. }
  12870. this._webVRInitPromise = this._webVRInitPromise || this._getVRDisplaysAsync();
  12871. this._webVRInitPromise.then(notifyObservers);
  12872. return this._webVRInitPromise;
  12873. };
  12874. /**
  12875. * Call this function to switch to webVR mode
  12876. * Will do nothing if webVR is not supported or if there is no webVR device
  12877. * @see http://doc.babylonjs.com/how_to/webvr_camera
  12878. */
  12879. Engine.prototype.enableVR = function () {
  12880. var _this = this;
  12881. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  12882. var onResolved = function () {
  12883. _this.onVRRequestPresentComplete.notifyObservers(true);
  12884. _this._onVRFullScreenTriggered();
  12885. };
  12886. var onRejected = function () {
  12887. _this.onVRRequestPresentComplete.notifyObservers(false);
  12888. };
  12889. this.onVRRequestPresentStart.notifyObservers(this);
  12890. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  12891. }
  12892. };
  12893. /**
  12894. * Call this function to leave webVR mode
  12895. * Will do nothing if webVR is not supported or if there is no webVR device
  12896. * @see http://doc.babylonjs.com/how_to/webvr_camera
  12897. */
  12898. Engine.prototype.disableVR = function () {
  12899. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  12900. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  12901. }
  12902. };
  12903. Engine.prototype._getVRDisplaysAsync = function () {
  12904. var _this = this;
  12905. return new Promise(function (res, rej) {
  12906. if (navigator.getVRDisplays) {
  12907. navigator.getVRDisplays().then(function (devices) {
  12908. _this._vrSupported = true;
  12909. // note that devices may actually be an empty array. This is fine;
  12910. // we expect this._vrDisplay to be undefined in this case.
  12911. _this._vrDisplay = devices[0];
  12912. res({
  12913. vrDisplay: _this._vrDisplay,
  12914. vrSupported: _this._vrSupported
  12915. });
  12916. });
  12917. }
  12918. else {
  12919. _this._vrDisplay = undefined;
  12920. _this._vrSupported = false;
  12921. res({
  12922. vrDisplay: _this._vrDisplay,
  12923. vrSupported: _this._vrSupported
  12924. });
  12925. }
  12926. });
  12927. };
  12928. /**
  12929. * Binds the frame buffer to the specified texture.
  12930. * @param texture The texture to render to or null for the default canvas
  12931. * @param faceIndex The face of the texture to render to in case of cube texture
  12932. * @param requiredWidth The width of the target to render to
  12933. * @param requiredHeight The height of the target to render to
  12934. * @param forceFullscreenViewport Forces the viewport to be the entire texture/screen if true
  12935. * @param depthStencilTexture The depth stencil texture to use to render
  12936. * @param lodLevel defines le lod level to bind to the frame buffer
  12937. */
  12938. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport, depthStencilTexture, lodLevel) {
  12939. if (lodLevel === void 0) { lodLevel = 0; }
  12940. if (this._currentRenderTarget) {
  12941. this.unBindFramebuffer(this._currentRenderTarget);
  12942. }
  12943. this._currentRenderTarget = texture;
  12944. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  12945. var gl = this._gl;
  12946. if (texture.isCube) {
  12947. if (faceIndex === undefined) {
  12948. faceIndex = 0;
  12949. }
  12950. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, lodLevel);
  12951. if (depthStencilTexture) {
  12952. if (depthStencilTexture._generateStencilBuffer) {
  12953. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, lodLevel);
  12954. }
  12955. else {
  12956. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, lodLevel);
  12957. }
  12958. }
  12959. }
  12960. if (this._cachedViewport && !forceFullscreenViewport) {
  12961. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  12962. }
  12963. else {
  12964. if (!requiredWidth) {
  12965. requiredWidth = texture.width;
  12966. if (lodLevel) {
  12967. requiredWidth = requiredWidth / Math.pow(2, lodLevel);
  12968. }
  12969. }
  12970. if (!requiredHeight) {
  12971. requiredHeight = texture.height;
  12972. if (lodLevel) {
  12973. requiredHeight = requiredHeight / Math.pow(2, lodLevel);
  12974. }
  12975. }
  12976. this._viewport(0, 0, requiredWidth, requiredHeight);
  12977. }
  12978. this.wipeCaches();
  12979. };
  12980. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  12981. if (this._currentFramebuffer !== framebuffer) {
  12982. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  12983. this._currentFramebuffer = framebuffer;
  12984. }
  12985. };
  12986. /**
  12987. * Unbind the current render target texture from the webGL context
  12988. * @param texture defines the render target texture to unbind
  12989. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  12990. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  12991. */
  12992. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  12993. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  12994. this._currentRenderTarget = null;
  12995. // If MSAA, we need to bitblt back to main texture
  12996. var gl = this._gl;
  12997. if (texture._MSAAFramebuffer) {
  12998. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  12999. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  13000. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  13001. }
  13002. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  13003. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  13004. gl.generateMipmap(gl.TEXTURE_2D);
  13005. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13006. }
  13007. if (onBeforeUnbind) {
  13008. if (texture._MSAAFramebuffer) {
  13009. // Bind the correct framebuffer
  13010. this.bindUnboundFramebuffer(texture._framebuffer);
  13011. }
  13012. onBeforeUnbind();
  13013. }
  13014. this.bindUnboundFramebuffer(null);
  13015. };
  13016. /**
  13017. * Unbind a list of render target textures from the webGL context
  13018. * This is used only when drawBuffer extension or webGL2 are active
  13019. * @param textures defines the render target textures to unbind
  13020. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  13021. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  13022. */
  13023. Engine.prototype.unBindMultiColorAttachmentFramebuffer = function (textures, disableGenerateMipMaps, onBeforeUnbind) {
  13024. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  13025. this._currentRenderTarget = null;
  13026. // If MSAA, we need to bitblt back to main texture
  13027. var gl = this._gl;
  13028. if (textures[0]._MSAAFramebuffer) {
  13029. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, textures[0]._MSAAFramebuffer);
  13030. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, textures[0]._framebuffer);
  13031. var attachments = textures[0]._attachments;
  13032. if (!attachments) {
  13033. attachments = new Array(textures.length);
  13034. textures[0]._attachments = attachments;
  13035. }
  13036. for (var i = 0; i < textures.length; i++) {
  13037. var texture = textures[i];
  13038. for (var j = 0; j < attachments.length; j++) {
  13039. attachments[j] = gl.NONE;
  13040. }
  13041. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13042. gl.readBuffer(attachments[i]);
  13043. gl.drawBuffers(attachments);
  13044. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  13045. }
  13046. for (var i = 0; i < attachments.length; i++) {
  13047. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13048. }
  13049. gl.drawBuffers(attachments);
  13050. }
  13051. for (var i = 0; i < textures.length; i++) {
  13052. var texture = textures[i];
  13053. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  13054. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  13055. gl.generateMipmap(gl.TEXTURE_2D);
  13056. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13057. }
  13058. }
  13059. if (onBeforeUnbind) {
  13060. if (textures[0]._MSAAFramebuffer) {
  13061. // Bind the correct framebuffer
  13062. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  13063. }
  13064. onBeforeUnbind();
  13065. }
  13066. this.bindUnboundFramebuffer(null);
  13067. };
  13068. /**
  13069. * Force the mipmap generation for the given render target texture
  13070. * @param texture defines the render target texture to use
  13071. */
  13072. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  13073. if (texture.generateMipMaps) {
  13074. var gl = this._gl;
  13075. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13076. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  13077. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13078. }
  13079. };
  13080. /**
  13081. * Force a webGL flush (ie. a flush of all waiting webGL commands)
  13082. */
  13083. Engine.prototype.flushFramebuffer = function () {
  13084. this._gl.flush();
  13085. };
  13086. /**
  13087. * Unbind the current render target and bind the default framebuffer
  13088. */
  13089. Engine.prototype.restoreDefaultFramebuffer = function () {
  13090. if (this._currentRenderTarget) {
  13091. this.unBindFramebuffer(this._currentRenderTarget);
  13092. }
  13093. else {
  13094. this.bindUnboundFramebuffer(null);
  13095. }
  13096. if (this._cachedViewport) {
  13097. this.setViewport(this._cachedViewport);
  13098. }
  13099. this.wipeCaches();
  13100. };
  13101. // UBOs
  13102. /**
  13103. * Create an uniform buffer
  13104. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13105. * @param elements defines the content of the uniform buffer
  13106. * @returns the webGL uniform buffer
  13107. */
  13108. Engine.prototype.createUniformBuffer = function (elements) {
  13109. var ubo = this._gl.createBuffer();
  13110. if (!ubo) {
  13111. throw new Error("Unable to create uniform buffer");
  13112. }
  13113. this.bindUniformBuffer(ubo);
  13114. if (elements instanceof Float32Array) {
  13115. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  13116. }
  13117. else {
  13118. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  13119. }
  13120. this.bindUniformBuffer(null);
  13121. ubo.references = 1;
  13122. return ubo;
  13123. };
  13124. /**
  13125. * Create a dynamic uniform buffer
  13126. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13127. * @param elements defines the content of the uniform buffer
  13128. * @returns the webGL uniform buffer
  13129. */
  13130. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  13131. var ubo = this._gl.createBuffer();
  13132. if (!ubo) {
  13133. throw new Error("Unable to create dynamic uniform buffer");
  13134. }
  13135. this.bindUniformBuffer(ubo);
  13136. if (elements instanceof Float32Array) {
  13137. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  13138. }
  13139. else {
  13140. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  13141. }
  13142. this.bindUniformBuffer(null);
  13143. ubo.references = 1;
  13144. return ubo;
  13145. };
  13146. /**
  13147. * Update an existing uniform buffer
  13148. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13149. * @param uniformBuffer defines the target uniform buffer
  13150. * @param elements defines the content to update
  13151. * @param offset defines the offset in the uniform buffer where update should start
  13152. * @param count defines the size of the data to update
  13153. */
  13154. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  13155. this.bindUniformBuffer(uniformBuffer);
  13156. if (offset === undefined) {
  13157. offset = 0;
  13158. }
  13159. if (count === undefined) {
  13160. if (elements instanceof Float32Array) {
  13161. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  13162. }
  13163. else {
  13164. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  13165. }
  13166. }
  13167. else {
  13168. if (elements instanceof Float32Array) {
  13169. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  13170. }
  13171. else {
  13172. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  13173. }
  13174. }
  13175. this.bindUniformBuffer(null);
  13176. };
  13177. // VBOs
  13178. Engine.prototype._resetVertexBufferBinding = function () {
  13179. this.bindArrayBuffer(null);
  13180. this._cachedVertexBuffers = null;
  13181. };
  13182. /**
  13183. * Creates a vertex buffer
  13184. * @param data the data for the vertex buffer
  13185. * @returns the new WebGL static buffer
  13186. */
  13187. Engine.prototype.createVertexBuffer = function (data) {
  13188. var vbo = this._gl.createBuffer();
  13189. if (!vbo) {
  13190. throw new Error("Unable to create vertex buffer");
  13191. }
  13192. this.bindArrayBuffer(vbo);
  13193. if (data instanceof Array) {
  13194. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.STATIC_DRAW);
  13195. }
  13196. else {
  13197. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.STATIC_DRAW);
  13198. }
  13199. this._resetVertexBufferBinding();
  13200. vbo.references = 1;
  13201. return vbo;
  13202. };
  13203. /**
  13204. * Creates a dynamic vertex buffer
  13205. * @param data the data for the dynamic vertex buffer
  13206. * @returns the new WebGL dynamic buffer
  13207. */
  13208. Engine.prototype.createDynamicVertexBuffer = function (data) {
  13209. var vbo = this._gl.createBuffer();
  13210. if (!vbo) {
  13211. throw new Error("Unable to create dynamic vertex buffer");
  13212. }
  13213. this.bindArrayBuffer(vbo);
  13214. if (data instanceof Array) {
  13215. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.DYNAMIC_DRAW);
  13216. }
  13217. else {
  13218. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.DYNAMIC_DRAW);
  13219. }
  13220. this._resetVertexBufferBinding();
  13221. vbo.references = 1;
  13222. return vbo;
  13223. };
  13224. /**
  13225. * Update a dynamic index buffer
  13226. * @param indexBuffer defines the target index buffer
  13227. * @param indices defines the data to update
  13228. * @param offset defines the offset in the target index buffer where update should start
  13229. */
  13230. Engine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  13231. if (offset === void 0) { offset = 0; }
  13232. // Force cache update
  13233. this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
  13234. this.bindIndexBuffer(indexBuffer);
  13235. var arrayBuffer;
  13236. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  13237. arrayBuffer = indices;
  13238. }
  13239. else {
  13240. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  13241. }
  13242. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  13243. this._resetIndexBufferBinding();
  13244. };
  13245. /**
  13246. * Updates a dynamic vertex buffer.
  13247. * @param vertexBuffer the vertex buffer to update
  13248. * @param data the data used to update the vertex buffer
  13249. * @param byteOffset the byte offset of the data
  13250. * @param byteLength the byte length of the data
  13251. */
  13252. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, data, byteOffset, byteLength) {
  13253. this.bindArrayBuffer(vertexBuffer);
  13254. if (byteOffset === undefined) {
  13255. byteOffset = 0;
  13256. }
  13257. if (byteLength === undefined) {
  13258. if (data instanceof Array) {
  13259. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, new Float32Array(data));
  13260. }
  13261. else {
  13262. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, data);
  13263. }
  13264. }
  13265. else {
  13266. if (data instanceof Array) {
  13267. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(data).subarray(byteOffset, byteOffset + byteLength));
  13268. }
  13269. else {
  13270. if (data instanceof ArrayBuffer) {
  13271. data = new Uint8Array(data, byteOffset, byteLength);
  13272. }
  13273. else {
  13274. data = new Uint8Array(data.buffer, data.byteOffset + byteOffset, byteLength);
  13275. }
  13276. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13277. }
  13278. }
  13279. this._resetVertexBufferBinding();
  13280. };
  13281. Engine.prototype._resetIndexBufferBinding = function () {
  13282. this.bindIndexBuffer(null);
  13283. this._cachedIndexBuffer = null;
  13284. };
  13285. /**
  13286. * Creates a new index buffer
  13287. * @param indices defines the content of the index buffer
  13288. * @param updatable defines if the index buffer must be updatable
  13289. * @returns a new webGL buffer
  13290. */
  13291. Engine.prototype.createIndexBuffer = function (indices, updatable) {
  13292. var vbo = this._gl.createBuffer();
  13293. if (!vbo) {
  13294. throw new Error("Unable to create index buffer");
  13295. }
  13296. this.bindIndexBuffer(vbo);
  13297. // Check for 32 bits indices
  13298. var arrayBuffer;
  13299. var need32Bits = false;
  13300. if (indices instanceof Uint16Array) {
  13301. arrayBuffer = indices;
  13302. }
  13303. else {
  13304. //check 32 bit support
  13305. if (this._caps.uintIndices) {
  13306. if (indices instanceof Uint32Array) {
  13307. arrayBuffer = indices;
  13308. need32Bits = true;
  13309. }
  13310. else {
  13311. //number[] or Int32Array, check if 32 bit is necessary
  13312. for (var index = 0; index < indices.length; index++) {
  13313. if (indices[index] > 65535) {
  13314. need32Bits = true;
  13315. break;
  13316. }
  13317. }
  13318. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  13319. }
  13320. }
  13321. else {
  13322. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  13323. arrayBuffer = new Uint16Array(indices);
  13324. }
  13325. }
  13326. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  13327. this._resetIndexBufferBinding();
  13328. vbo.references = 1;
  13329. vbo.is32Bits = need32Bits;
  13330. return vbo;
  13331. };
  13332. /**
  13333. * Bind a webGL buffer to the webGL context
  13334. * @param buffer defines the buffer to bind
  13335. */
  13336. Engine.prototype.bindArrayBuffer = function (buffer) {
  13337. if (!this._vaoRecordInProgress) {
  13338. this._unbindVertexArrayObject();
  13339. }
  13340. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  13341. };
  13342. /**
  13343. * Bind an uniform buffer to the current webGL context
  13344. * @param buffer defines the buffer to bind
  13345. */
  13346. Engine.prototype.bindUniformBuffer = function (buffer) {
  13347. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  13348. };
  13349. /**
  13350. * Bind a buffer to the current webGL context at a given location
  13351. * @param buffer defines the buffer to bind
  13352. * @param location defines the index where to bind the buffer
  13353. */
  13354. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  13355. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  13356. };
  13357. /**
  13358. * Bind a specific block at a given index in a specific shader program
  13359. * @param shaderProgram defines the shader program
  13360. * @param blockName defines the block name
  13361. * @param index defines the index where to bind the block
  13362. */
  13363. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  13364. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  13365. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  13366. };
  13367. ;
  13368. Engine.prototype.bindIndexBuffer = function (buffer) {
  13369. if (!this._vaoRecordInProgress) {
  13370. this._unbindVertexArrayObject();
  13371. }
  13372. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  13373. };
  13374. Engine.prototype.bindBuffer = function (buffer, target) {
  13375. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  13376. this._gl.bindBuffer(target, buffer);
  13377. this._currentBoundBuffer[target] = buffer;
  13378. }
  13379. };
  13380. /**
  13381. * update the bound buffer with the given data
  13382. * @param data defines the data to update
  13383. */
  13384. Engine.prototype.updateArrayBuffer = function (data) {
  13385. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13386. };
  13387. Engine.prototype._vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  13388. var pointer = this._currentBufferPointers[indx];
  13389. var changed = false;
  13390. if (!pointer.active) {
  13391. changed = true;
  13392. pointer.active = true;
  13393. pointer.index = indx;
  13394. pointer.size = size;
  13395. pointer.type = type;
  13396. pointer.normalized = normalized;
  13397. pointer.stride = stride;
  13398. pointer.offset = offset;
  13399. pointer.buffer = buffer;
  13400. }
  13401. else {
  13402. if (pointer.buffer !== buffer) {
  13403. pointer.buffer = buffer;
  13404. changed = true;
  13405. }
  13406. if (pointer.size !== size) {
  13407. pointer.size = size;
  13408. changed = true;
  13409. }
  13410. if (pointer.type !== type) {
  13411. pointer.type = type;
  13412. changed = true;
  13413. }
  13414. if (pointer.normalized !== normalized) {
  13415. pointer.normalized = normalized;
  13416. changed = true;
  13417. }
  13418. if (pointer.stride !== stride) {
  13419. pointer.stride = stride;
  13420. changed = true;
  13421. }
  13422. if (pointer.offset !== offset) {
  13423. pointer.offset = offset;
  13424. changed = true;
  13425. }
  13426. }
  13427. if (changed || this._vaoRecordInProgress) {
  13428. this.bindArrayBuffer(buffer);
  13429. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  13430. }
  13431. };
  13432. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  13433. if (indexBuffer == null) {
  13434. return;
  13435. }
  13436. if (this._cachedIndexBuffer !== indexBuffer) {
  13437. this._cachedIndexBuffer = indexBuffer;
  13438. this.bindIndexBuffer(indexBuffer);
  13439. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  13440. }
  13441. };
  13442. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  13443. var attributes = effect.getAttributesNames();
  13444. if (!this._vaoRecordInProgress) {
  13445. this._unbindVertexArrayObject();
  13446. }
  13447. this.unbindAllAttributes();
  13448. for (var index = 0; index < attributes.length; index++) {
  13449. var order = effect.getAttributeLocation(index);
  13450. if (order >= 0) {
  13451. var vertexBuffer = vertexBuffers[attributes[index]];
  13452. if (!vertexBuffer) {
  13453. continue;
  13454. }
  13455. this._gl.enableVertexAttribArray(order);
  13456. if (!this._vaoRecordInProgress) {
  13457. this._vertexAttribArraysEnabled[order] = true;
  13458. }
  13459. var buffer = vertexBuffer.getBuffer();
  13460. if (buffer) {
  13461. this._vertexAttribPointer(buffer, order, vertexBuffer.getSize(), vertexBuffer.type, vertexBuffer.normalized, vertexBuffer.byteStride, vertexBuffer.byteOffset);
  13462. if (vertexBuffer.getIsInstanced()) {
  13463. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  13464. if (!this._vaoRecordInProgress) {
  13465. this._currentInstanceLocations.push(order);
  13466. this._currentInstanceBuffers.push(buffer);
  13467. }
  13468. }
  13469. }
  13470. }
  13471. }
  13472. };
  13473. /**
  13474. * Records a vertex array object
  13475. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  13476. * @param vertexBuffers defines the list of vertex buffers to store
  13477. * @param indexBuffer defines the index buffer to store
  13478. * @param effect defines the effect to store
  13479. * @returns the new vertex array object
  13480. */
  13481. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  13482. var vao = this._gl.createVertexArray();
  13483. this._vaoRecordInProgress = true;
  13484. this._gl.bindVertexArray(vao);
  13485. this._mustWipeVertexAttributes = true;
  13486. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  13487. this.bindIndexBuffer(indexBuffer);
  13488. this._vaoRecordInProgress = false;
  13489. this._gl.bindVertexArray(null);
  13490. return vao;
  13491. };
  13492. /**
  13493. * Bind a specific vertex array object
  13494. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  13495. * @param vertexArrayObject defines the vertex array object to bind
  13496. * @param indexBuffer defines the index buffer to bind
  13497. */
  13498. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  13499. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  13500. this._cachedVertexArrayObject = vertexArrayObject;
  13501. this._gl.bindVertexArray(vertexArrayObject);
  13502. this._cachedVertexBuffers = null;
  13503. this._cachedIndexBuffer = null;
  13504. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  13505. this._mustWipeVertexAttributes = true;
  13506. }
  13507. };
  13508. /**
  13509. * Bind webGl buffers directly to the webGL context
  13510. * @param vertexBuffer defines the vertex buffer to bind
  13511. * @param indexBuffer defines the index buffer to bind
  13512. * @param vertexDeclaration defines the vertex declaration to use with the vertex buffer
  13513. * @param vertexStrideSize defines the vertex stride of the vertex buffer
  13514. * @param effect defines the effect associated with the vertex buffer
  13515. */
  13516. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  13517. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  13518. this._cachedVertexBuffers = vertexBuffer;
  13519. this._cachedEffectForVertexBuffers = effect;
  13520. var attributesCount = effect.getAttributesCount();
  13521. this._unbindVertexArrayObject();
  13522. this.unbindAllAttributes();
  13523. var offset = 0;
  13524. for (var index = 0; index < attributesCount; index++) {
  13525. if (index < vertexDeclaration.length) {
  13526. var order = effect.getAttributeLocation(index);
  13527. if (order >= 0) {
  13528. this._gl.enableVertexAttribArray(order);
  13529. this._vertexAttribArraysEnabled[order] = true;
  13530. this._vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  13531. }
  13532. offset += vertexDeclaration[index] * 4;
  13533. }
  13534. }
  13535. }
  13536. this._bindIndexBufferWithCache(indexBuffer);
  13537. };
  13538. Engine.prototype._unbindVertexArrayObject = function () {
  13539. if (!this._cachedVertexArrayObject) {
  13540. return;
  13541. }
  13542. this._cachedVertexArrayObject = null;
  13543. this._gl.bindVertexArray(null);
  13544. };
  13545. /**
  13546. * Bind a list of vertex buffers to the webGL context
  13547. * @param vertexBuffers defines the list of vertex buffers to bind
  13548. * @param indexBuffer defines the index buffer to bind
  13549. * @param effect defines the effect associated with the vertex buffers
  13550. */
  13551. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  13552. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  13553. this._cachedVertexBuffers = vertexBuffers;
  13554. this._cachedEffectForVertexBuffers = effect;
  13555. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  13556. }
  13557. this._bindIndexBufferWithCache(indexBuffer);
  13558. };
  13559. /**
  13560. * Unbind all instance attributes
  13561. */
  13562. Engine.prototype.unbindInstanceAttributes = function () {
  13563. var boundBuffer;
  13564. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  13565. var instancesBuffer = this._currentInstanceBuffers[i];
  13566. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  13567. boundBuffer = instancesBuffer;
  13568. this.bindArrayBuffer(instancesBuffer);
  13569. }
  13570. var offsetLocation = this._currentInstanceLocations[i];
  13571. this._gl.vertexAttribDivisor(offsetLocation, 0);
  13572. }
  13573. this._currentInstanceBuffers.length = 0;
  13574. this._currentInstanceLocations.length = 0;
  13575. };
  13576. /**
  13577. * Release and free the memory of a vertex array object
  13578. * @param vao defines the vertex array object to delete
  13579. */
  13580. Engine.prototype.releaseVertexArrayObject = function (vao) {
  13581. this._gl.deleteVertexArray(vao);
  13582. };
  13583. /** @hidden */
  13584. Engine.prototype._releaseBuffer = function (buffer) {
  13585. buffer.references--;
  13586. if (buffer.references === 0) {
  13587. this._gl.deleteBuffer(buffer);
  13588. return true;
  13589. }
  13590. return false;
  13591. };
  13592. /**
  13593. * Creates a webGL buffer to use with instanciation
  13594. * @param capacity defines the size of the buffer
  13595. * @returns the webGL buffer
  13596. */
  13597. Engine.prototype.createInstancesBuffer = function (capacity) {
  13598. var buffer = this._gl.createBuffer();
  13599. if (!buffer) {
  13600. throw new Error("Unable to create instance buffer");
  13601. }
  13602. buffer.capacity = capacity;
  13603. this.bindArrayBuffer(buffer);
  13604. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  13605. return buffer;
  13606. };
  13607. /**
  13608. * Delete a webGL buffer used with instanciation
  13609. * @param buffer defines the webGL buffer to delete
  13610. */
  13611. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  13612. this._gl.deleteBuffer(buffer);
  13613. };
  13614. /**
  13615. * Update the content of a webGL buffer used with instanciation and bind it to the webGL context
  13616. * @param instancesBuffer defines the webGL buffer to update and bind
  13617. * @param data defines the data to store in the buffer
  13618. * @param offsetLocations defines the offsets or attributes information used to determine where data must be stored in the buffer
  13619. */
  13620. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  13621. this.bindArrayBuffer(instancesBuffer);
  13622. if (data) {
  13623. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13624. }
  13625. if (offsetLocations[0].index !== undefined) {
  13626. var stride = 0;
  13627. for (var i = 0; i < offsetLocations.length; i++) {
  13628. var ai = offsetLocations[i];
  13629. stride += ai.attributeSize * 4;
  13630. }
  13631. for (var i = 0; i < offsetLocations.length; i++) {
  13632. var ai = offsetLocations[i];
  13633. if (!this._vertexAttribArraysEnabled[ai.index]) {
  13634. this._gl.enableVertexAttribArray(ai.index);
  13635. this._vertexAttribArraysEnabled[ai.index] = true;
  13636. }
  13637. this._vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  13638. this._gl.vertexAttribDivisor(ai.index, 1);
  13639. this._currentInstanceLocations.push(ai.index);
  13640. this._currentInstanceBuffers.push(instancesBuffer);
  13641. }
  13642. }
  13643. else {
  13644. for (var index = 0; index < 4; index++) {
  13645. var offsetLocation = offsetLocations[index];
  13646. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  13647. this._gl.enableVertexAttribArray(offsetLocation);
  13648. this._vertexAttribArraysEnabled[offsetLocation] = true;
  13649. }
  13650. this._vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  13651. this._gl.vertexAttribDivisor(offsetLocation, 1);
  13652. this._currentInstanceLocations.push(offsetLocation);
  13653. this._currentInstanceBuffers.push(instancesBuffer);
  13654. }
  13655. }
  13656. };
  13657. /**
  13658. * Apply all cached states (depth, culling, stencil and alpha)
  13659. */
  13660. Engine.prototype.applyStates = function () {
  13661. this._depthCullingState.apply(this._gl);
  13662. this._stencilState.apply(this._gl);
  13663. this._alphaState.apply(this._gl);
  13664. };
  13665. /**
  13666. * Send a draw order
  13667. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  13668. * @param indexStart defines the starting index
  13669. * @param indexCount defines the number of index to draw
  13670. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13671. */
  13672. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  13673. this.drawElementsType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, indexStart, indexCount, instancesCount);
  13674. };
  13675. /**
  13676. * Draw a list of points
  13677. * @param verticesStart defines the index of first vertex to draw
  13678. * @param verticesCount defines the count of vertices to draw
  13679. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13680. */
  13681. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  13682. this.drawArraysType(BABYLON.Material.PointFillMode, verticesStart, verticesCount, instancesCount);
  13683. };
  13684. /**
  13685. * Draw a list of unindexed primitives
  13686. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  13687. * @param verticesStart defines the index of first vertex to draw
  13688. * @param verticesCount defines the count of vertices to draw
  13689. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13690. */
  13691. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  13692. this.drawArraysType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, verticesStart, verticesCount, instancesCount);
  13693. };
  13694. /**
  13695. * Draw a list of indexed primitives
  13696. * @param fillMode defines the primitive to use
  13697. * @param indexStart defines the starting index
  13698. * @param indexCount defines the number of index to draw
  13699. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13700. */
  13701. Engine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  13702. // Apply states
  13703. this.applyStates();
  13704. this._drawCalls.addCount(1, false);
  13705. // Render
  13706. var drawMode = this._drawMode(fillMode);
  13707. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  13708. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  13709. if (instancesCount) {
  13710. this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount);
  13711. }
  13712. else {
  13713. this._gl.drawElements(drawMode, indexCount, indexFormat, indexStart * mult);
  13714. }
  13715. };
  13716. /**
  13717. * Draw a list of unindexed primitives
  13718. * @param fillMode defines the primitive to use
  13719. * @param verticesStart defines the index of first vertex to draw
  13720. * @param verticesCount defines the count of vertices to draw
  13721. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13722. */
  13723. Engine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  13724. // Apply states
  13725. this.applyStates();
  13726. this._drawCalls.addCount(1, false);
  13727. var drawMode = this._drawMode(fillMode);
  13728. if (instancesCount) {
  13729. this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount);
  13730. }
  13731. else {
  13732. this._gl.drawArrays(drawMode, verticesStart, verticesCount);
  13733. }
  13734. };
  13735. Engine.prototype._drawMode = function (fillMode) {
  13736. switch (fillMode) {
  13737. // Triangle views
  13738. case BABYLON.Material.TriangleFillMode:
  13739. return this._gl.TRIANGLES;
  13740. case BABYLON.Material.PointFillMode:
  13741. return this._gl.POINTS;
  13742. case BABYLON.Material.WireFrameFillMode:
  13743. return this._gl.LINES;
  13744. // Draw modes
  13745. case BABYLON.Material.PointListDrawMode:
  13746. return this._gl.POINTS;
  13747. case BABYLON.Material.LineListDrawMode:
  13748. return this._gl.LINES;
  13749. case BABYLON.Material.LineLoopDrawMode:
  13750. return this._gl.LINE_LOOP;
  13751. case BABYLON.Material.LineStripDrawMode:
  13752. return this._gl.LINE_STRIP;
  13753. case BABYLON.Material.TriangleStripDrawMode:
  13754. return this._gl.TRIANGLE_STRIP;
  13755. case BABYLON.Material.TriangleFanDrawMode:
  13756. return this._gl.TRIANGLE_FAN;
  13757. default:
  13758. return this._gl.TRIANGLES;
  13759. }
  13760. };
  13761. // Shaders
  13762. /** @hidden */
  13763. Engine.prototype._releaseEffect = function (effect) {
  13764. if (this._compiledEffects[effect._key]) {
  13765. delete this._compiledEffects[effect._key];
  13766. this._deleteProgram(effect.getProgram());
  13767. }
  13768. };
  13769. /** @hidden */
  13770. Engine.prototype._deleteProgram = function (program) {
  13771. if (program) {
  13772. program.__SPECTOR_rebuildProgram = null;
  13773. if (program.transformFeedback) {
  13774. this.deleteTransformFeedback(program.transformFeedback);
  13775. program.transformFeedback = null;
  13776. }
  13777. this._gl.deleteProgram(program);
  13778. }
  13779. };
  13780. /**
  13781. * Create a new effect (used to store vertex/fragment shaders)
  13782. * @param baseName defines the base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  13783. * @param attributesNamesOrOptions defines either a list of attribute names or an EffectCreationOptions object
  13784. * @param uniformsNamesOrEngine defines either a list of uniform names or the engine to use
  13785. * @param samplers defines an array of string used to represent textures
  13786. * @param defines defines the string containing the defines to use to compile the shaders
  13787. * @param fallbacks defines the list of potential fallbacks to use if shader conmpilation fails
  13788. * @param onCompiled defines a function to call when the effect creation is successful
  13789. * @param onError defines a function to call when the effect creation has failed
  13790. * @param indexParameters defines an object containing the index values to use to compile shaders (like the maximum number of simultaneous lights)
  13791. * @returns the new Effect
  13792. */
  13793. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  13794. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  13795. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  13796. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  13797. if (this._compiledEffects[name]) {
  13798. var compiledEffect = this._compiledEffects[name];
  13799. if (onCompiled && compiledEffect.isReady()) {
  13800. onCompiled(compiledEffect);
  13801. }
  13802. return compiledEffect;
  13803. }
  13804. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  13805. effect._key = name;
  13806. this._compiledEffects[name] = effect;
  13807. return effect;
  13808. };
  13809. Engine.prototype._compileShader = function (source, type, defines, shaderVersion) {
  13810. return this._compileRawShader(shaderVersion + (defines ? defines + "\n" : "") + source, type);
  13811. };
  13812. ;
  13813. Engine.prototype._compileRawShader = function (source, type) {
  13814. var gl = this._gl;
  13815. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  13816. gl.shaderSource(shader, source);
  13817. gl.compileShader(shader);
  13818. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  13819. var log = gl.getShaderInfoLog(shader);
  13820. if (log) {
  13821. throw new Error(log);
  13822. }
  13823. }
  13824. if (!shader) {
  13825. throw new Error("Something went wrong while compile the shader.");
  13826. }
  13827. return shader;
  13828. };
  13829. ;
  13830. /**
  13831. * Directly creates a webGL program
  13832. * @param vertexCode defines the vertex shader code to use
  13833. * @param fragmentCode defines the fragment shader code to use
  13834. * @param context defines the webGL context to use (if not set, the current one will be used)
  13835. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  13836. * @returns the new webGL program
  13837. */
  13838. Engine.prototype.createRawShaderProgram = function (vertexCode, fragmentCode, context, transformFeedbackVaryings) {
  13839. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13840. context = context || this._gl;
  13841. var vertexShader = this._compileRawShader(vertexCode, "vertex");
  13842. var fragmentShader = this._compileRawShader(fragmentCode, "fragment");
  13843. return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  13844. };
  13845. /**
  13846. * Creates a webGL program
  13847. * @param vertexCode defines the vertex shader code to use
  13848. * @param fragmentCode defines the fragment shader code to use
  13849. * @param defines defines the string containing the defines to use to compile the shaders
  13850. * @param context defines the webGL context to use (if not set, the current one will be used)
  13851. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  13852. * @returns the new webGL program
  13853. */
  13854. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context, transformFeedbackVaryings) {
  13855. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13856. context = context || this._gl;
  13857. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  13858. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  13859. var vertexShader = this._compileShader(vertexCode, "vertex", defines, shaderVersion);
  13860. var fragmentShader = this._compileShader(fragmentCode, "fragment", defines, shaderVersion);
  13861. var program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  13862. this.onAfterShaderCompilationObservable.notifyObservers(this);
  13863. return program;
  13864. };
  13865. Engine.prototype._createShaderProgram = function (vertexShader, fragmentShader, context, transformFeedbackVaryings) {
  13866. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13867. var shaderProgram = context.createProgram();
  13868. if (!shaderProgram) {
  13869. throw new Error("Unable to create program");
  13870. }
  13871. context.attachShader(shaderProgram, vertexShader);
  13872. context.attachShader(shaderProgram, fragmentShader);
  13873. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  13874. var transformFeedback = this.createTransformFeedback();
  13875. this.bindTransformFeedback(transformFeedback);
  13876. this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
  13877. shaderProgram.transformFeedback = transformFeedback;
  13878. }
  13879. context.linkProgram(shaderProgram);
  13880. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  13881. this.bindTransformFeedback(null);
  13882. }
  13883. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  13884. if (!linked) {
  13885. var error = context.getProgramInfoLog(shaderProgram);
  13886. if (error) {
  13887. throw new Error(error);
  13888. }
  13889. }
  13890. if (this.validateShaderPrograms) {
  13891. context.validateProgram(shaderProgram);
  13892. var validated = context.getProgramParameter(shaderProgram, context.VALIDATE_STATUS);
  13893. if (!validated) {
  13894. var error = context.getProgramInfoLog(shaderProgram);
  13895. if (error) {
  13896. throw new Error(error);
  13897. }
  13898. }
  13899. }
  13900. context.deleteShader(vertexShader);
  13901. context.deleteShader(fragmentShader);
  13902. return shaderProgram;
  13903. };
  13904. /**
  13905. * Gets the list of webGL uniform locations associated with a specific program based on a list of uniform names
  13906. * @param shaderProgram defines the webGL program to use
  13907. * @param uniformsNames defines the list of uniform names
  13908. * @returns an array of webGL uniform locations
  13909. */
  13910. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  13911. var results = new Array();
  13912. for (var index = 0; index < uniformsNames.length; index++) {
  13913. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  13914. }
  13915. return results;
  13916. };
  13917. /**
  13918. * Gets the lsit of active attributes for a given webGL program
  13919. * @param shaderProgram defines the webGL program to use
  13920. * @param attributesNames defines the list of attribute names to get
  13921. * @returns an array of indices indicating the offset of each attribute
  13922. */
  13923. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  13924. var results = [];
  13925. for (var index = 0; index < attributesNames.length; index++) {
  13926. try {
  13927. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  13928. }
  13929. catch (e) {
  13930. results.push(-1);
  13931. }
  13932. }
  13933. return results;
  13934. };
  13935. /**
  13936. * Activates an effect, mkaing it the current one (ie. the one used for rendering)
  13937. * @param effect defines the effect to activate
  13938. */
  13939. Engine.prototype.enableEffect = function (effect) {
  13940. if (!effect || effect === this._currentEffect) {
  13941. return;
  13942. }
  13943. // Use program
  13944. this.bindSamplers(effect);
  13945. this._currentEffect = effect;
  13946. if (effect.onBind) {
  13947. effect.onBind(effect);
  13948. }
  13949. if (effect._onBindObservable) {
  13950. effect._onBindObservable.notifyObservers(effect);
  13951. }
  13952. };
  13953. /**
  13954. * Set the value of an uniform to an array of int32
  13955. * @param uniform defines the webGL uniform location where to store the value
  13956. * @param array defines the array of int32 to store
  13957. */
  13958. Engine.prototype.setIntArray = function (uniform, array) {
  13959. if (!uniform)
  13960. return;
  13961. this._gl.uniform1iv(uniform, array);
  13962. };
  13963. /**
  13964. * Set the value of an uniform to an array of int32 (stored as vec2)
  13965. * @param uniform defines the webGL uniform location where to store the value
  13966. * @param array defines the array of int32 to store
  13967. */
  13968. Engine.prototype.setIntArray2 = function (uniform, array) {
  13969. if (!uniform || array.length % 2 !== 0)
  13970. return;
  13971. this._gl.uniform2iv(uniform, array);
  13972. };
  13973. /**
  13974. * Set the value of an uniform to an array of int32 (stored as vec3)
  13975. * @param uniform defines the webGL uniform location where to store the value
  13976. * @param array defines the array of int32 to store
  13977. */
  13978. Engine.prototype.setIntArray3 = function (uniform, array) {
  13979. if (!uniform || array.length % 3 !== 0)
  13980. return;
  13981. this._gl.uniform3iv(uniform, array);
  13982. };
  13983. /**
  13984. * Set the value of an uniform to an array of int32 (stored as vec4)
  13985. * @param uniform defines the webGL uniform location where to store the value
  13986. * @param array defines the array of int32 to store
  13987. */
  13988. Engine.prototype.setIntArray4 = function (uniform, array) {
  13989. if (!uniform || array.length % 4 !== 0)
  13990. return;
  13991. this._gl.uniform4iv(uniform, array);
  13992. };
  13993. /**
  13994. * Set the value of an uniform to an array of float32
  13995. * @param uniform defines the webGL uniform location where to store the value
  13996. * @param array defines the array of float32 to store
  13997. */
  13998. Engine.prototype.setFloatArray = function (uniform, array) {
  13999. if (!uniform)
  14000. return;
  14001. this._gl.uniform1fv(uniform, array);
  14002. };
  14003. /**
  14004. * Set the value of an uniform to an array of float32 (stored as vec2)
  14005. * @param uniform defines the webGL uniform location where to store the value
  14006. * @param array defines the array of float32 to store
  14007. */
  14008. Engine.prototype.setFloatArray2 = function (uniform, array) {
  14009. if (!uniform || array.length % 2 !== 0)
  14010. return;
  14011. this._gl.uniform2fv(uniform, array);
  14012. };
  14013. /**
  14014. * Set the value of an uniform to an array of float32 (stored as vec3)
  14015. * @param uniform defines the webGL uniform location where to store the value
  14016. * @param array defines the array of float32 to store
  14017. */
  14018. Engine.prototype.setFloatArray3 = function (uniform, array) {
  14019. if (!uniform || array.length % 3 !== 0)
  14020. return;
  14021. this._gl.uniform3fv(uniform, array);
  14022. };
  14023. /**
  14024. * Set the value of an uniform to an array of float32 (stored as vec4)
  14025. * @param uniform defines the webGL uniform location where to store the value
  14026. * @param array defines the array of float32 to store
  14027. */
  14028. Engine.prototype.setFloatArray4 = function (uniform, array) {
  14029. if (!uniform || array.length % 4 !== 0)
  14030. return;
  14031. this._gl.uniform4fv(uniform, array);
  14032. };
  14033. /**
  14034. * Set the value of an uniform to an array of number
  14035. * @param uniform defines the webGL uniform location where to store the value
  14036. * @param array defines the array of number to store
  14037. */
  14038. Engine.prototype.setArray = function (uniform, array) {
  14039. if (!uniform)
  14040. return;
  14041. this._gl.uniform1fv(uniform, array);
  14042. };
  14043. /**
  14044. * Set the value of an uniform to an array of number (stored as vec2)
  14045. * @param uniform defines the webGL uniform location where to store the value
  14046. * @param array defines the array of number to store
  14047. */
  14048. Engine.prototype.setArray2 = function (uniform, array) {
  14049. if (!uniform || array.length % 2 !== 0)
  14050. return;
  14051. this._gl.uniform2fv(uniform, array);
  14052. };
  14053. /**
  14054. * Set the value of an uniform to an array of number (stored as vec3)
  14055. * @param uniform defines the webGL uniform location where to store the value
  14056. * @param array defines the array of number to store
  14057. */
  14058. Engine.prototype.setArray3 = function (uniform, array) {
  14059. if (!uniform || array.length % 3 !== 0)
  14060. return;
  14061. this._gl.uniform3fv(uniform, array);
  14062. };
  14063. /**
  14064. * Set the value of an uniform to an array of number (stored as vec4)
  14065. * @param uniform defines the webGL uniform location where to store the value
  14066. * @param array defines the array of number to store
  14067. */
  14068. Engine.prototype.setArray4 = function (uniform, array) {
  14069. if (!uniform || array.length % 4 !== 0)
  14070. return;
  14071. this._gl.uniform4fv(uniform, array);
  14072. };
  14073. /**
  14074. * Set the value of an uniform to an array of float32 (stored as matrices)
  14075. * @param uniform defines the webGL uniform location where to store the value
  14076. * @param matrices defines the array of float32 to store
  14077. */
  14078. Engine.prototype.setMatrices = function (uniform, matrices) {
  14079. if (!uniform)
  14080. return;
  14081. this._gl.uniformMatrix4fv(uniform, false, matrices);
  14082. };
  14083. /**
  14084. * Set the value of an uniform to a matrix
  14085. * @param uniform defines the webGL uniform location where to store the value
  14086. * @param matrix defines the matrix to store
  14087. */
  14088. Engine.prototype.setMatrix = function (uniform, matrix) {
  14089. if (!uniform)
  14090. return;
  14091. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  14092. };
  14093. /**
  14094. * Set the value of an uniform to a matrix (3x3)
  14095. * @param uniform defines the webGL uniform location where to store the value
  14096. * @param matrix defines the Float32Array representing the 3x3 matrix to store
  14097. */
  14098. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  14099. if (!uniform)
  14100. return;
  14101. this._gl.uniformMatrix3fv(uniform, false, matrix);
  14102. };
  14103. /**
  14104. * Set the value of an uniform to a matrix (2x2)
  14105. * @param uniform defines the webGL uniform location where to store the value
  14106. * @param matrix defines the Float32Array representing the 2x2 matrix to store
  14107. */
  14108. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  14109. if (!uniform)
  14110. return;
  14111. this._gl.uniformMatrix2fv(uniform, false, matrix);
  14112. };
  14113. /**
  14114. * Set the value of an uniform to a number (int)
  14115. * @param uniform defines the webGL uniform location where to store the value
  14116. * @param value defines the int number to store
  14117. */
  14118. Engine.prototype.setInt = function (uniform, value) {
  14119. if (!uniform)
  14120. return;
  14121. this._gl.uniform1i(uniform, value);
  14122. };
  14123. /**
  14124. * Set the value of an uniform to a number (float)
  14125. * @param uniform defines the webGL uniform location where to store the value
  14126. * @param value defines the float number to store
  14127. */
  14128. Engine.prototype.setFloat = function (uniform, value) {
  14129. if (!uniform)
  14130. return;
  14131. this._gl.uniform1f(uniform, value);
  14132. };
  14133. /**
  14134. * Set the value of an uniform to a vec2
  14135. * @param uniform defines the webGL uniform location where to store the value
  14136. * @param x defines the 1st component of the value
  14137. * @param y defines the 2nd component of the value
  14138. */
  14139. Engine.prototype.setFloat2 = function (uniform, x, y) {
  14140. if (!uniform)
  14141. return;
  14142. this._gl.uniform2f(uniform, x, y);
  14143. };
  14144. /**
  14145. * Set the value of an uniform to a vec3
  14146. * @param uniform defines the webGL uniform location where to store the value
  14147. * @param x defines the 1st component of the value
  14148. * @param y defines the 2nd component of the value
  14149. * @param z defines the 3rd component of the value
  14150. */
  14151. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  14152. if (!uniform)
  14153. return;
  14154. this._gl.uniform3f(uniform, x, y, z);
  14155. };
  14156. /**
  14157. * Set the value of an uniform to a boolean
  14158. * @param uniform defines the webGL uniform location where to store the value
  14159. * @param bool defines the boolean to store
  14160. */
  14161. Engine.prototype.setBool = function (uniform, bool) {
  14162. if (!uniform)
  14163. return;
  14164. this._gl.uniform1i(uniform, bool);
  14165. };
  14166. /**
  14167. * Set the value of an uniform to a vec4
  14168. * @param uniform defines the webGL uniform location where to store the value
  14169. * @param x defines the 1st component of the value
  14170. * @param y defines the 2nd component of the value
  14171. * @param z defines the 3rd component of the value
  14172. * @param w defines the 4th component of the value
  14173. */
  14174. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  14175. if (!uniform)
  14176. return;
  14177. this._gl.uniform4f(uniform, x, y, z, w);
  14178. };
  14179. /**
  14180. * Set the value of an uniform to a Color3
  14181. * @param uniform defines the webGL uniform location where to store the value
  14182. * @param color3 defines the color to store
  14183. */
  14184. Engine.prototype.setColor3 = function (uniform, color3) {
  14185. if (!uniform)
  14186. return;
  14187. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  14188. };
  14189. /**
  14190. * Set the value of an uniform to a Color3 and an alpha value
  14191. * @param uniform defines the webGL uniform location where to store the value
  14192. * @param color3 defines the color to store
  14193. * @param alpha defines the alpha component to store
  14194. */
  14195. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  14196. if (!uniform)
  14197. return;
  14198. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  14199. };
  14200. /**
  14201. * Sets a Color4 on a uniform variable
  14202. * @param uniform defines the uniform location
  14203. * @param color4 defines the value to be set
  14204. */
  14205. Engine.prototype.setDirectColor4 = function (uniform, color4) {
  14206. if (!uniform)
  14207. return;
  14208. this._gl.uniform4f(uniform, color4.r, color4.g, color4.b, color4.a);
  14209. };
  14210. // States
  14211. /**
  14212. * Set various states to the webGL context
  14213. * @param culling defines backface culling state
  14214. * @param zOffset defines the value to apply to zOffset (0 by default)
  14215. * @param force defines if states must be applied even if cache is up to date
  14216. * @param reverseSide defines if culling must be reversed (CCW instead of CW and CW instead of CCW)
  14217. */
  14218. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  14219. if (zOffset === void 0) { zOffset = 0; }
  14220. if (reverseSide === void 0) { reverseSide = false; }
  14221. // Culling
  14222. if (this._depthCullingState.cull !== culling || force) {
  14223. this._depthCullingState.cull = culling;
  14224. }
  14225. // Cull face
  14226. var cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  14227. if (this._depthCullingState.cullFace !== cullFace || force) {
  14228. this._depthCullingState.cullFace = cullFace;
  14229. }
  14230. // Z offset
  14231. this.setZOffset(zOffset);
  14232. // Front face
  14233. var frontFace = reverseSide ? this._gl.CW : this._gl.CCW;
  14234. if (this._depthCullingState.frontFace !== frontFace || force) {
  14235. this._depthCullingState.frontFace = frontFace;
  14236. }
  14237. };
  14238. /**
  14239. * Set the z offset to apply to current rendering
  14240. * @param value defines the offset to apply
  14241. */
  14242. Engine.prototype.setZOffset = function (value) {
  14243. this._depthCullingState.zOffset = value;
  14244. };
  14245. /**
  14246. * Gets the current value of the zOffset
  14247. * @returns the current zOffset state
  14248. */
  14249. Engine.prototype.getZOffset = function () {
  14250. return this._depthCullingState.zOffset;
  14251. };
  14252. /**
  14253. * Enable or disable depth buffering
  14254. * @param enable defines the state to set
  14255. */
  14256. Engine.prototype.setDepthBuffer = function (enable) {
  14257. this._depthCullingState.depthTest = enable;
  14258. };
  14259. /**
  14260. * Gets a boolean indicating if depth writing is enabled
  14261. * @returns the current depth writing state
  14262. */
  14263. Engine.prototype.getDepthWrite = function () {
  14264. return this._depthCullingState.depthMask;
  14265. };
  14266. /**
  14267. * Enable or disable depth writing
  14268. * @param enable defines the state to set
  14269. */
  14270. Engine.prototype.setDepthWrite = function (enable) {
  14271. this._depthCullingState.depthMask = enable;
  14272. };
  14273. /**
  14274. * Enable or disable color writing
  14275. * @param enable defines the state to set
  14276. */
  14277. Engine.prototype.setColorWrite = function (enable) {
  14278. this._gl.colorMask(enable, enable, enable, enable);
  14279. this._colorWrite = enable;
  14280. };
  14281. /**
  14282. * Gets a boolean indicating if color writing is enabled
  14283. * @returns the current color writing state
  14284. */
  14285. Engine.prototype.getColorWrite = function () {
  14286. return this._colorWrite;
  14287. };
  14288. /**
  14289. * Sets alpha constants used by some alpha blending modes
  14290. * @param r defines the red component
  14291. * @param g defines the green component
  14292. * @param b defines the blue component
  14293. * @param a defines the alpha component
  14294. */
  14295. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  14296. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  14297. };
  14298. /**
  14299. * Sets the current alpha mode
  14300. * @param mode defines the mode to use (one of the BABYLON.Engine.ALPHA_XXX)
  14301. * @param noDepthWriteChange defines if depth writing state should remains unchanged (false by default)
  14302. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  14303. */
  14304. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  14305. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  14306. if (this._alphaMode === mode) {
  14307. return;
  14308. }
  14309. switch (mode) {
  14310. case Engine.ALPHA_DISABLE:
  14311. this._alphaState.alphaBlend = false;
  14312. break;
  14313. case Engine.ALPHA_PREMULTIPLIED:
  14314. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  14315. this._alphaState.alphaBlend = true;
  14316. break;
  14317. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  14318. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  14319. this._alphaState.alphaBlend = true;
  14320. break;
  14321. case Engine.ALPHA_COMBINE:
  14322. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  14323. this._alphaState.alphaBlend = true;
  14324. break;
  14325. case Engine.ALPHA_ONEONE:
  14326. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  14327. this._alphaState.alphaBlend = true;
  14328. break;
  14329. case Engine.ALPHA_ADD:
  14330. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  14331. this._alphaState.alphaBlend = true;
  14332. break;
  14333. case Engine.ALPHA_SUBTRACT:
  14334. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  14335. this._alphaState.alphaBlend = true;
  14336. break;
  14337. case Engine.ALPHA_MULTIPLY:
  14338. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  14339. this._alphaState.alphaBlend = true;
  14340. break;
  14341. case Engine.ALPHA_MAXIMIZED:
  14342. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  14343. this._alphaState.alphaBlend = true;
  14344. break;
  14345. case Engine.ALPHA_INTERPOLATE:
  14346. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  14347. this._alphaState.alphaBlend = true;
  14348. break;
  14349. case Engine.ALPHA_SCREENMODE:
  14350. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  14351. this._alphaState.alphaBlend = true;
  14352. break;
  14353. }
  14354. if (!noDepthWriteChange) {
  14355. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  14356. }
  14357. this._alphaMode = mode;
  14358. };
  14359. /**
  14360. * Gets the current alpha mode
  14361. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  14362. * @returns the current alpha mode
  14363. */
  14364. Engine.prototype.getAlphaMode = function () {
  14365. return this._alphaMode;
  14366. };
  14367. // Textures
  14368. /**
  14369. * Clears the list of texture accessible through engine.
  14370. * This can help preventing texture load conflict due to name collision.
  14371. */
  14372. Engine.prototype.clearInternalTexturesCache = function () {
  14373. this._internalTexturesCache = [];
  14374. };
  14375. /**
  14376. * Force the entire cache to be cleared
  14377. * You should not have to use this function unless your engine needs to share the webGL context with another engine
  14378. * @param bruteForce defines a boolean to force clearing ALL caches (including stencil, detoh and alpha states)
  14379. */
  14380. Engine.prototype.wipeCaches = function (bruteForce) {
  14381. if (this.preventCacheWipeBetweenFrames && !bruteForce) {
  14382. return;
  14383. }
  14384. this._currentEffect = null;
  14385. this._viewportCached.x = 0;
  14386. this._viewportCached.y = 0;
  14387. this._viewportCached.z = 0;
  14388. this._viewportCached.w = 0;
  14389. if (bruteForce) {
  14390. this.resetTextureCache();
  14391. this._currentProgram = null;
  14392. this._stencilState.reset();
  14393. this._depthCullingState.reset();
  14394. this.setDepthFunctionToLessOrEqual();
  14395. this._alphaState.reset();
  14396. this._unpackFlipYCached = null;
  14397. }
  14398. this._resetVertexBufferBinding();
  14399. this._cachedIndexBuffer = null;
  14400. this._cachedEffectForVertexBuffers = null;
  14401. this._unbindVertexArrayObject();
  14402. this.bindIndexBuffer(null);
  14403. };
  14404. /**
  14405. * Set the compressed texture format to use, based on the formats you have, and the formats
  14406. * supported by the hardware / browser.
  14407. *
  14408. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  14409. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  14410. * to API arguments needed to compressed textures. This puts the burden on the container
  14411. * generator to house the arcane code for determining these for current & future formats.
  14412. *
  14413. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  14414. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  14415. *
  14416. * Note: The result of this call is not taken into account when a texture is base64.
  14417. *
  14418. * @param formatsAvailable defines the list of those format families you have created
  14419. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  14420. *
  14421. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  14422. * @returns The extension selected.
  14423. */
  14424. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  14425. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  14426. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  14427. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  14428. return this._textureFormatInUse = this._texturesSupported[i];
  14429. }
  14430. }
  14431. }
  14432. // actively set format to nothing, to allow this to be called more than once
  14433. // and possibly fail the 2nd time
  14434. this._textureFormatInUse = null;
  14435. return null;
  14436. };
  14437. Engine.prototype._getSamplingParameters = function (samplingMode, generateMipMaps) {
  14438. var gl = this._gl;
  14439. var magFilter = gl.NEAREST;
  14440. var minFilter = gl.NEAREST;
  14441. switch (samplingMode) {
  14442. case Engine.TEXTURE_BILINEAR_SAMPLINGMODE:
  14443. magFilter = gl.LINEAR;
  14444. if (generateMipMaps) {
  14445. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  14446. }
  14447. else {
  14448. minFilter = gl.LINEAR;
  14449. }
  14450. break;
  14451. case Engine.TEXTURE_TRILINEAR_SAMPLINGMODE:
  14452. magFilter = gl.LINEAR;
  14453. if (generateMipMaps) {
  14454. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  14455. }
  14456. else {
  14457. minFilter = gl.LINEAR;
  14458. }
  14459. break;
  14460. case Engine.TEXTURE_NEAREST_SAMPLINGMODE:
  14461. magFilter = gl.NEAREST;
  14462. if (generateMipMaps) {
  14463. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  14464. }
  14465. else {
  14466. minFilter = gl.NEAREST;
  14467. }
  14468. break;
  14469. case Engine.TEXTURE_NEAREST_NEAREST_MIPNEAREST:
  14470. magFilter = gl.NEAREST;
  14471. if (generateMipMaps) {
  14472. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  14473. }
  14474. else {
  14475. minFilter = gl.NEAREST;
  14476. }
  14477. break;
  14478. case Engine.TEXTURE_NEAREST_LINEAR_MIPNEAREST:
  14479. magFilter = gl.NEAREST;
  14480. if (generateMipMaps) {
  14481. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  14482. }
  14483. else {
  14484. minFilter = gl.LINEAR;
  14485. }
  14486. break;
  14487. case Engine.TEXTURE_NEAREST_LINEAR_MIPLINEAR:
  14488. magFilter = gl.NEAREST;
  14489. if (generateMipMaps) {
  14490. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  14491. }
  14492. else {
  14493. minFilter = gl.LINEAR;
  14494. }
  14495. break;
  14496. case Engine.TEXTURE_NEAREST_LINEAR:
  14497. magFilter = gl.NEAREST;
  14498. minFilter = gl.LINEAR;
  14499. break;
  14500. case Engine.TEXTURE_NEAREST_NEAREST:
  14501. magFilter = gl.NEAREST;
  14502. minFilter = gl.NEAREST;
  14503. break;
  14504. case Engine.TEXTURE_LINEAR_NEAREST_MIPNEAREST:
  14505. magFilter = gl.LINEAR;
  14506. if (generateMipMaps) {
  14507. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  14508. }
  14509. else {
  14510. minFilter = gl.NEAREST;
  14511. }
  14512. break;
  14513. case Engine.TEXTURE_LINEAR_NEAREST_MIPLINEAR:
  14514. magFilter = gl.LINEAR;
  14515. if (generateMipMaps) {
  14516. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  14517. }
  14518. else {
  14519. minFilter = gl.NEAREST;
  14520. }
  14521. break;
  14522. case Engine.TEXTURE_LINEAR_LINEAR:
  14523. magFilter = gl.LINEAR;
  14524. minFilter = gl.LINEAR;
  14525. break;
  14526. case Engine.TEXTURE_LINEAR_NEAREST:
  14527. magFilter = gl.LINEAR;
  14528. minFilter = gl.NEAREST;
  14529. break;
  14530. }
  14531. return {
  14532. min: minFilter,
  14533. mag: magFilter
  14534. };
  14535. };
  14536. Engine.prototype._partialLoadImg = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  14537. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  14538. var img;
  14539. var onload = function () {
  14540. loadedImages[index] = img;
  14541. loadedImages._internalCount++;
  14542. if (scene) {
  14543. scene._removePendingData(img);
  14544. }
  14545. if (loadedImages._internalCount === 6) {
  14546. onfinish(loadedImages);
  14547. }
  14548. };
  14549. var onerror = function (message, exception) {
  14550. if (scene) {
  14551. scene._removePendingData(img);
  14552. }
  14553. if (onErrorCallBack) {
  14554. onErrorCallBack(message, exception);
  14555. }
  14556. };
  14557. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  14558. if (scene) {
  14559. scene._addPendingData(img);
  14560. }
  14561. };
  14562. Engine.prototype._cascadeLoadImgs = function (rootUrl, scene, onfinish, files, onError) {
  14563. if (onError === void 0) { onError = null; }
  14564. var loadedImages = [];
  14565. loadedImages._internalCount = 0;
  14566. for (var index = 0; index < 6; index++) {
  14567. this._partialLoadImg(files[index], index, loadedImages, scene, onfinish, onError);
  14568. }
  14569. };
  14570. ;
  14571. /** @hidden */
  14572. Engine.prototype._createTexture = function () {
  14573. var texture = this._gl.createTexture();
  14574. if (!texture) {
  14575. throw new Error("Unable to create texture");
  14576. }
  14577. return texture;
  14578. };
  14579. /**
  14580. * Usually called from BABYLON.Texture.ts.
  14581. * Passed information to create a WebGLTexture
  14582. * @param urlArg defines a value which contains one of the following:
  14583. * * A conventional http URL, e.g. 'http://...' or 'file://...'
  14584. * * A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  14585. * * An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  14586. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated. Ignored for compressed textures. They must be in the file
  14587. * @param invertY when true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file
  14588. * @param scene needed for loading to the correct scene
  14589. * @param samplingMode mode with should be used sample / access the texture (Default: BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  14590. * @param onLoad optional callback to be called upon successful completion
  14591. * @param onError optional callback to be called upon failure
  14592. * @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
  14593. * @param fallback an internal argument in case the function must be called again, due to etc1 not having alpha capabilities
  14594. * @param format internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures
  14595. * @param forcedExtension defines the extension to use to pick the right loader
  14596. * @returns a InternalTexture for assignment back into BABYLON.Texture
  14597. */
  14598. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallback, format, forcedExtension) {
  14599. var _this = this;
  14600. if (samplingMode === void 0) { samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE; }
  14601. if (onLoad === void 0) { onLoad = null; }
  14602. if (onError === void 0) { onError = null; }
  14603. if (buffer === void 0) { buffer = null; }
  14604. if (fallback === void 0) { fallback = null; }
  14605. if (format === void 0) { format = null; }
  14606. if (forcedExtension === void 0) { forcedExtension = null; }
  14607. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  14608. var fromData = url.substr(0, 5) === "data:";
  14609. var fromBlob = url.substr(0, 5) === "blob:";
  14610. var isBase64 = fromData && url.indexOf(";base64,") !== -1;
  14611. var texture = fallback ? fallback : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  14612. // establish the file extension, if possible
  14613. var lastDot = url.lastIndexOf('.');
  14614. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? url.substring(lastDot).toLowerCase() : "");
  14615. var loader = null;
  14616. for (var _i = 0, _a = Engine._TextureLoaders; _i < _a.length; _i++) {
  14617. var availableLoader = _a[_i];
  14618. if (availableLoader.canLoad(extension, this._textureFormatInUse, fallback, isBase64, buffer ? true : false)) {
  14619. loader = availableLoader;
  14620. break;
  14621. }
  14622. }
  14623. if (loader) {
  14624. url = loader.transformUrl(url, this._textureFormatInUse);
  14625. }
  14626. if (scene) {
  14627. scene._addPendingData(texture);
  14628. }
  14629. texture.url = url;
  14630. texture.generateMipMaps = !noMipmap;
  14631. texture.samplingMode = samplingMode;
  14632. texture.invertY = invertY;
  14633. if (!this._doNotHandleContextLost) {
  14634. // Keep a link to the buffer only if we plan to handle context lost
  14635. texture._buffer = buffer;
  14636. }
  14637. var onLoadObserver = null;
  14638. if (onLoad && !fallback) {
  14639. onLoadObserver = texture.onLoadedObservable.add(onLoad);
  14640. }
  14641. if (!fallback)
  14642. this._internalTexturesCache.push(texture);
  14643. var onInternalError = function (message, exception) {
  14644. if (scene) {
  14645. scene._removePendingData(texture);
  14646. }
  14647. var customFallback = false;
  14648. if (loader) {
  14649. var fallbackUrl = loader.getFallbackTextureUrl(url, _this._textureFormatInUse);
  14650. if (fallbackUrl) {
  14651. // Add Back
  14652. customFallback = true;
  14653. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  14654. }
  14655. }
  14656. if (!customFallback) {
  14657. if (onLoadObserver) {
  14658. texture.onLoadedObservable.remove(onLoadObserver);
  14659. }
  14660. if (BABYLON.Tools.UseFallbackTexture) {
  14661. _this.createTexture(BABYLON.Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  14662. }
  14663. }
  14664. if (onError) {
  14665. onError(message || "Unknown error", exception);
  14666. }
  14667. };
  14668. // processing for non-image formats
  14669. if (loader) {
  14670. var callback = function (data) {
  14671. loader.loadData(data, texture, function (width, height, loadMipmap, isCompressed, done) {
  14672. _this._prepareWebGLTexture(texture, scene, width, height, invertY, !loadMipmap, isCompressed, function () {
  14673. done();
  14674. return false;
  14675. }, samplingMode);
  14676. });
  14677. };
  14678. if (!buffer) {
  14679. this._loadFile(url, callback, undefined, scene ? scene.database : undefined, true, function (request, exception) {
  14680. onInternalError("Unable to load " + (request ? request.responseURL : url, exception));
  14681. });
  14682. }
  14683. else {
  14684. callback(buffer);
  14685. }
  14686. }
  14687. else {
  14688. var onload = function (img) {
  14689. if (fromBlob && !_this._doNotHandleContextLost) {
  14690. // We need to store the image if we need to rebuild the texture
  14691. // in case of a webgl context lost
  14692. texture._buffer = img;
  14693. }
  14694. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  14695. var gl = _this._gl;
  14696. var isPot = (img.width === potWidth && img.height === potHeight);
  14697. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  14698. if (isPot) {
  14699. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  14700. return false;
  14701. }
  14702. var maxTextureSize = _this._caps.maxTextureSize;
  14703. if (img.width > maxTextureSize || img.height > maxTextureSize) {
  14704. _this._prepareWorkingCanvas();
  14705. if (!_this._workingCanvas || !_this._workingContext) {
  14706. return false;
  14707. }
  14708. _this._workingCanvas.width = potWidth;
  14709. _this._workingCanvas.height = potHeight;
  14710. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  14711. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  14712. texture.width = potWidth;
  14713. texture.height = potHeight;
  14714. return false;
  14715. }
  14716. else {
  14717. // Using shaders when possible to rescale because canvas.drawImage is lossy
  14718. var source_1 = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  14719. _this._bindTextureDirectly(gl.TEXTURE_2D, source_1, true);
  14720. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  14721. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  14722. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  14723. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14724. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14725. _this._rescaleTexture(source_1, texture, scene, internalFormat, function () {
  14726. _this._releaseTexture(source_1);
  14727. _this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  14728. continuationCallback();
  14729. });
  14730. }
  14731. return true;
  14732. }, samplingMode);
  14733. };
  14734. if (!fromData || isBase64) {
  14735. if (buffer instanceof HTMLImageElement) {
  14736. onload(buffer);
  14737. }
  14738. else {
  14739. BABYLON.Tools.LoadImage(url, onload, onInternalError, scene ? scene.database : null);
  14740. }
  14741. }
  14742. else if (typeof buffer === "string" || buffer instanceof ArrayBuffer || buffer instanceof Blob) {
  14743. BABYLON.Tools.LoadImage(buffer, onload, onInternalError, scene ? scene.database : null);
  14744. }
  14745. else {
  14746. onload(buffer);
  14747. }
  14748. }
  14749. return texture;
  14750. };
  14751. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  14752. var _this = this;
  14753. var rtt = this.createRenderTargetTexture({
  14754. width: destination.width,
  14755. height: destination.height,
  14756. }, {
  14757. generateMipMaps: false,
  14758. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  14759. samplingMode: Engine.TEXTURE_BILINEAR_SAMPLINGMODE,
  14760. generateDepthBuffer: false,
  14761. generateStencilBuffer: false
  14762. });
  14763. if (!this._rescalePostProcess) {
  14764. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, Engine.TEXTURE_BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  14765. }
  14766. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  14767. _this._rescalePostProcess.onApply = function (effect) {
  14768. effect._bindTexture("textureSampler", source);
  14769. };
  14770. var hostingScene = scene;
  14771. if (!hostingScene) {
  14772. hostingScene = _this.scenes[_this.scenes.length - 1];
  14773. }
  14774. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt, true);
  14775. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination, true);
  14776. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  14777. _this.unBindFramebuffer(rtt);
  14778. _this._releaseTexture(rtt);
  14779. if (onComplete) {
  14780. onComplete();
  14781. }
  14782. });
  14783. };
  14784. /**
  14785. * Update a raw texture
  14786. * @param texture defines the texture to update
  14787. * @param data defines the data to store in the texture
  14788. * @param format defines the format of the data
  14789. * @param invertY defines if data must be stored with Y axis inverted
  14790. * @param compression defines the compression used (null by default)
  14791. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  14792. */
  14793. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression, type) {
  14794. if (compression === void 0) { compression = null; }
  14795. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  14796. if (!texture) {
  14797. return;
  14798. }
  14799. // babylon's internalSizedFomat but gl's texImage2D internalFormat
  14800. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type, format);
  14801. // babylon's internalFormat but gl's texImage2D format
  14802. var internalFormat = this._getInternalFormat(format);
  14803. var textureType = this._getWebGLTextureType(type);
  14804. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14805. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  14806. if (!this._doNotHandleContextLost) {
  14807. texture._bufferView = data;
  14808. texture.format = format;
  14809. texture.type = type;
  14810. texture.invertY = invertY;
  14811. texture._compression = compression;
  14812. }
  14813. if (texture.width % 4 !== 0) {
  14814. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  14815. }
  14816. if (compression && data) {
  14817. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  14818. }
  14819. else {
  14820. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, data);
  14821. }
  14822. if (texture.generateMipMaps) {
  14823. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14824. }
  14825. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14826. // this.resetTextureCache();
  14827. texture.isReady = true;
  14828. };
  14829. /**
  14830. * Creates a raw texture
  14831. * @param data defines the data to store in the texture
  14832. * @param width defines the width of the texture
  14833. * @param height defines the height of the texture
  14834. * @param format defines the format of the data
  14835. * @param generateMipMaps defines if the engine should generate the mip levels
  14836. * @param invertY defines if data must be stored with Y axis inverted
  14837. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  14838. * @param compression defines the compression used (null by default)
  14839. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  14840. * @returns the raw texture inside an InternalTexture
  14841. */
  14842. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression, type) {
  14843. if (compression === void 0) { compression = null; }
  14844. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  14845. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  14846. texture.baseWidth = width;
  14847. texture.baseHeight = height;
  14848. texture.width = width;
  14849. texture.height = height;
  14850. texture.format = format;
  14851. texture.generateMipMaps = generateMipMaps;
  14852. texture.samplingMode = samplingMode;
  14853. texture.invertY = invertY;
  14854. texture._compression = compression;
  14855. texture.type = type;
  14856. if (!this._doNotHandleContextLost) {
  14857. texture._bufferView = data;
  14858. }
  14859. this.updateRawTexture(texture, data, format, invertY, compression, type);
  14860. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14861. // Filters
  14862. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  14863. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  14864. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14865. if (generateMipMaps) {
  14866. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14867. }
  14868. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14869. this._internalTexturesCache.push(texture);
  14870. return texture;
  14871. };
  14872. /** @hidden */
  14873. Engine.prototype._unpackFlipY = function (value) {
  14874. if (this._unpackFlipYCached !== value) {
  14875. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, value ? 1 : 0);
  14876. if (this.enableUnpackFlipYCached) {
  14877. this._unpackFlipYCached = value;
  14878. }
  14879. }
  14880. };
  14881. /** @hidden */
  14882. Engine.prototype._getUnpackAlignement = function () {
  14883. return this._gl.getParameter(this._gl.UNPACK_ALIGNMENT);
  14884. };
  14885. /**
  14886. * Creates a dynamic texture
  14887. * @param width defines the width of the texture
  14888. * @param height defines the height of the texture
  14889. * @param generateMipMaps defines if the engine should generate the mip levels
  14890. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  14891. * @returns the dynamic texture inside an InternalTexture
  14892. */
  14893. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  14894. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  14895. texture.baseWidth = width;
  14896. texture.baseHeight = height;
  14897. if (generateMipMaps) {
  14898. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  14899. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  14900. }
  14901. // this.resetTextureCache();
  14902. texture.width = width;
  14903. texture.height = height;
  14904. texture.isReady = false;
  14905. texture.generateMipMaps = generateMipMaps;
  14906. texture.samplingMode = samplingMode;
  14907. this.updateTextureSamplingMode(samplingMode, texture);
  14908. this._internalTexturesCache.push(texture);
  14909. return texture;
  14910. };
  14911. /**
  14912. * Update the sampling mode of a given texture
  14913. * @param samplingMode defines the required sampling mode
  14914. * @param texture defines the texture to update
  14915. */
  14916. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  14917. var filters = this._getSamplingParameters(samplingMode, texture.generateMipMaps);
  14918. if (texture.isCube) {
  14919. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14920. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14921. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14922. }
  14923. else if (texture.is3D) {
  14924. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14925. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14926. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14927. }
  14928. else {
  14929. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14930. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14931. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14932. }
  14933. texture.samplingMode = samplingMode;
  14934. };
  14935. /**
  14936. * Update the content of a dynamic texture
  14937. * @param texture defines the texture to update
  14938. * @param canvas defines the canvas containing the source
  14939. * @param invertY defines if data must be stored with Y axis inverted
  14940. * @param premulAlpha defines if alpha is stored as premultiplied
  14941. * @param format defines the format of the data
  14942. */
  14943. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  14944. if (premulAlpha === void 0) { premulAlpha = false; }
  14945. if (!texture) {
  14946. return;
  14947. }
  14948. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14949. this._unpackFlipY(invertY);
  14950. if (premulAlpha) {
  14951. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  14952. }
  14953. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  14954. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  14955. if (texture.generateMipMaps) {
  14956. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14957. }
  14958. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14959. if (premulAlpha) {
  14960. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  14961. }
  14962. texture.isReady = true;
  14963. };
  14964. /**
  14965. * Update a video texture
  14966. * @param texture defines the texture to update
  14967. * @param video defines the video element to use
  14968. * @param invertY defines if data must be stored with Y axis inverted
  14969. */
  14970. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  14971. if (!texture || texture._isDisabled) {
  14972. return;
  14973. }
  14974. var wasPreviouslyBound = this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14975. this._unpackFlipY(!invertY); // Video are upside down by default
  14976. try {
  14977. // Testing video texture support
  14978. if (this._videoTextureSupported === undefined) {
  14979. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  14980. if (this._gl.getError() !== 0) {
  14981. this._videoTextureSupported = false;
  14982. }
  14983. else {
  14984. this._videoTextureSupported = true;
  14985. }
  14986. }
  14987. // Copy video through the current working canvas if video texture is not supported
  14988. if (!this._videoTextureSupported) {
  14989. if (!texture._workingCanvas) {
  14990. texture._workingCanvas = document.createElement("canvas");
  14991. var context = texture._workingCanvas.getContext("2d");
  14992. if (!context) {
  14993. throw new Error("Unable to get 2d context");
  14994. }
  14995. texture._workingContext = context;
  14996. texture._workingCanvas.width = texture.width;
  14997. texture._workingCanvas.height = texture.height;
  14998. }
  14999. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  15000. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  15001. }
  15002. else {
  15003. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  15004. }
  15005. if (texture.generateMipMaps) {
  15006. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15007. }
  15008. if (!wasPreviouslyBound) {
  15009. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  15010. }
  15011. // this.resetTextureCache();
  15012. texture.isReady = true;
  15013. }
  15014. catch (ex) {
  15015. // Something unexpected
  15016. // Let's disable the texture
  15017. texture._isDisabled = true;
  15018. }
  15019. };
  15020. /**
  15021. * Updates a depth texture Comparison Mode and Function.
  15022. * If the comparison Function is equal to 0, the mode will be set to none.
  15023. * Otherwise, this only works in webgl 2 and requires a shadow sampler in the shader.
  15024. * @param texture The texture to set the comparison function for
  15025. * @param comparisonFunction The comparison function to set, 0 if no comparison required
  15026. */
  15027. Engine.prototype.updateTextureComparisonFunction = function (texture, comparisonFunction) {
  15028. if (this.webGLVersion === 1) {
  15029. BABYLON.Tools.Error("WebGL 1 does not support texture comparison.");
  15030. return;
  15031. }
  15032. var gl = this._gl;
  15033. if (texture.isCube) {
  15034. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  15035. if (comparisonFunction === 0) {
  15036. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  15037. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  15038. }
  15039. else {
  15040. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  15041. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  15042. }
  15043. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  15044. }
  15045. else {
  15046. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  15047. if (comparisonFunction === 0) {
  15048. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  15049. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  15050. }
  15051. else {
  15052. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  15053. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  15054. }
  15055. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  15056. }
  15057. texture._comparisonFunction = comparisonFunction;
  15058. };
  15059. Engine.prototype._setupDepthStencilTexture = function (internalTexture, size, generateStencil, bilinearFiltering, comparisonFunction) {
  15060. var width = size.width || size;
  15061. var height = size.height || size;
  15062. internalTexture.baseWidth = width;
  15063. internalTexture.baseHeight = height;
  15064. internalTexture.width = width;
  15065. internalTexture.height = height;
  15066. internalTexture.isReady = true;
  15067. internalTexture.samples = 1;
  15068. internalTexture.generateMipMaps = false;
  15069. internalTexture._generateDepthBuffer = true;
  15070. internalTexture._generateStencilBuffer = generateStencil;
  15071. internalTexture.samplingMode = bilinearFiltering ? Engine.TEXTURE_BILINEAR_SAMPLINGMODE : Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15072. internalTexture.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15073. internalTexture._comparisonFunction = comparisonFunction;
  15074. var gl = this._gl;
  15075. var target = internalTexture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  15076. var samplingParameters = this._getSamplingParameters(internalTexture.samplingMode, false);
  15077. gl.texParameteri(target, gl.TEXTURE_MAG_FILTER, samplingParameters.mag);
  15078. gl.texParameteri(target, gl.TEXTURE_MIN_FILTER, samplingParameters.min);
  15079. gl.texParameteri(target, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15080. gl.texParameteri(target, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15081. if (comparisonFunction === 0) {
  15082. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  15083. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  15084. }
  15085. else {
  15086. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  15087. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  15088. }
  15089. };
  15090. /**
  15091. * Creates a depth stencil texture.
  15092. * This is only available in WebGL 2 or with the depth texture extension available.
  15093. * @param size The size of face edge in the texture.
  15094. * @param options The options defining the texture.
  15095. * @returns The texture
  15096. */
  15097. Engine.prototype.createDepthStencilTexture = function (size, options) {
  15098. if (options.isCube) {
  15099. var width = size.width || size;
  15100. return this._createDepthStencilCubeTexture(width, options);
  15101. }
  15102. else {
  15103. return this._createDepthStencilTexture(size, options);
  15104. }
  15105. };
  15106. /**
  15107. * Creates a depth stencil texture.
  15108. * This is only available in WebGL 2 or with the depth texture extension available.
  15109. * @param size The size of face edge in the texture.
  15110. * @param options The options defining the texture.
  15111. * @returns The texture
  15112. */
  15113. Engine.prototype._createDepthStencilTexture = function (size, options) {
  15114. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DEPTHTEXTURE);
  15115. if (!this._caps.depthTextureExtension) {
  15116. BABYLON.Tools.Error("Depth texture is not supported by your browser or hardware.");
  15117. return internalTexture;
  15118. }
  15119. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  15120. var gl = this._gl;
  15121. this._bindTextureDirectly(gl.TEXTURE_2D, internalTexture, true);
  15122. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  15123. if (this.webGLVersion > 1) {
  15124. if (internalOptions.generateStencil) {
  15125. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH24_STENCIL8, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  15126. }
  15127. else {
  15128. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT24, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  15129. }
  15130. }
  15131. else {
  15132. if (internalOptions.generateStencil) {
  15133. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_STENCIL, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  15134. }
  15135. else {
  15136. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  15137. }
  15138. }
  15139. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15140. return internalTexture;
  15141. };
  15142. /**
  15143. * Creates a depth stencil cube texture.
  15144. * This is only available in WebGL 2.
  15145. * @param size The size of face edge in the cube texture.
  15146. * @param options The options defining the cube texture.
  15147. * @returns The cube texture
  15148. */
  15149. Engine.prototype._createDepthStencilCubeTexture = function (size, options) {
  15150. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_UNKNOWN);
  15151. internalTexture.isCube = true;
  15152. if (this.webGLVersion === 1) {
  15153. BABYLON.Tools.Error("Depth cube texture is not supported by WebGL 1.");
  15154. return internalTexture;
  15155. }
  15156. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  15157. var gl = this._gl;
  15158. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, internalTexture, true);
  15159. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  15160. // Create the depth/stencil buffer
  15161. for (var face = 0; face < 6; face++) {
  15162. if (internalOptions.generateStencil) {
  15163. 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);
  15164. }
  15165. else {
  15166. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, gl.DEPTH_COMPONENT24, size, size, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  15167. }
  15168. }
  15169. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15170. return internalTexture;
  15171. };
  15172. /**
  15173. * Sets the frame buffer Depth / Stencil attachement of the render target to the defined depth stencil texture.
  15174. * @param renderTarget The render target to set the frame buffer for
  15175. */
  15176. Engine.prototype.setFrameBufferDepthStencilTexture = function (renderTarget) {
  15177. // Create the framebuffer
  15178. var internalTexture = renderTarget.getInternalTexture();
  15179. if (!internalTexture || !internalTexture._framebuffer || !renderTarget.depthStencilTexture) {
  15180. return;
  15181. }
  15182. var gl = this._gl;
  15183. var depthStencilTexture = renderTarget.depthStencilTexture;
  15184. this.bindUnboundFramebuffer(internalTexture._framebuffer);
  15185. if (depthStencilTexture.isCube) {
  15186. if (depthStencilTexture._generateStencilBuffer) {
  15187. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  15188. }
  15189. else {
  15190. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  15191. }
  15192. }
  15193. else {
  15194. if (depthStencilTexture._generateStencilBuffer) {
  15195. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  15196. }
  15197. else {
  15198. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  15199. }
  15200. }
  15201. this.bindUnboundFramebuffer(null);
  15202. };
  15203. /**
  15204. * Creates a new render target texture
  15205. * @param size defines the size of the texture
  15206. * @param options defines the options used to create the texture
  15207. * @returns a new render target texture stored in an InternalTexture
  15208. */
  15209. Engine.prototype.createRenderTargetTexture = function (size, options) {
  15210. var fullOptions = new RenderTargetCreationOptions();
  15211. if (options !== undefined && typeof options === "object") {
  15212. fullOptions.generateMipMaps = options.generateMipMaps;
  15213. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  15214. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  15215. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  15216. fullOptions.samplingMode = options.samplingMode === undefined ? Engine.TEXTURE_TRILINEAR_SAMPLINGMODE : options.samplingMode;
  15217. fullOptions.format = options.format === undefined ? Engine.TEXTUREFORMAT_RGBA : options.format;
  15218. }
  15219. else {
  15220. fullOptions.generateMipMaps = options;
  15221. fullOptions.generateDepthBuffer = true;
  15222. fullOptions.generateStencilBuffer = false;
  15223. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15224. fullOptions.samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE;
  15225. fullOptions.format = Engine.TEXTUREFORMAT_RGBA;
  15226. }
  15227. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15228. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15229. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15230. }
  15231. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15232. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15233. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15234. }
  15235. var gl = this._gl;
  15236. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  15237. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  15238. var width = size.width || size;
  15239. var height = size.height || size;
  15240. var filters = this._getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false);
  15241. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15242. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15243. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  15244. }
  15245. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  15246. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  15247. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15248. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15249. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type, fullOptions.format), width, height, 0, this._getInternalFormat(fullOptions.format), this._getWebGLTextureType(fullOptions.type), null);
  15250. // Create the framebuffer
  15251. var currentFrameBuffer = this._currentFramebuffer;
  15252. var framebuffer = gl.createFramebuffer();
  15253. this.bindUnboundFramebuffer(framebuffer);
  15254. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  15255. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  15256. if (fullOptions.generateMipMaps) {
  15257. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15258. }
  15259. // Unbind
  15260. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15261. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15262. this.bindUnboundFramebuffer(currentFrameBuffer);
  15263. texture._framebuffer = framebuffer;
  15264. texture.baseWidth = width;
  15265. texture.baseHeight = height;
  15266. texture.width = width;
  15267. texture.height = height;
  15268. texture.isReady = true;
  15269. texture.samples = 1;
  15270. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  15271. texture.samplingMode = fullOptions.samplingMode;
  15272. texture.type = fullOptions.type;
  15273. texture.format = fullOptions.format;
  15274. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  15275. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  15276. // this.resetTextureCache();
  15277. this._internalTexturesCache.push(texture);
  15278. return texture;
  15279. };
  15280. /**
  15281. * Create a multi render target texture
  15282. * @see http://doc.babylonjs.com/features/webgl2#multiple-render-target
  15283. * @param size defines the size of the texture
  15284. * @param options defines the creation options
  15285. * @returns the cube texture as an InternalTexture
  15286. */
  15287. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  15288. var generateMipMaps = false;
  15289. var generateDepthBuffer = true;
  15290. var generateStencilBuffer = false;
  15291. var generateDepthTexture = false;
  15292. var textureCount = 1;
  15293. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  15294. var defaultSamplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE;
  15295. var types = new Array();
  15296. var samplingModes = new Array();
  15297. if (options !== undefined) {
  15298. generateMipMaps = options.generateMipMaps === undefined ? false : options.generateMipMaps;
  15299. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  15300. generateStencilBuffer = options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  15301. generateDepthTexture = options.generateDepthTexture === undefined ? false : options.generateDepthTexture;
  15302. textureCount = options.textureCount || 1;
  15303. if (options.types) {
  15304. types = options.types;
  15305. }
  15306. if (options.samplingModes) {
  15307. samplingModes = options.samplingModes;
  15308. }
  15309. }
  15310. var gl = this._gl;
  15311. // Create the framebuffer
  15312. var framebuffer = gl.createFramebuffer();
  15313. this.bindUnboundFramebuffer(framebuffer);
  15314. var width = size.width || size;
  15315. var height = size.height || size;
  15316. var textures = [];
  15317. var attachments = [];
  15318. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  15319. for (var i = 0; i < textureCount; i++) {
  15320. var samplingMode = samplingModes[i] || defaultSamplingMode;
  15321. var type = types[i] || defaultType;
  15322. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15323. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15324. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15325. }
  15326. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15327. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15328. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15329. }
  15330. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  15331. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15332. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15333. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  15334. }
  15335. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  15336. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  15337. textures.push(texture);
  15338. attachments.push(attachment);
  15339. gl.activeTexture(gl["TEXTURE" + i]);
  15340. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  15341. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  15342. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  15343. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15344. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15345. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  15346. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  15347. if (generateMipMaps) {
  15348. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15349. }
  15350. // Unbind
  15351. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15352. texture._framebuffer = framebuffer;
  15353. texture._depthStencilBuffer = depthStencilBuffer;
  15354. texture.baseWidth = width;
  15355. texture.baseHeight = height;
  15356. texture.width = width;
  15357. texture.height = height;
  15358. texture.isReady = true;
  15359. texture.samples = 1;
  15360. texture.generateMipMaps = generateMipMaps;
  15361. texture.samplingMode = samplingMode;
  15362. texture.type = type;
  15363. texture._generateDepthBuffer = generateDepthBuffer;
  15364. texture._generateStencilBuffer = generateStencilBuffer;
  15365. texture._attachments = attachments;
  15366. this._internalTexturesCache.push(texture);
  15367. }
  15368. if (generateDepthTexture && this._caps.depthTextureExtension) {
  15369. // Depth texture
  15370. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  15371. gl.activeTexture(gl.TEXTURE0);
  15372. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  15373. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15374. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15375. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15376. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15377. 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);
  15378. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  15379. depthTexture._framebuffer = framebuffer;
  15380. depthTexture.baseWidth = width;
  15381. depthTexture.baseHeight = height;
  15382. depthTexture.width = width;
  15383. depthTexture.height = height;
  15384. depthTexture.isReady = true;
  15385. depthTexture.samples = 1;
  15386. depthTexture.generateMipMaps = generateMipMaps;
  15387. depthTexture.samplingMode = gl.NEAREST;
  15388. depthTexture._generateDepthBuffer = generateDepthBuffer;
  15389. depthTexture._generateStencilBuffer = generateStencilBuffer;
  15390. textures.push(depthTexture);
  15391. this._internalTexturesCache.push(depthTexture);
  15392. }
  15393. gl.drawBuffers(attachments);
  15394. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15395. this.bindUnboundFramebuffer(null);
  15396. this.resetTextureCache();
  15397. return textures;
  15398. };
  15399. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  15400. if (samples === void 0) { samples = 1; }
  15401. var depthStencilBuffer = null;
  15402. var gl = this._gl;
  15403. // Create the depth/stencil buffer
  15404. if (generateStencilBuffer) {
  15405. depthStencilBuffer = gl.createRenderbuffer();
  15406. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  15407. if (samples > 1) {
  15408. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  15409. }
  15410. else {
  15411. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  15412. }
  15413. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  15414. }
  15415. else if (generateDepthBuffer) {
  15416. depthStencilBuffer = gl.createRenderbuffer();
  15417. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  15418. if (samples > 1) {
  15419. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  15420. }
  15421. else {
  15422. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  15423. }
  15424. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  15425. }
  15426. return depthStencilBuffer;
  15427. };
  15428. /**
  15429. * Updates the sample count of a render target texture
  15430. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  15431. * @param texture defines the texture to update
  15432. * @param samples defines the sample count to set
  15433. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  15434. */
  15435. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  15436. if (this.webGLVersion < 2 || !texture) {
  15437. return 1;
  15438. }
  15439. if (texture.samples === samples) {
  15440. return samples;
  15441. }
  15442. var gl = this._gl;
  15443. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  15444. // Dispose previous render buffers
  15445. if (texture._depthStencilBuffer) {
  15446. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  15447. texture._depthStencilBuffer = null;
  15448. }
  15449. if (texture._MSAAFramebuffer) {
  15450. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  15451. texture._MSAAFramebuffer = null;
  15452. }
  15453. if (texture._MSAARenderBuffer) {
  15454. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  15455. texture._MSAARenderBuffer = null;
  15456. }
  15457. if (samples > 1) {
  15458. var framebuffer = gl.createFramebuffer();
  15459. if (!framebuffer) {
  15460. throw new Error("Unable to create multi sampled framebuffer");
  15461. }
  15462. texture._MSAAFramebuffer = framebuffer;
  15463. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  15464. var colorRenderbuffer = gl.createRenderbuffer();
  15465. if (!colorRenderbuffer) {
  15466. throw new Error("Unable to create multi sampled framebuffer");
  15467. }
  15468. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  15469. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  15470. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  15471. texture._MSAARenderBuffer = colorRenderbuffer;
  15472. }
  15473. else {
  15474. this.bindUnboundFramebuffer(texture._framebuffer);
  15475. }
  15476. texture.samples = samples;
  15477. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  15478. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15479. this.bindUnboundFramebuffer(null);
  15480. return samples;
  15481. };
  15482. /**
  15483. * Update the sample count for a given multiple render target texture
  15484. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  15485. * @param textures defines the textures to update
  15486. * @param samples defines the sample count to set
  15487. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  15488. */
  15489. Engine.prototype.updateMultipleRenderTargetTextureSampleCount = function (textures, samples) {
  15490. if (this.webGLVersion < 2 || !textures || textures.length == 0) {
  15491. return 1;
  15492. }
  15493. if (textures[0].samples === samples) {
  15494. return samples;
  15495. }
  15496. var gl = this._gl;
  15497. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  15498. // Dispose previous render buffers
  15499. if (textures[0]._depthStencilBuffer) {
  15500. gl.deleteRenderbuffer(textures[0]._depthStencilBuffer);
  15501. textures[0]._depthStencilBuffer = null;
  15502. }
  15503. if (textures[0]._MSAAFramebuffer) {
  15504. gl.deleteFramebuffer(textures[0]._MSAAFramebuffer);
  15505. textures[0]._MSAAFramebuffer = null;
  15506. }
  15507. for (var i = 0; i < textures.length; i++) {
  15508. if (textures[i]._MSAARenderBuffer) {
  15509. gl.deleteRenderbuffer(textures[i]._MSAARenderBuffer);
  15510. textures[i]._MSAARenderBuffer = null;
  15511. }
  15512. }
  15513. if (samples > 1) {
  15514. var framebuffer = gl.createFramebuffer();
  15515. if (!framebuffer) {
  15516. throw new Error("Unable to create multi sampled framebuffer");
  15517. }
  15518. this.bindUnboundFramebuffer(framebuffer);
  15519. var depthStencilBuffer = this._setupFramebufferDepthAttachments(textures[0]._generateStencilBuffer, textures[0]._generateDepthBuffer, textures[0].width, textures[0].height, samples);
  15520. var attachments = [];
  15521. for (var i = 0; i < textures.length; i++) {
  15522. var texture = textures[i];
  15523. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  15524. var colorRenderbuffer = gl.createRenderbuffer();
  15525. if (!colorRenderbuffer) {
  15526. throw new Error("Unable to create multi sampled framebuffer");
  15527. }
  15528. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  15529. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  15530. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, colorRenderbuffer);
  15531. texture._MSAAFramebuffer = framebuffer;
  15532. texture._MSAARenderBuffer = colorRenderbuffer;
  15533. texture.samples = samples;
  15534. texture._depthStencilBuffer = depthStencilBuffer;
  15535. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15536. attachments.push(attachment);
  15537. }
  15538. gl.drawBuffers(attachments);
  15539. }
  15540. else {
  15541. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  15542. }
  15543. this.bindUnboundFramebuffer(null);
  15544. return samples;
  15545. };
  15546. /** @hidden */
  15547. Engine.prototype._uploadCompressedDataToTextureDirectly = function (texture, internalFormat, width, height, data, faceIndex, lod) {
  15548. if (faceIndex === void 0) { faceIndex = 0; }
  15549. if (lod === void 0) { lod = 0; }
  15550. var gl = this._gl;
  15551. var target = gl.TEXTURE_2D;
  15552. if (texture.isCube) {
  15553. target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
  15554. }
  15555. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  15556. };
  15557. /** @hidden */
  15558. Engine.prototype._uploadDataToTextureDirectly = function (texture, imageData, faceIndex, lod) {
  15559. if (faceIndex === void 0) { faceIndex = 0; }
  15560. if (lod === void 0) { lod = 0; }
  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. this._unpackFlipY(texture.invertY);
  15566. var target = gl.TEXTURE_2D;
  15567. if (texture.isCube) {
  15568. target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
  15569. }
  15570. var lodMaxWidth = Math.round(BABYLON.Scalar.Log2(texture.width));
  15571. var lodMaxHeight = Math.round(BABYLON.Scalar.Log2(texture.height));
  15572. var width = Math.pow(2, Math.max(lodMaxWidth - lod, 0));
  15573. var height = Math.pow(2, Math.max(lodMaxHeight - lod, 0));
  15574. gl.texImage2D(target, lod, internalFormat, width, height, 0, format, textureType, imageData);
  15575. };
  15576. /** @hidden */
  15577. Engine.prototype._uploadArrayBufferViewToTexture = function (texture, imageData, faceIndex, lod) {
  15578. if (faceIndex === void 0) { faceIndex = 0; }
  15579. if (lod === void 0) { lod = 0; }
  15580. var gl = this._gl;
  15581. var bindTarget = texture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  15582. this._bindTextureDirectly(bindTarget, texture, true);
  15583. this._uploadDataToTextureDirectly(texture, imageData, faceIndex, lod);
  15584. this._bindTextureDirectly(bindTarget, null, true);
  15585. };
  15586. /** @hidden */
  15587. Engine.prototype._uploadImageToTexture = function (texture, image, faceIndex, lod) {
  15588. if (faceIndex === void 0) { faceIndex = 0; }
  15589. if (lod === void 0) { lod = 0; }
  15590. var gl = this._gl;
  15591. var textureType = this._getWebGLTextureType(texture.type);
  15592. var format = this._getInternalFormat(texture.format);
  15593. var internalFormat = this._getRGBABufferInternalSizedFormat(texture.type, format);
  15594. var bindTarget = texture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  15595. this._bindTextureDirectly(bindTarget, texture, true);
  15596. this._unpackFlipY(texture.invertY);
  15597. var target = gl.TEXTURE_2D;
  15598. if (texture.isCube) {
  15599. target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
  15600. }
  15601. gl.texImage2D(target, lod, internalFormat, format, textureType, image);
  15602. this._bindTextureDirectly(bindTarget, null, true);
  15603. };
  15604. /**
  15605. * Creates a new render target cube texture
  15606. * @param size defines the size of the texture
  15607. * @param options defines the options used to create the texture
  15608. * @returns a new render target cube texture stored in an InternalTexture
  15609. */
  15610. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  15611. var fullOptions = __assign({ generateMipMaps: true, generateDepthBuffer: true, generateStencilBuffer: false, type: Engine.TEXTURETYPE_UNSIGNED_INT, samplingMode: Engine.TEXTURE_TRILINEAR_SAMPLINGMODE, format: Engine.TEXTUREFORMAT_RGBA }, options);
  15612. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && fullOptions.generateStencilBuffer;
  15613. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15614. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15615. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15616. }
  15617. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15618. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15619. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15620. }
  15621. var gl = this._gl;
  15622. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  15623. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15624. var filters = this._getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps);
  15625. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15626. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15627. BABYLON.Tools.Warn("Float textures are not supported. Cube render target forced to TEXTURETYPE_UNESIGNED_BYTE type");
  15628. }
  15629. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  15630. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  15631. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15632. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15633. for (var face = 0; face < 6; face++) {
  15634. 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);
  15635. }
  15636. // Create the framebuffer
  15637. var framebuffer = gl.createFramebuffer();
  15638. this.bindUnboundFramebuffer(framebuffer);
  15639. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer, fullOptions.generateDepthBuffer, size, size);
  15640. // MipMaps
  15641. if (fullOptions.generateMipMaps) {
  15642. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15643. }
  15644. // Unbind
  15645. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15646. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15647. this.bindUnboundFramebuffer(null);
  15648. texture._framebuffer = framebuffer;
  15649. texture.width = size;
  15650. texture.height = size;
  15651. texture.isReady = true;
  15652. texture.isCube = true;
  15653. texture.samples = 1;
  15654. texture.generateMipMaps = fullOptions.generateMipMaps;
  15655. texture.samplingMode = fullOptions.samplingMode;
  15656. texture.type = fullOptions.type;
  15657. texture.format = fullOptions.format;
  15658. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  15659. texture._generateStencilBuffer = fullOptions.generateStencilBuffer;
  15660. this._internalTexturesCache.push(texture);
  15661. return texture;
  15662. };
  15663. /**
  15664. * Create a cube texture from prefiltered data (ie. the mipmaps contain ready to use data for PBR reflection)
  15665. * @param rootUrl defines the url where the file to load is located
  15666. * @param scene defines the current scene
  15667. * @param lodScale defines scale to apply to the mip map selection
  15668. * @param lodOffset defines offset to apply to the mip map selection
  15669. * @param onLoad defines an optional callback raised when the texture is loaded
  15670. * @param onError defines an optional callback raised if there is an issue to load the texture
  15671. * @param format defines the format of the data
  15672. * @param forcedExtension defines the extension to use to pick the right loader
  15673. * @param createPolynomials defines wheter or not to create polynomails harmonics for the texture
  15674. * @returns the cube texture as an InternalTexture
  15675. */
  15676. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, lodScale, lodOffset, onLoad, onError, format, forcedExtension, createPolynomials) {
  15677. var _this = this;
  15678. if (onLoad === void 0) { onLoad = null; }
  15679. if (onError === void 0) { onError = null; }
  15680. if (forcedExtension === void 0) { forcedExtension = null; }
  15681. if (createPolynomials === void 0) { createPolynomials = true; }
  15682. var callback = function (loadData) {
  15683. if (!loadData) {
  15684. if (onLoad) {
  15685. onLoad(null);
  15686. }
  15687. return;
  15688. }
  15689. var texture = loadData.texture;
  15690. if (!createPolynomials) {
  15691. texture._sphericalPolynomial = new BABYLON.SphericalPolynomial();
  15692. }
  15693. else if (loadData.info.sphericalPolynomial) {
  15694. texture._sphericalPolynomial = loadData.info.sphericalPolynomial;
  15695. }
  15696. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  15697. if (_this._caps.textureLOD) {
  15698. // Do not add extra process if texture lod is supported.
  15699. if (onLoad) {
  15700. onLoad(texture);
  15701. }
  15702. return;
  15703. }
  15704. var mipSlices = 3;
  15705. var gl = _this._gl;
  15706. var width = loadData.width;
  15707. if (!width) {
  15708. return;
  15709. }
  15710. var textures = [];
  15711. for (var i = 0; i < mipSlices; i++) {
  15712. //compute LOD from even spacing in smoothness (matching shader calculation)
  15713. var smoothness = i / (mipSlices - 1);
  15714. var roughness = 1 - smoothness;
  15715. var minLODIndex = lodOffset; // roughness = 0
  15716. var maxLODIndex = BABYLON.Scalar.Log2(width) * lodScale + lodOffset; // roughness = 1
  15717. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  15718. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  15719. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  15720. glTextureFromLod.type = texture.type;
  15721. glTextureFromLod.format = texture.format;
  15722. glTextureFromLod.width = Math.pow(2, Math.max(BABYLON.Scalar.Log2(width) - mipmapIndex, 0));
  15723. glTextureFromLod.height = glTextureFromLod.width;
  15724. glTextureFromLod.isCube = true;
  15725. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod, true);
  15726. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  15727. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  15728. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15729. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15730. if (loadData.isDDS) {
  15731. var info = loadData.info;
  15732. var data = loadData.data;
  15733. _this._unpackFlipY(info.isCompressed);
  15734. BABYLON.DDSTools.UploadDDSLevels(_this, glTextureFromLod, data, info, true, 6, mipmapIndex);
  15735. }
  15736. else {
  15737. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  15738. }
  15739. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15740. // Wrap in a base texture for easy binding.
  15741. var lodTexture = new BABYLON.BaseTexture(scene);
  15742. lodTexture.isCube = true;
  15743. lodTexture._texture = glTextureFromLod;
  15744. glTextureFromLod.isReady = true;
  15745. textures.push(lodTexture);
  15746. }
  15747. texture._lodTextureHigh = textures[2];
  15748. texture._lodTextureMid = textures[1];
  15749. texture._lodTextureLow = textures[0];
  15750. if (onLoad) {
  15751. onLoad(texture);
  15752. }
  15753. };
  15754. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension, createPolynomials, lodScale, lodOffset);
  15755. };
  15756. /**
  15757. * Creates a cube texture
  15758. * @param rootUrl defines the url where the files to load is located
  15759. * @param scene defines the current scene
  15760. * @param files defines the list of files to load (1 per face)
  15761. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated (false by default)
  15762. * @param onLoad defines an optional callback raised when the texture is loaded
  15763. * @param onError defines an optional callback raised if there is an issue to load the texture
  15764. * @param format defines the format of the data
  15765. * @param forcedExtension defines the extension to use to pick the right loader
  15766. * @param createPolynomials if a polynomial sphere should be created for the cube texture
  15767. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  15768. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  15769. * @param fallback defines texture to use while falling back when (compressed) texture file not found.
  15770. * @returns the cube texture as an InternalTexture
  15771. */
  15772. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension, createPolynomials, lodScale, lodOffset, fallback) {
  15773. var _this = this;
  15774. if (onLoad === void 0) { onLoad = null; }
  15775. if (onError === void 0) { onError = null; }
  15776. if (forcedExtension === void 0) { forcedExtension = null; }
  15777. if (createPolynomials === void 0) { createPolynomials = false; }
  15778. if (lodScale === void 0) { lodScale = 0; }
  15779. if (lodOffset === void 0) { lodOffset = 0; }
  15780. if (fallback === void 0) { fallback = null; }
  15781. var gl = this._gl;
  15782. var texture = fallback ? fallback : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  15783. texture.isCube = true;
  15784. texture.url = rootUrl;
  15785. texture.generateMipMaps = !noMipmap;
  15786. texture._lodGenerationScale = lodScale;
  15787. texture._lodGenerationOffset = lodOffset;
  15788. if (!this._doNotHandleContextLost) {
  15789. texture._extension = forcedExtension;
  15790. texture._files = files;
  15791. }
  15792. var lastDot = rootUrl.lastIndexOf('.');
  15793. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  15794. var loader = null;
  15795. for (var _i = 0, _a = Engine._TextureLoaders; _i < _a.length; _i++) {
  15796. var availableLoader = _a[_i];
  15797. if (availableLoader.canLoad(extension, this._textureFormatInUse, fallback, false, false)) {
  15798. loader = availableLoader;
  15799. break;
  15800. }
  15801. }
  15802. var onInternalError = function (request, exception) {
  15803. if (loader) {
  15804. var fallbackUrl = loader.getFallbackTextureUrl(rootUrl, _this._textureFormatInUse);
  15805. if (fallbackUrl) {
  15806. _this.createCubeTexture(fallbackUrl, scene, files, noMipmap, onLoad, onError, format, extension, createPolynomials, lodScale, lodOffset, texture);
  15807. }
  15808. }
  15809. if (onError && request) {
  15810. onError(request.status + " " + request.statusText, exception);
  15811. }
  15812. };
  15813. if (loader) {
  15814. rootUrl = loader.transformUrl(rootUrl, this._textureFormatInUse);
  15815. var onloaddata = function (data) {
  15816. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15817. loader.loadCubeData(data, texture, createPolynomials, onLoad, onError);
  15818. };
  15819. if (files && files.length === 6) {
  15820. if (loader.supportCascades) {
  15821. this._cascadeLoadFiles(scene, onloaddata, files, onError);
  15822. }
  15823. else if (onError) {
  15824. onError("Textures type does not support cascades.");
  15825. }
  15826. }
  15827. else {
  15828. this._loadFile(rootUrl, onloaddata, undefined, undefined, true, onInternalError);
  15829. }
  15830. }
  15831. else {
  15832. if (!files) {
  15833. throw new Error("Cannot load cubemap because files were not defined");
  15834. }
  15835. this._cascadeLoadImgs(rootUrl, scene, function (imgs) {
  15836. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  15837. var height = width;
  15838. _this._prepareWorkingCanvas();
  15839. if (!_this._workingCanvas || !_this._workingContext) {
  15840. return;
  15841. }
  15842. _this._workingCanvas.width = width;
  15843. _this._workingCanvas.height = height;
  15844. var faces = [
  15845. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  15846. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  15847. ];
  15848. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15849. _this._unpackFlipY(false);
  15850. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  15851. for (var index = 0; index < faces.length; index++) {
  15852. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  15853. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  15854. }
  15855. if (!noMipmap) {
  15856. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15857. }
  15858. _this._setCubeMapTextureParams(!noMipmap);
  15859. texture.width = width;
  15860. texture.height = height;
  15861. texture.isReady = true;
  15862. if (format) {
  15863. texture.format = format;
  15864. }
  15865. texture.onLoadedObservable.notifyObservers(texture);
  15866. texture.onLoadedObservable.clear();
  15867. if (onLoad) {
  15868. onLoad();
  15869. }
  15870. }, files, onError);
  15871. }
  15872. this._internalTexturesCache.push(texture);
  15873. return texture;
  15874. };
  15875. /**
  15876. * @hidden
  15877. */
  15878. Engine.prototype._setCubeMapTextureParams = function (loadMipmap) {
  15879. var gl = this._gl;
  15880. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  15881. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  15882. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15883. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15884. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15885. // this.resetTextureCache();
  15886. };
  15887. /**
  15888. * Update a raw cube texture
  15889. * @param texture defines the texture to udpdate
  15890. * @param data defines the data to store
  15891. * @param format defines the data format
  15892. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  15893. * @param invertY defines if data must be stored with Y axis inverted
  15894. * @param compression defines the compression used (null by default)
  15895. * @param level defines which level of the texture to update
  15896. */
  15897. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  15898. if (compression === void 0) { compression = null; }
  15899. if (level === void 0) { level = 0; }
  15900. texture._bufferViewArray = data;
  15901. texture.format = format;
  15902. texture.type = type;
  15903. texture.invertY = invertY;
  15904. texture._compression = compression;
  15905. var gl = this._gl;
  15906. var textureType = this._getWebGLTextureType(type);
  15907. var internalFormat = this._getInternalFormat(format);
  15908. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  15909. var needConversion = false;
  15910. if (internalFormat === gl.RGB) {
  15911. internalFormat = gl.RGBA;
  15912. needConversion = true;
  15913. }
  15914. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15915. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  15916. if (texture.width % 4 !== 0) {
  15917. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  15918. }
  15919. // Data are known to be in +X +Y +Z -X -Y -Z
  15920. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  15921. var faceData = data[faceIndex];
  15922. if (compression) {
  15923. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData);
  15924. }
  15925. else {
  15926. if (needConversion) {
  15927. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  15928. }
  15929. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  15930. }
  15931. }
  15932. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  15933. if (isPot && texture.generateMipMaps && level === 0) {
  15934. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  15935. }
  15936. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  15937. // this.resetTextureCache();
  15938. texture.isReady = true;
  15939. };
  15940. /**
  15941. * Creates a new raw cube texture
  15942. * @param data defines the array of data to use to create each face
  15943. * @param size defines the size of the textures
  15944. * @param format defines the format of the data
  15945. * @param type defines the type of the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  15946. * @param generateMipMaps defines if the engine should generate the mip levels
  15947. * @param invertY defines if data must be stored with Y axis inverted
  15948. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  15949. * @param compression defines the compression used (null by default)
  15950. * @returns the cube texture as an InternalTexture
  15951. */
  15952. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  15953. if (compression === void 0) { compression = null; }
  15954. var gl = this._gl;
  15955. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  15956. texture.isCube = true;
  15957. texture.format = format;
  15958. texture.type = type;
  15959. if (!this._doNotHandleContextLost) {
  15960. texture._bufferViewArray = data;
  15961. }
  15962. var textureType = this._getWebGLTextureType(type);
  15963. var internalFormat = this._getInternalFormat(format);
  15964. if (internalFormat === gl.RGB) {
  15965. internalFormat = gl.RGBA;
  15966. }
  15967. // Mipmap generation needs a sized internal format that is both color-renderable and texture-filterable
  15968. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  15969. generateMipMaps = false;
  15970. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15971. BABYLON.Tools.Warn("Float texture filtering is not supported. Mipmap generation and sampling mode are forced to false and TEXTURE_NEAREST_SAMPLINGMODE, respectively.");
  15972. }
  15973. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  15974. generateMipMaps = false;
  15975. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15976. BABYLON.Tools.Warn("Half float texture filtering is not supported. Mipmap generation and sampling mode are forced to false and TEXTURE_NEAREST_SAMPLINGMODE, respectively.");
  15977. }
  15978. else if (textureType === gl.FLOAT && !this._caps.textureFloatRender) {
  15979. generateMipMaps = false;
  15980. BABYLON.Tools.Warn("Render to float textures is not supported. Mipmap generation forced to false.");
  15981. }
  15982. else if (textureType === gl.HALF_FLOAT && !this._caps.colorBufferFloat) {
  15983. generateMipMaps = false;
  15984. BABYLON.Tools.Warn("Render to half float textures is not supported. Mipmap generation forced to false.");
  15985. }
  15986. var width = size;
  15987. var height = width;
  15988. texture.width = width;
  15989. texture.height = height;
  15990. // Double check on POT to generate Mips.
  15991. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  15992. if (!isPot) {
  15993. generateMipMaps = false;
  15994. }
  15995. // Upload data if needed. The texture won't be ready until then.
  15996. if (data) {
  15997. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  15998. }
  15999. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  16000. // Filters
  16001. if (data && generateMipMaps) {
  16002. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  16003. }
  16004. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  16005. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  16006. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  16007. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  16008. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  16009. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  16010. texture.generateMipMaps = generateMipMaps;
  16011. return texture;
  16012. };
  16013. /**
  16014. * Creates a new raw cube texture from a specified url
  16015. * @param url defines the url where the data is located
  16016. * @param scene defines the current scene
  16017. * @param size defines the size of the textures
  16018. * @param format defines the format of the data
  16019. * @param type defines the type fo the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  16020. * @param noMipmap defines if the engine should avoid generating the mip levels
  16021. * @param callback defines a callback used to extract texture data from loaded data
  16022. * @param mipmapGenerator defines to provide an optional tool to generate mip levels
  16023. * @param onLoad defines a callback called when texture is loaded
  16024. * @param onError defines a callback called if there is an error
  16025. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  16026. * @param invertY defines if data must be stored with Y axis inverted
  16027. * @returns the cube texture as an InternalTexture
  16028. */
  16029. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmapGenerator, onLoad, onError, samplingMode, invertY) {
  16030. var _this = this;
  16031. if (onLoad === void 0) { onLoad = null; }
  16032. if (onError === void 0) { onError = null; }
  16033. if (samplingMode === void 0) { samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE; }
  16034. if (invertY === void 0) { invertY = false; }
  16035. var gl = this._gl;
  16036. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  16037. scene._addPendingData(texture);
  16038. texture.url = url;
  16039. this._internalTexturesCache.push(texture);
  16040. var onerror = function (request, exception) {
  16041. scene._removePendingData(texture);
  16042. if (onError && request) {
  16043. onError(request.status + " " + request.statusText, exception);
  16044. }
  16045. };
  16046. var internalCallback = function (data) {
  16047. var width = texture.width;
  16048. var faceDataArrays = callback(data);
  16049. if (!faceDataArrays) {
  16050. return;
  16051. }
  16052. if (mipmapGenerator) {
  16053. var textureType = _this._getWebGLTextureType(type);
  16054. var internalFormat = _this._getInternalFormat(format);
  16055. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  16056. var needConversion = false;
  16057. if (internalFormat === gl.RGB) {
  16058. internalFormat = gl.RGBA;
  16059. needConversion = true;
  16060. }
  16061. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  16062. _this._unpackFlipY(false);
  16063. var mipData = mipmapGenerator(faceDataArrays);
  16064. for (var level = 0; level < mipData.length; level++) {
  16065. var mipSize = width >> level;
  16066. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  16067. var mipFaceData = mipData[level][faceIndex];
  16068. if (needConversion) {
  16069. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  16070. }
  16071. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  16072. }
  16073. }
  16074. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  16075. }
  16076. else {
  16077. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  16078. }
  16079. texture.isReady = true;
  16080. // this.resetTextureCache();
  16081. scene._removePendingData(texture);
  16082. if (onLoad) {
  16083. onLoad();
  16084. }
  16085. };
  16086. this._loadFile(url, function (data) {
  16087. internalCallback(data);
  16088. }, undefined, scene.database, true, onerror);
  16089. return texture;
  16090. };
  16091. ;
  16092. /**
  16093. * Update a raw 3D texture
  16094. * @param texture defines the texture to update
  16095. * @param data defines the data to store
  16096. * @param format defines the data format
  16097. * @param invertY defines if data must be stored with Y axis inverted
  16098. * @param compression defines the used compression (can be null)
  16099. * @param textureType defines the texture Type (Engine.TEXTURETYPE_UNSIGNED_INT, Engine.TEXTURETYPE_FLOAT...)
  16100. */
  16101. Engine.prototype.updateRawTexture3D = function (texture, data, format, invertY, compression, textureType) {
  16102. if (compression === void 0) { compression = null; }
  16103. if (textureType === void 0) { textureType = Engine.TEXTURETYPE_UNSIGNED_INT; }
  16104. var internalType = this._getWebGLTextureType(textureType);
  16105. var internalFormat = this._getInternalFormat(format);
  16106. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(textureType, format);
  16107. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  16108. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  16109. if (!this._doNotHandleContextLost) {
  16110. texture._bufferView = data;
  16111. texture.format = format;
  16112. texture.invertY = invertY;
  16113. texture._compression = compression;
  16114. }
  16115. if (texture.width % 4 !== 0) {
  16116. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  16117. }
  16118. if (compression && data) {
  16119. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data);
  16120. }
  16121. else {
  16122. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalSizedFomat, texture.width, texture.height, texture.depth, 0, internalFormat, internalType, data);
  16123. }
  16124. if (texture.generateMipMaps) {
  16125. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  16126. }
  16127. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16128. // this.resetTextureCache();
  16129. texture.isReady = true;
  16130. };
  16131. /**
  16132. * Creates a new raw 3D texture
  16133. * @param data defines the data used to create the texture
  16134. * @param width defines the width of the texture
  16135. * @param height defines the height of the texture
  16136. * @param depth defines the depth of the texture
  16137. * @param format defines the format of the texture
  16138. * @param generateMipMaps defines if the engine must generate mip levels
  16139. * @param invertY defines if data must be stored with Y axis inverted
  16140. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  16141. * @param compression defines the compressed used (can be null)
  16142. * @param textureType defines the compressed used (can be null)
  16143. * @returns a new raw 3D texture (stored in an InternalTexture)
  16144. */
  16145. Engine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression, textureType) {
  16146. if (compression === void 0) { compression = null; }
  16147. if (textureType === void 0) { textureType = Engine.TEXTURETYPE_UNSIGNED_INT; }
  16148. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW3D);
  16149. texture.baseWidth = width;
  16150. texture.baseHeight = height;
  16151. texture.baseDepth = depth;
  16152. texture.width = width;
  16153. texture.height = height;
  16154. texture.depth = depth;
  16155. texture.format = format;
  16156. texture.type = textureType;
  16157. texture.generateMipMaps = generateMipMaps;
  16158. texture.samplingMode = samplingMode;
  16159. texture.is3D = true;
  16160. if (!this._doNotHandleContextLost) {
  16161. texture._bufferView = data;
  16162. }
  16163. this.updateRawTexture3D(texture, data, format, invertY, compression, textureType);
  16164. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  16165. // Filters
  16166. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  16167. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  16168. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  16169. if (generateMipMaps) {
  16170. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  16171. }
  16172. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16173. this._internalTexturesCache.push(texture);
  16174. return texture;
  16175. };
  16176. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  16177. var gl = this._gl;
  16178. if (!gl) {
  16179. return;
  16180. }
  16181. var filters = this._getSamplingParameters(samplingMode, !noMipmap);
  16182. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  16183. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  16184. if (!noMipmap && !isCompressed) {
  16185. gl.generateMipmap(gl.TEXTURE_2D);
  16186. }
  16187. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  16188. // this.resetTextureCache();
  16189. if (scene) {
  16190. scene._removePendingData(texture);
  16191. }
  16192. texture.onLoadedObservable.notifyObservers(texture);
  16193. texture.onLoadedObservable.clear();
  16194. };
  16195. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  16196. var _this = this;
  16197. if (samplingMode === void 0) { samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE; }
  16198. var maxTextureSize = this.getCaps().maxTextureSize;
  16199. var potWidth = Math.min(maxTextureSize, this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, maxTextureSize) : width);
  16200. var potHeight = Math.min(maxTextureSize, this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, maxTextureSize) : height);
  16201. var gl = this._gl;
  16202. if (!gl) {
  16203. return;
  16204. }
  16205. if (!texture._webGLTexture) {
  16206. // this.resetTextureCache();
  16207. if (scene) {
  16208. scene._removePendingData(texture);
  16209. }
  16210. return;
  16211. }
  16212. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  16213. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  16214. texture.baseWidth = width;
  16215. texture.baseHeight = height;
  16216. texture.width = potWidth;
  16217. texture.height = potHeight;
  16218. texture.isReady = true;
  16219. if (processFunction(potWidth, potHeight, function () {
  16220. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  16221. })) {
  16222. // Returning as texture needs extra async steps
  16223. return;
  16224. }
  16225. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  16226. };
  16227. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  16228. // Create new RGBA data container.
  16229. var rgbaData;
  16230. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  16231. rgbaData = new Float32Array(width * height * 4);
  16232. }
  16233. else {
  16234. rgbaData = new Uint32Array(width * height * 4);
  16235. }
  16236. // Convert each pixel.
  16237. for (var x = 0; x < width; x++) {
  16238. for (var y = 0; y < height; y++) {
  16239. var index = (y * width + x) * 3;
  16240. var newIndex = (y * width + x) * 4;
  16241. // Map Old Value to new value.
  16242. rgbaData[newIndex + 0] = rgbData[index + 0];
  16243. rgbaData[newIndex + 1] = rgbData[index + 1];
  16244. rgbaData[newIndex + 2] = rgbData[index + 2];
  16245. // Add fully opaque alpha channel.
  16246. rgbaData[newIndex + 3] = 1;
  16247. }
  16248. }
  16249. return rgbaData;
  16250. };
  16251. /** @hidden */
  16252. Engine.prototype._releaseFramebufferObjects = function (texture) {
  16253. var gl = this._gl;
  16254. if (texture._framebuffer) {
  16255. gl.deleteFramebuffer(texture._framebuffer);
  16256. texture._framebuffer = null;
  16257. }
  16258. if (texture._depthStencilBuffer) {
  16259. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  16260. texture._depthStencilBuffer = null;
  16261. }
  16262. if (texture._MSAAFramebuffer) {
  16263. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  16264. texture._MSAAFramebuffer = null;
  16265. }
  16266. if (texture._MSAARenderBuffer) {
  16267. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  16268. texture._MSAARenderBuffer = null;
  16269. }
  16270. };
  16271. /** @hidden */
  16272. Engine.prototype._releaseTexture = function (texture) {
  16273. var gl = this._gl;
  16274. this._releaseFramebufferObjects(texture);
  16275. gl.deleteTexture(texture._webGLTexture);
  16276. // Unbind channels
  16277. this.unbindAllTextures();
  16278. var index = this._internalTexturesCache.indexOf(texture);
  16279. if (index !== -1) {
  16280. this._internalTexturesCache.splice(index, 1);
  16281. }
  16282. // Integrated fixed lod samplers.
  16283. if (texture._lodTextureHigh) {
  16284. texture._lodTextureHigh.dispose();
  16285. }
  16286. if (texture._lodTextureMid) {
  16287. texture._lodTextureMid.dispose();
  16288. }
  16289. if (texture._lodTextureLow) {
  16290. texture._lodTextureLow.dispose();
  16291. }
  16292. // Set output texture of post process to null if the texture has been released/disposed
  16293. this.scenes.forEach(function (scene) {
  16294. scene.postProcesses.forEach(function (postProcess) {
  16295. if (postProcess._outputTexture == texture) {
  16296. postProcess._outputTexture = null;
  16297. }
  16298. });
  16299. scene.cameras.forEach(function (camera) {
  16300. camera._postProcesses.forEach(function (postProcess) {
  16301. if (postProcess) {
  16302. if (postProcess._outputTexture == texture) {
  16303. postProcess._outputTexture = null;
  16304. }
  16305. }
  16306. });
  16307. });
  16308. });
  16309. };
  16310. Engine.prototype.setProgram = function (program) {
  16311. if (this._currentProgram !== program) {
  16312. this._gl.useProgram(program);
  16313. this._currentProgram = program;
  16314. }
  16315. };
  16316. /**
  16317. * Binds an effect to the webGL context
  16318. * @param effect defines the effect to bind
  16319. */
  16320. Engine.prototype.bindSamplers = function (effect) {
  16321. this.setProgram(effect.getProgram());
  16322. var samplers = effect.getSamplers();
  16323. for (var index = 0; index < samplers.length; index++) {
  16324. var uniform = effect.getUniform(samplers[index]);
  16325. if (uniform) {
  16326. this._boundUniforms[index] = uniform;
  16327. }
  16328. }
  16329. this._currentEffect = null;
  16330. };
  16331. Engine.prototype._moveBoundTextureOnTop = function (internalTexture) {
  16332. if (this.disableTextureBindingOptimization || this._lastBoundInternalTextureTracker.previous === internalTexture) {
  16333. return;
  16334. }
  16335. // Remove
  16336. this._linkTrackers(internalTexture.previous, internalTexture.next);
  16337. // Bind last to it
  16338. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, internalTexture);
  16339. // Bind to dummy
  16340. this._linkTrackers(internalTexture, this._lastBoundInternalTextureTracker);
  16341. };
  16342. Engine.prototype._getCorrectTextureChannel = function (channel, internalTexture) {
  16343. if (!internalTexture) {
  16344. return -1;
  16345. }
  16346. internalTexture._initialSlot = channel;
  16347. if (this.disableTextureBindingOptimization) { // We want texture sampler ID === texture channel
  16348. if (channel !== internalTexture._designatedSlot) {
  16349. this._textureCollisions.addCount(1, false);
  16350. }
  16351. }
  16352. else {
  16353. if (channel !== internalTexture._designatedSlot) {
  16354. if (internalTexture._designatedSlot > -1) { // Texture is already assigned to a slot
  16355. return internalTexture._designatedSlot;
  16356. }
  16357. else {
  16358. // No slot for this texture, let's pick a new one (if we find a free slot)
  16359. if (this._nextFreeTextureSlots.length) {
  16360. return this._nextFreeTextureSlots[0];
  16361. }
  16362. // We need to recycle the oldest bound texture, sorry.
  16363. this._textureCollisions.addCount(1, false);
  16364. return this._removeDesignatedSlot(this._firstBoundInternalTextureTracker.next);
  16365. }
  16366. }
  16367. }
  16368. return channel;
  16369. };
  16370. Engine.prototype._linkTrackers = function (previous, next) {
  16371. previous.next = next;
  16372. next.previous = previous;
  16373. };
  16374. Engine.prototype._removeDesignatedSlot = function (internalTexture) {
  16375. var currentSlot = internalTexture._designatedSlot;
  16376. if (currentSlot === -1) {
  16377. return -1;
  16378. }
  16379. internalTexture._designatedSlot = -1;
  16380. if (this.disableTextureBindingOptimization) {
  16381. return -1;
  16382. }
  16383. // Remove from bound list
  16384. this._linkTrackers(internalTexture.previous, internalTexture.next);
  16385. // Free the slot
  16386. this._boundTexturesCache[currentSlot] = null;
  16387. this._nextFreeTextureSlots.push(currentSlot);
  16388. return currentSlot;
  16389. };
  16390. Engine.prototype._activateCurrentTexture = function () {
  16391. if (this._currentTextureChannel !== this._activeChannel) {
  16392. this._gl.activeTexture(this._gl.TEXTURE0 + this._activeChannel);
  16393. this._currentTextureChannel = this._activeChannel;
  16394. }
  16395. };
  16396. /** @hidden */
  16397. Engine.prototype._bindTextureDirectly = function (target, texture, forTextureDataUpdate, force) {
  16398. if (forTextureDataUpdate === void 0) { forTextureDataUpdate = false; }
  16399. if (force === void 0) { force = false; }
  16400. var wasPreviouslyBound = false;
  16401. if (forTextureDataUpdate && texture && texture._designatedSlot > -1) {
  16402. this._activeChannel = texture._designatedSlot;
  16403. }
  16404. var currentTextureBound = this._boundTexturesCache[this._activeChannel];
  16405. var isTextureForRendering = texture && texture._initialSlot > -1;
  16406. if (currentTextureBound !== texture || force) {
  16407. if (currentTextureBound) {
  16408. this._removeDesignatedSlot(currentTextureBound);
  16409. }
  16410. this._activateCurrentTexture();
  16411. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  16412. this._boundTexturesCache[this._activeChannel] = texture;
  16413. if (texture) {
  16414. if (!this.disableTextureBindingOptimization) {
  16415. var slotIndex = this._nextFreeTextureSlots.indexOf(this._activeChannel);
  16416. if (slotIndex > -1) {
  16417. this._nextFreeTextureSlots.splice(slotIndex, 1);
  16418. }
  16419. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, texture);
  16420. this._linkTrackers(texture, this._lastBoundInternalTextureTracker);
  16421. }
  16422. texture._designatedSlot = this._activeChannel;
  16423. }
  16424. }
  16425. else if (forTextureDataUpdate) {
  16426. wasPreviouslyBound = true;
  16427. this._activateCurrentTexture();
  16428. }
  16429. if (isTextureForRendering && !forTextureDataUpdate) {
  16430. this._bindSamplerUniformToChannel(texture._initialSlot, this._activeChannel);
  16431. }
  16432. return wasPreviouslyBound;
  16433. };
  16434. /** @hidden */
  16435. Engine.prototype._bindTexture = function (channel, texture) {
  16436. if (channel < 0) {
  16437. return;
  16438. }
  16439. if (texture) {
  16440. channel = this._getCorrectTextureChannel(channel, texture);
  16441. }
  16442. this._activeChannel = channel;
  16443. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  16444. };
  16445. /**
  16446. * Sets a texture to the webGL context from a postprocess
  16447. * @param channel defines the channel to use
  16448. * @param postProcess defines the source postprocess
  16449. */
  16450. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  16451. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  16452. };
  16453. /**
  16454. * Binds the output of the passed in post process to the texture channel specified
  16455. * @param channel The channel the texture should be bound to
  16456. * @param postProcess The post process which's output should be bound
  16457. */
  16458. Engine.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  16459. this._bindTexture(channel, postProcess ? postProcess._outputTexture : null);
  16460. };
  16461. /**
  16462. * Unbind all textures from the webGL context
  16463. */
  16464. Engine.prototype.unbindAllTextures = function () {
  16465. for (var channel = 0; channel < this._maxSimultaneousTextures; channel++) {
  16466. this._activeChannel = channel;
  16467. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  16468. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  16469. if (this.webGLVersion > 1) {
  16470. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16471. }
  16472. }
  16473. };
  16474. /**
  16475. * Sets a texture to the according uniform.
  16476. * @param channel The texture channel
  16477. * @param uniform The uniform to set
  16478. * @param texture The texture to apply
  16479. */
  16480. Engine.prototype.setTexture = function (channel, uniform, texture) {
  16481. if (channel < 0) {
  16482. return;
  16483. }
  16484. if (uniform) {
  16485. this._boundUniforms[channel] = uniform;
  16486. }
  16487. this._setTexture(channel, texture);
  16488. };
  16489. /**
  16490. * Sets a depth stencil texture from a render target to the according uniform.
  16491. * @param channel The texture channel
  16492. * @param uniform The uniform to set
  16493. * @param texture The render target texture containing the depth stencil texture to apply
  16494. */
  16495. Engine.prototype.setDepthStencilTexture = function (channel, uniform, texture) {
  16496. if (channel < 0) {
  16497. return;
  16498. }
  16499. if (uniform) {
  16500. this._boundUniforms[channel] = uniform;
  16501. }
  16502. if (!texture || !texture.depthStencilTexture) {
  16503. this._setTexture(channel, null);
  16504. }
  16505. else {
  16506. this._setTexture(channel, texture, false, true);
  16507. }
  16508. };
  16509. Engine.prototype._bindSamplerUniformToChannel = function (sourceSlot, destination) {
  16510. var uniform = this._boundUniforms[sourceSlot];
  16511. if (uniform._currentState === destination) {
  16512. return;
  16513. }
  16514. this._gl.uniform1i(uniform, destination);
  16515. uniform._currentState = destination;
  16516. };
  16517. Engine.prototype._getTextureWrapMode = function (mode) {
  16518. switch (mode) {
  16519. case Engine.TEXTURE_WRAP_ADDRESSMODE:
  16520. return this._gl.REPEAT;
  16521. case Engine.TEXTURE_CLAMP_ADDRESSMODE:
  16522. return this._gl.CLAMP_TO_EDGE;
  16523. case Engine.TEXTURE_MIRROR_ADDRESSMODE:
  16524. return this._gl.MIRRORED_REPEAT;
  16525. }
  16526. return this._gl.REPEAT;
  16527. };
  16528. Engine.prototype._setTexture = function (channel, texture, isPartOfTextureArray, depthStencilTexture) {
  16529. if (isPartOfTextureArray === void 0) { isPartOfTextureArray = false; }
  16530. if (depthStencilTexture === void 0) { depthStencilTexture = false; }
  16531. // Not ready?
  16532. if (!texture) {
  16533. if (this._boundTexturesCache[channel] != null) {
  16534. this._activeChannel = channel;
  16535. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  16536. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  16537. if (this.webGLVersion > 1) {
  16538. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16539. }
  16540. }
  16541. return false;
  16542. }
  16543. // Video
  16544. if (texture.video) {
  16545. this._activeChannel = channel;
  16546. texture.update();
  16547. }
  16548. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) { // Delay loading
  16549. texture.delayLoad();
  16550. return false;
  16551. }
  16552. var internalTexture;
  16553. if (depthStencilTexture) {
  16554. internalTexture = texture.depthStencilTexture;
  16555. }
  16556. else if (texture.isReady()) {
  16557. internalTexture = texture.getInternalTexture();
  16558. }
  16559. else if (texture.isCube) {
  16560. internalTexture = this.emptyCubeTexture;
  16561. }
  16562. else if (texture.is3D) {
  16563. internalTexture = this.emptyTexture3D;
  16564. }
  16565. else {
  16566. internalTexture = this.emptyTexture;
  16567. }
  16568. if (!isPartOfTextureArray) {
  16569. channel = this._getCorrectTextureChannel(channel, internalTexture);
  16570. }
  16571. var needToBind = true;
  16572. if (this._boundTexturesCache[channel] === internalTexture) {
  16573. this._moveBoundTextureOnTop(internalTexture);
  16574. if (!isPartOfTextureArray) {
  16575. this._bindSamplerUniformToChannel(internalTexture._initialSlot, channel);
  16576. }
  16577. needToBind = false;
  16578. }
  16579. this._activeChannel = channel;
  16580. if (internalTexture && internalTexture.is3D) {
  16581. if (needToBind) {
  16582. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture, isPartOfTextureArray);
  16583. }
  16584. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  16585. internalTexture._cachedWrapU = texture.wrapU;
  16586. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  16587. }
  16588. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  16589. internalTexture._cachedWrapV = texture.wrapV;
  16590. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  16591. }
  16592. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  16593. internalTexture._cachedWrapR = texture.wrapR;
  16594. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._getTextureWrapMode(texture.wrapR), internalTexture);
  16595. }
  16596. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  16597. }
  16598. else if (internalTexture && internalTexture.isCube) {
  16599. if (needToBind) {
  16600. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture, isPartOfTextureArray);
  16601. }
  16602. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  16603. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  16604. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  16605. var textureWrapMode = (texture.coordinatesMode !== Engine.TEXTURE_CUBIC_MODE && texture.coordinatesMode !== Engine.TEXTURE_SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  16606. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode, internalTexture);
  16607. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  16608. }
  16609. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  16610. }
  16611. else {
  16612. if (needToBind) {
  16613. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture, isPartOfTextureArray);
  16614. }
  16615. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  16616. internalTexture._cachedWrapU = texture.wrapU;
  16617. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  16618. }
  16619. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  16620. internalTexture._cachedWrapV = texture.wrapV;
  16621. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  16622. }
  16623. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  16624. }
  16625. return true;
  16626. };
  16627. /**
  16628. * Sets an array of texture to the webGL context
  16629. * @param channel defines the channel where the texture array must be set
  16630. * @param uniform defines the associated uniform location
  16631. * @param textures defines the array of textures to bind
  16632. */
  16633. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  16634. if (channel < 0 || !uniform) {
  16635. return;
  16636. }
  16637. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  16638. this._textureUnits = new Int32Array(textures.length);
  16639. }
  16640. for (var i = 0; i < textures.length; i++) {
  16641. this._textureUnits[i] = this._getCorrectTextureChannel(channel + i, textures[i].getInternalTexture());
  16642. }
  16643. this._gl.uniform1iv(uniform, this._textureUnits);
  16644. for (var index = 0; index < textures.length; index++) {
  16645. this._setTexture(this._textureUnits[index], textures[index], true);
  16646. }
  16647. };
  16648. /** @hidden */
  16649. Engine.prototype._setAnisotropicLevel = function (target, texture) {
  16650. var internalTexture = texture.getInternalTexture();
  16651. if (!internalTexture) {
  16652. return;
  16653. }
  16654. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  16655. var value = texture.anisotropicFilteringLevel;
  16656. if (internalTexture.samplingMode !== Engine.TEXTURE_LINEAR_LINEAR_MIPNEAREST
  16657. && internalTexture.samplingMode !== Engine.TEXTURE_LINEAR_LINEAR_MIPLINEAR
  16658. && internalTexture.samplingMode !== Engine.TEXTURE_LINEAR_LINEAR) {
  16659. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  16660. }
  16661. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  16662. this._setTextureParameterFloat(target, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy), internalTexture);
  16663. internalTexture._cachedAnisotropicFilteringLevel = value;
  16664. }
  16665. };
  16666. Engine.prototype._setTextureParameterFloat = function (target, parameter, value, texture) {
  16667. this._bindTextureDirectly(target, texture, true, true);
  16668. this._gl.texParameterf(target, parameter, value);
  16669. };
  16670. Engine.prototype._setTextureParameterInteger = function (target, parameter, value, texture) {
  16671. if (texture) {
  16672. this._bindTextureDirectly(target, texture, true, true);
  16673. }
  16674. this._gl.texParameteri(target, parameter, value);
  16675. };
  16676. /**
  16677. * Reads pixels from the current frame buffer. Please note that this function can be slow
  16678. * @param x defines the x coordinate of the rectangle where pixels must be read
  16679. * @param y defines the y coordinate of the rectangle where pixels must be read
  16680. * @param width defines the width of the rectangle where pixels must be read
  16681. * @param height defines the height of the rectangle where pixels must be read
  16682. * @returns a Uint8Array containing RGBA colors
  16683. */
  16684. Engine.prototype.readPixels = function (x, y, width, height) {
  16685. var data = new Uint8Array(height * width * 4);
  16686. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  16687. return data;
  16688. };
  16689. /**
  16690. * Add an externaly attached data from its key.
  16691. * This method call will fail and return false, if such key already exists.
  16692. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  16693. * @param key the unique key that identifies the data
  16694. * @param data the data object to associate to the key for this Engine instance
  16695. * @return true if no such key were already present and the data was added successfully, false otherwise
  16696. */
  16697. Engine.prototype.addExternalData = function (key, data) {
  16698. if (!this._externalData) {
  16699. this._externalData = new BABYLON.StringDictionary();
  16700. }
  16701. return this._externalData.add(key, data);
  16702. };
  16703. /**
  16704. * Get an externaly attached data from its key
  16705. * @param key the unique key that identifies the data
  16706. * @return the associated data, if present (can be null), or undefined if not present
  16707. */
  16708. Engine.prototype.getExternalData = function (key) {
  16709. if (!this._externalData) {
  16710. this._externalData = new BABYLON.StringDictionary();
  16711. }
  16712. return this._externalData.get(key);
  16713. };
  16714. /**
  16715. * Get an externaly attached data from its key, create it using a factory if it's not already present
  16716. * @param key the unique key that identifies the data
  16717. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  16718. * @return the associated data, can be null if the factory returned null.
  16719. */
  16720. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  16721. if (!this._externalData) {
  16722. this._externalData = new BABYLON.StringDictionary();
  16723. }
  16724. return this._externalData.getOrAddWithFactory(key, factory);
  16725. };
  16726. /**
  16727. * Remove an externaly attached data from the Engine instance
  16728. * @param key the unique key that identifies the data
  16729. * @return true if the data was successfully removed, false if it doesn't exist
  16730. */
  16731. Engine.prototype.removeExternalData = function (key) {
  16732. if (!this._externalData) {
  16733. this._externalData = new BABYLON.StringDictionary();
  16734. }
  16735. return this._externalData.remove(key);
  16736. };
  16737. /**
  16738. * Unbind all vertex attributes from the webGL context
  16739. */
  16740. Engine.prototype.unbindAllAttributes = function () {
  16741. if (this._mustWipeVertexAttributes) {
  16742. this._mustWipeVertexAttributes = false;
  16743. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  16744. this._gl.disableVertexAttribArray(i);
  16745. this._vertexAttribArraysEnabled[i] = false;
  16746. this._currentBufferPointers[i].active = false;
  16747. }
  16748. return;
  16749. }
  16750. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  16751. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  16752. continue;
  16753. }
  16754. this._gl.disableVertexAttribArray(i);
  16755. this._vertexAttribArraysEnabled[i] = false;
  16756. this._currentBufferPointers[i].active = false;
  16757. }
  16758. };
  16759. /**
  16760. * 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
  16761. */
  16762. Engine.prototype.releaseEffects = function () {
  16763. for (var name in this._compiledEffects) {
  16764. this._deleteProgram(this._compiledEffects[name]._program);
  16765. }
  16766. this._compiledEffects = {};
  16767. };
  16768. /**
  16769. * Dispose and release all associated resources
  16770. */
  16771. Engine.prototype.dispose = function () {
  16772. this.hideLoadingUI();
  16773. this.stopRenderLoop();
  16774. // Release postProcesses
  16775. while (this.postProcesses.length) {
  16776. this.postProcesses[0].dispose();
  16777. }
  16778. // Empty texture
  16779. if (this._emptyTexture) {
  16780. this._releaseTexture(this._emptyTexture);
  16781. this._emptyTexture = null;
  16782. }
  16783. if (this._emptyCubeTexture) {
  16784. this._releaseTexture(this._emptyCubeTexture);
  16785. this._emptyCubeTexture = null;
  16786. }
  16787. // Rescale PP
  16788. if (this._rescalePostProcess) {
  16789. this._rescalePostProcess.dispose();
  16790. }
  16791. // Release scenes
  16792. while (this.scenes.length) {
  16793. this.scenes[0].dispose();
  16794. }
  16795. // Release audio engine
  16796. if (Engine.Instances.length === 1 && Engine.audioEngine) {
  16797. Engine.audioEngine.dispose();
  16798. }
  16799. // Release effects
  16800. this.releaseEffects();
  16801. // Unbind
  16802. this.unbindAllAttributes();
  16803. this._boundUniforms = [];
  16804. if (this._dummyFramebuffer) {
  16805. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  16806. }
  16807. //WebVR
  16808. this.disableVR();
  16809. // Events
  16810. if (BABYLON.Tools.IsWindowObjectExist()) {
  16811. window.removeEventListener("blur", this._onBlur);
  16812. window.removeEventListener("focus", this._onFocus);
  16813. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  16814. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  16815. if (this._renderingCanvas) {
  16816. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  16817. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  16818. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasPointerOut);
  16819. if (!this._doNotHandleContextLost) {
  16820. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  16821. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  16822. }
  16823. }
  16824. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  16825. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  16826. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  16827. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  16828. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  16829. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  16830. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  16831. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  16832. if (this._onVrDisplayConnect) {
  16833. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  16834. if (this._onVrDisplayDisconnect) {
  16835. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  16836. }
  16837. if (this._onVrDisplayPresentChange) {
  16838. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  16839. }
  16840. this._onVrDisplayConnect = null;
  16841. this._onVrDisplayDisconnect = null;
  16842. }
  16843. }
  16844. // Remove from Instances
  16845. var index = Engine.Instances.indexOf(this);
  16846. if (index >= 0) {
  16847. Engine.Instances.splice(index, 1);
  16848. }
  16849. this._workingCanvas = null;
  16850. this._workingContext = null;
  16851. this._currentBufferPointers = [];
  16852. this._renderingCanvas = null;
  16853. this._currentProgram = null;
  16854. this._bindedRenderFunction = null;
  16855. this.onResizeObservable.clear();
  16856. this.onCanvasBlurObservable.clear();
  16857. this.onCanvasFocusObservable.clear();
  16858. this.onCanvasPointerOutObservable.clear();
  16859. this.onBeginFrameObservable.clear();
  16860. this.onEndFrameObservable.clear();
  16861. BABYLON.Effect.ResetCache();
  16862. // Abort active requests
  16863. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  16864. var request = _a[_i];
  16865. request.abort();
  16866. }
  16867. };
  16868. // Loading screen
  16869. /**
  16870. * Display the loading screen
  16871. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16872. */
  16873. Engine.prototype.displayLoadingUI = function () {
  16874. if (!BABYLON.Tools.IsWindowObjectExist()) {
  16875. return;
  16876. }
  16877. var loadingScreen = this.loadingScreen;
  16878. if (loadingScreen) {
  16879. loadingScreen.displayLoadingUI();
  16880. }
  16881. };
  16882. /**
  16883. * Hide the loading screen
  16884. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16885. */
  16886. Engine.prototype.hideLoadingUI = function () {
  16887. if (!BABYLON.Tools.IsWindowObjectExist()) {
  16888. return;
  16889. }
  16890. var loadingScreen = this.loadingScreen;
  16891. if (loadingScreen) {
  16892. loadingScreen.hideLoadingUI();
  16893. }
  16894. };
  16895. Object.defineProperty(Engine.prototype, "loadingScreen", {
  16896. /**
  16897. * Gets the current loading screen object
  16898. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16899. */
  16900. get: function () {
  16901. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen && this._renderingCanvas)
  16902. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  16903. return this._loadingScreen;
  16904. },
  16905. /**
  16906. * Sets the current loading screen object
  16907. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16908. */
  16909. set: function (loadingScreen) {
  16910. this._loadingScreen = loadingScreen;
  16911. },
  16912. enumerable: true,
  16913. configurable: true
  16914. });
  16915. Object.defineProperty(Engine.prototype, "loadingUIText", {
  16916. /**
  16917. * Sets the current loading screen text
  16918. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16919. */
  16920. set: function (text) {
  16921. this.loadingScreen.loadingUIText = text;
  16922. },
  16923. enumerable: true,
  16924. configurable: true
  16925. });
  16926. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  16927. /**
  16928. * Sets the current loading screen background color
  16929. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16930. */
  16931. set: function (color) {
  16932. this.loadingScreen.loadingUIBackgroundColor = color;
  16933. },
  16934. enumerable: true,
  16935. configurable: true
  16936. });
  16937. /**
  16938. * Attach a new callback raised when context lost event is fired
  16939. * @param callback defines the callback to call
  16940. */
  16941. Engine.prototype.attachContextLostEvent = function (callback) {
  16942. if (this._renderingCanvas) {
  16943. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  16944. }
  16945. };
  16946. /**
  16947. * Attach a new callback raised when context restored event is fired
  16948. * @param callback defines the callback to call
  16949. */
  16950. Engine.prototype.attachContextRestoredEvent = function (callback) {
  16951. if (this._renderingCanvas) {
  16952. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  16953. }
  16954. };
  16955. /**
  16956. * Gets the source code of the vertex shader associated with a specific webGL program
  16957. * @param program defines the program to use
  16958. * @returns a string containing the source code of the vertex shader associated with the program
  16959. */
  16960. Engine.prototype.getVertexShaderSource = function (program) {
  16961. var shaders = this._gl.getAttachedShaders(program);
  16962. if (!shaders) {
  16963. return null;
  16964. }
  16965. return this._gl.getShaderSource(shaders[0]);
  16966. };
  16967. /**
  16968. * Gets the source code of the fragment shader associated with a specific webGL program
  16969. * @param program defines the program to use
  16970. * @returns a string containing the source code of the fragment shader associated with the program
  16971. */
  16972. Engine.prototype.getFragmentShaderSource = function (program) {
  16973. var shaders = this._gl.getAttachedShaders(program);
  16974. if (!shaders) {
  16975. return null;
  16976. }
  16977. return this._gl.getShaderSource(shaders[1]);
  16978. };
  16979. /**
  16980. * Get the current error code of the webGL context
  16981. * @returns the error code
  16982. * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/getError
  16983. */
  16984. Engine.prototype.getError = function () {
  16985. return this._gl.getError();
  16986. };
  16987. // FPS
  16988. /**
  16989. * Gets the current framerate
  16990. * @returns a number representing the framerate
  16991. */
  16992. Engine.prototype.getFps = function () {
  16993. return this._fps;
  16994. };
  16995. /**
  16996. * Gets the time spent between current and previous frame
  16997. * @returns a number representing the delta time in ms
  16998. */
  16999. Engine.prototype.getDeltaTime = function () {
  17000. return this._deltaTime;
  17001. };
  17002. Engine.prototype._measureFps = function () {
  17003. this._performanceMonitor.sampleFrame();
  17004. this._fps = this._performanceMonitor.averageFPS;
  17005. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  17006. };
  17007. /** @hidden */
  17008. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex, level, buffer) {
  17009. if (faceIndex === void 0) { faceIndex = -1; }
  17010. if (level === void 0) { level = 0; }
  17011. if (buffer === void 0) { buffer = null; }
  17012. var gl = this._gl;
  17013. if (!this._dummyFramebuffer) {
  17014. var dummy = gl.createFramebuffer();
  17015. if (!dummy) {
  17016. throw new Error("Unable to create dummy framebuffer");
  17017. }
  17018. this._dummyFramebuffer = dummy;
  17019. }
  17020. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  17021. if (faceIndex > -1) {
  17022. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, level);
  17023. }
  17024. else {
  17025. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, level);
  17026. }
  17027. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  17028. switch (readType) {
  17029. case gl.UNSIGNED_BYTE:
  17030. if (!buffer) {
  17031. buffer = new Uint8Array(4 * width * height);
  17032. }
  17033. readType = gl.UNSIGNED_BYTE;
  17034. break;
  17035. default:
  17036. if (!buffer) {
  17037. buffer = new Float32Array(4 * width * height);
  17038. }
  17039. readType = gl.FLOAT;
  17040. break;
  17041. }
  17042. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  17043. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  17044. return buffer;
  17045. };
  17046. Engine.prototype._canRenderToFloatFramebuffer = function () {
  17047. if (this._webGLVersion > 1) {
  17048. return this._caps.colorBufferFloat;
  17049. }
  17050. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_FLOAT);
  17051. };
  17052. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  17053. if (this._webGLVersion > 1) {
  17054. return this._caps.colorBufferFloat;
  17055. }
  17056. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_HALF_FLOAT);
  17057. };
  17058. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  17059. Engine.prototype._canRenderToFramebuffer = function (type) {
  17060. var gl = this._gl;
  17061. //clear existing errors
  17062. while (gl.getError() !== gl.NO_ERROR) { }
  17063. var successful = true;
  17064. var texture = gl.createTexture();
  17065. gl.bindTexture(gl.TEXTURE_2D, texture);
  17066. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  17067. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  17068. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  17069. var fb = gl.createFramebuffer();
  17070. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  17071. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  17072. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  17073. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  17074. successful = successful && (gl.getError() === gl.NO_ERROR);
  17075. //try render by clearing frame buffer's color buffer
  17076. if (successful) {
  17077. gl.clear(gl.COLOR_BUFFER_BIT);
  17078. successful = successful && (gl.getError() === gl.NO_ERROR);
  17079. }
  17080. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  17081. if (successful) {
  17082. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  17083. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  17084. var readFormat = gl.RGBA;
  17085. var readType = gl.UNSIGNED_BYTE;
  17086. var buffer = new Uint8Array(4);
  17087. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  17088. successful = successful && (gl.getError() === gl.NO_ERROR);
  17089. }
  17090. //clean up
  17091. gl.deleteTexture(texture);
  17092. gl.deleteFramebuffer(fb);
  17093. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  17094. //clear accumulated errors
  17095. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  17096. return successful;
  17097. };
  17098. /** @hidden */
  17099. Engine.prototype._getWebGLTextureType = function (type) {
  17100. if (this._webGLVersion === 1) {
  17101. switch (type) {
  17102. case Engine.TEXTURETYPE_FLOAT:
  17103. return this._gl.FLOAT;
  17104. case Engine.TEXTURETYPE_HALF_FLOAT:
  17105. return this._gl.HALF_FLOAT_OES;
  17106. case Engine.TEXTURETYPE_UNSIGNED_BYTE:
  17107. return this._gl.UNSIGNED_BYTE;
  17108. }
  17109. return this._gl.UNSIGNED_BYTE;
  17110. }
  17111. switch (type) {
  17112. case Engine.TEXTURETYPE_BYTE:
  17113. return this._gl.BYTE;
  17114. case Engine.TEXTURETYPE_UNSIGNED_BYTE:
  17115. return this._gl.UNSIGNED_BYTE;
  17116. case Engine.TEXTURETYPE_SHORT:
  17117. return this._gl.SHORT;
  17118. case Engine.TEXTURETYPE_UNSIGNED_SHORT:
  17119. return this._gl.UNSIGNED_SHORT;
  17120. case Engine.TEXTURETYPE_INT:
  17121. return this._gl.INT;
  17122. case Engine.TEXTURETYPE_UNSIGNED_INTEGER: // Refers to UNSIGNED_INT
  17123. return this._gl.UNSIGNED_INT;
  17124. case Engine.TEXTURETYPE_FLOAT:
  17125. return this._gl.FLOAT;
  17126. case Engine.TEXTURETYPE_HALF_FLOAT:
  17127. return this._gl.HALF_FLOAT;
  17128. case Engine.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4:
  17129. return this._gl.UNSIGNED_SHORT_4_4_4_4;
  17130. case Engine.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1:
  17131. return this._gl.UNSIGNED_SHORT_5_5_5_1;
  17132. case Engine.TEXTURETYPE_UNSIGNED_SHORT_5_6_5:
  17133. return this._gl.UNSIGNED_SHORT_5_6_5;
  17134. case Engine.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV:
  17135. return this._gl.UNSIGNED_INT_2_10_10_10_REV;
  17136. case Engine.TEXTURETYPE_UNSIGNED_INT_24_8:
  17137. return this._gl.UNSIGNED_INT_24_8;
  17138. case Engine.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV:
  17139. return this._gl.UNSIGNED_INT_10F_11F_11F_REV;
  17140. case Engine.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV:
  17141. return this._gl.UNSIGNED_INT_5_9_9_9_REV;
  17142. case Engine.TEXTURETYPE_FLOAT_32_UNSIGNED_INT_24_8_REV:
  17143. return this._gl.FLOAT_32_UNSIGNED_INT_24_8_REV;
  17144. }
  17145. return this._gl.UNSIGNED_BYTE;
  17146. };
  17147. ;
  17148. Engine.prototype._getInternalFormat = function (format) {
  17149. var internalFormat = this._gl.RGBA;
  17150. switch (format) {
  17151. case Engine.TEXTUREFORMAT_ALPHA:
  17152. internalFormat = this._gl.ALPHA;
  17153. break;
  17154. case Engine.TEXTUREFORMAT_LUMINANCE:
  17155. internalFormat = this._gl.LUMINANCE;
  17156. break;
  17157. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  17158. internalFormat = this._gl.LUMINANCE_ALPHA;
  17159. break;
  17160. case Engine.TEXTUREFORMAT_RED:
  17161. internalFormat = this._gl.RED;
  17162. break;
  17163. case Engine.TEXTUREFORMAT_RG:
  17164. internalFormat = this._gl.RG;
  17165. break;
  17166. case Engine.TEXTUREFORMAT_RGB:
  17167. internalFormat = this._gl.RGB;
  17168. break;
  17169. case Engine.TEXTUREFORMAT_RGBA:
  17170. internalFormat = this._gl.RGBA;
  17171. break;
  17172. }
  17173. if (this._webGLVersion > 1) {
  17174. switch (format) {
  17175. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17176. internalFormat = this._gl.RED_INTEGER;
  17177. break;
  17178. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17179. internalFormat = this._gl.RG_INTEGER;
  17180. break;
  17181. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17182. internalFormat = this._gl.RGB_INTEGER;
  17183. break;
  17184. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17185. internalFormat = this._gl.RGBA_INTEGER;
  17186. break;
  17187. }
  17188. }
  17189. return internalFormat;
  17190. };
  17191. /** @hidden */
  17192. Engine.prototype._getRGBABufferInternalSizedFormat = function (type, format) {
  17193. if (this._webGLVersion === 1) {
  17194. if (format !== undefined) {
  17195. switch (format) {
  17196. case Engine.TEXTUREFORMAT_ALPHA:
  17197. return this._gl.ALPHA;
  17198. case Engine.TEXTUREFORMAT_LUMINANCE:
  17199. return this._gl.LUMINANCE;
  17200. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  17201. return this._gl.LUMINANCE_ALPHA;
  17202. }
  17203. }
  17204. return this._gl.RGBA;
  17205. }
  17206. switch (type) {
  17207. case Engine.TEXTURETYPE_BYTE:
  17208. switch (format) {
  17209. case Engine.TEXTUREFORMAT_RED:
  17210. return this._gl.R8_SNORM;
  17211. case Engine.TEXTUREFORMAT_RG:
  17212. return this._gl.RG8_SNORM;
  17213. case Engine.TEXTUREFORMAT_RGB:
  17214. return this._gl.RGB8_SNORM;
  17215. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17216. return this._gl.R8I;
  17217. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17218. return this._gl.RG8I;
  17219. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17220. return this._gl.RGB8I;
  17221. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17222. return this._gl.RGBA8I;
  17223. default:
  17224. return this._gl.RGBA8_SNORM;
  17225. }
  17226. case Engine.TEXTURETYPE_UNSIGNED_BYTE:
  17227. switch (format) {
  17228. case Engine.TEXTUREFORMAT_RED:
  17229. return this._gl.R8;
  17230. case Engine.TEXTUREFORMAT_RG:
  17231. return this._gl.RG8;
  17232. case Engine.TEXTUREFORMAT_RGB:
  17233. return this._gl.RGB8; // By default. Other possibilities are RGB565, SRGB8.
  17234. case Engine.TEXTUREFORMAT_RGBA:
  17235. return this._gl.RGBA8; // By default. Other possibilities are RGB5_A1, RGBA4, SRGB8_ALPHA8.
  17236. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17237. return this._gl.R8UI;
  17238. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17239. return this._gl.RG8UI;
  17240. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17241. return this._gl.RGB8UI;
  17242. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17243. return this._gl.RGBA8UI;
  17244. default:
  17245. return this._gl.RGBA8;
  17246. }
  17247. case Engine.TEXTURETYPE_SHORT:
  17248. switch (format) {
  17249. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17250. return this._gl.R16I;
  17251. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17252. return this._gl.RG16I;
  17253. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17254. return this._gl.RGB16I;
  17255. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17256. return this._gl.RGBA16I;
  17257. default:
  17258. return this._gl.RGBA16I;
  17259. }
  17260. case Engine.TEXTURETYPE_UNSIGNED_SHORT:
  17261. switch (format) {
  17262. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17263. return this._gl.R16UI;
  17264. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17265. return this._gl.RG16UI;
  17266. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17267. return this._gl.RGB16UI;
  17268. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17269. return this._gl.RGBA16UI;
  17270. default:
  17271. return this._gl.RGBA16UI;
  17272. }
  17273. case Engine.TEXTURETYPE_INT:
  17274. switch (format) {
  17275. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17276. return this._gl.R32I;
  17277. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17278. return this._gl.RG32I;
  17279. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17280. return this._gl.RGB32I;
  17281. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17282. return this._gl.RGBA32I;
  17283. default:
  17284. return this._gl.RGBA32I;
  17285. }
  17286. case Engine.TEXTURETYPE_UNSIGNED_INTEGER: // Refers to UNSIGNED_INT
  17287. switch (format) {
  17288. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17289. return this._gl.R32UI;
  17290. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17291. return this._gl.RG32UI;
  17292. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17293. return this._gl.RGB32UI;
  17294. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17295. return this._gl.RGBA32UI;
  17296. default:
  17297. return this._gl.RGBA32UI;
  17298. }
  17299. case Engine.TEXTURETYPE_FLOAT:
  17300. switch (format) {
  17301. case Engine.TEXTUREFORMAT_RED:
  17302. return this._gl.R32F; // By default. Other possibility is R16F.
  17303. case Engine.TEXTUREFORMAT_RG:
  17304. return this._gl.RG32F; // By default. Other possibility is RG16F.
  17305. case Engine.TEXTUREFORMAT_RGB:
  17306. return this._gl.RGB32F; // By default. Other possibilities are RGB16F, R11F_G11F_B10F, RGB9_E5.
  17307. case Engine.TEXTUREFORMAT_RGBA:
  17308. return this._gl.RGBA32F; // By default. Other possibility is RGBA16F.
  17309. default:
  17310. return this._gl.RGBA32F;
  17311. }
  17312. case Engine.TEXTURETYPE_HALF_FLOAT:
  17313. switch (format) {
  17314. case Engine.TEXTUREFORMAT_RED:
  17315. return this._gl.R16F;
  17316. case Engine.TEXTUREFORMAT_RG:
  17317. return this._gl.RG16F;
  17318. case Engine.TEXTUREFORMAT_RGB:
  17319. return this._gl.RGB16F; // By default. Other possibilities are R11F_G11F_B10F, RGB9_E5.
  17320. case Engine.TEXTUREFORMAT_RGBA:
  17321. return this._gl.RGBA16F;
  17322. default:
  17323. return this._gl.RGBA16F;
  17324. }
  17325. case Engine.TEXTURETYPE_UNSIGNED_SHORT_5_6_5:
  17326. return this._gl.RGB565;
  17327. case Engine.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV:
  17328. return this._gl.R11F_G11F_B10F;
  17329. case Engine.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV:
  17330. return this._gl.RGB9_E5;
  17331. case Engine.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4:
  17332. return this._gl.RGBA4;
  17333. case Engine.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1:
  17334. return this._gl.RGB5_A1;
  17335. case Engine.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV:
  17336. switch (format) {
  17337. case Engine.TEXTUREFORMAT_RGBA:
  17338. return this._gl.RGB10_A2; // By default. Other possibility is RGB5_A1.
  17339. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17340. return this._gl.RGB10_A2UI;
  17341. default:
  17342. return this._gl.RGB10_A2;
  17343. }
  17344. }
  17345. return this._gl.RGBA8;
  17346. };
  17347. ;
  17348. /** @hidden */
  17349. Engine.prototype._getRGBAMultiSampleBufferFormat = function (type) {
  17350. if (type === Engine.TEXTURETYPE_FLOAT) {
  17351. return this._gl.RGBA32F;
  17352. }
  17353. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  17354. return this._gl.RGBA16F;
  17355. }
  17356. return this._gl.RGBA8;
  17357. };
  17358. ;
  17359. /** @hidden */
  17360. Engine.prototype._loadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  17361. var _this = this;
  17362. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, database, useArrayBuffer, onError);
  17363. this._activeRequests.push(request);
  17364. request.onCompleteObservable.add(function (request) {
  17365. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  17366. });
  17367. return request;
  17368. };
  17369. /** @hidden */
  17370. Engine.prototype._loadFileAsync = function (url, database, useArrayBuffer) {
  17371. var _this = this;
  17372. return new Promise(function (resolve, reject) {
  17373. _this._loadFile(url, function (data) {
  17374. resolve(data);
  17375. }, undefined, database, useArrayBuffer, function (request, exception) {
  17376. reject(exception);
  17377. });
  17378. });
  17379. };
  17380. Engine.prototype._partialLoadFile = function (url, index, loadedFiles, scene, onfinish, onErrorCallBack) {
  17381. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  17382. var onload = function (data) {
  17383. loadedFiles[index] = data;
  17384. loadedFiles._internalCount++;
  17385. if (loadedFiles._internalCount === 6) {
  17386. onfinish(loadedFiles);
  17387. }
  17388. };
  17389. var onerror = function (request, exception) {
  17390. if (onErrorCallBack && request) {
  17391. onErrorCallBack(request.status + " " + request.statusText, exception);
  17392. }
  17393. };
  17394. this._loadFile(url, onload, undefined, undefined, true, onerror);
  17395. };
  17396. Engine.prototype._cascadeLoadFiles = function (scene, onfinish, files, onError) {
  17397. if (onError === void 0) { onError = null; }
  17398. var loadedFiles = [];
  17399. loadedFiles._internalCount = 0;
  17400. for (var index = 0; index < 6; index++) {
  17401. this._partialLoadFile(files[index], index, loadedFiles, scene, onfinish, onError);
  17402. }
  17403. };
  17404. // Statics
  17405. /**
  17406. * Gets a boolean indicating if the engine can be instanciated (ie. if a webGL context can be found)
  17407. * @returns true if the engine can be created
  17408. * @ignorenaming
  17409. */
  17410. Engine.isSupported = function () {
  17411. try {
  17412. var tempcanvas = document.createElement("canvas");
  17413. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  17414. return gl != null && !!window.WebGLRenderingContext;
  17415. }
  17416. catch (e) {
  17417. return false;
  17418. }
  17419. };
  17420. /** Use this array to turn off some WebGL2 features on known buggy browsers version */
  17421. Engine.ExceptionList = [
  17422. { key: "Chrome/63.0", capture: "63\\.0\\.3239\\.(\\d+)", captureConstraint: 108, targets: ["uniformBuffer"] },
  17423. { key: "Firefox/58", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  17424. { key: "Firefox/59", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  17425. { key: "Macintosh", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  17426. { key: "iPhone", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  17427. { key: "iPad", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] }
  17428. ];
  17429. /** Gets the list of created engines */
  17430. Engine.Instances = new Array();
  17431. /**
  17432. * Hidden
  17433. */
  17434. Engine._TextureLoaders = [];
  17435. // Const statics
  17436. /** Defines that alpha blending is disabled */
  17437. Engine.ALPHA_DISABLE = 0;
  17438. /** Defines that alpha blending to SRC ALPHA * SRC + DEST */
  17439. Engine.ALPHA_ADD = 1;
  17440. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC ALPHA) * DEST */
  17441. Engine.ALPHA_COMBINE = 2;
  17442. /** Defines that alpha blending to DEST - SRC * DEST */
  17443. Engine.ALPHA_SUBTRACT = 3;
  17444. /** Defines that alpha blending to SRC * DEST */
  17445. Engine.ALPHA_MULTIPLY = 4;
  17446. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC) * DEST */
  17447. Engine.ALPHA_MAXIMIZED = 5;
  17448. /** Defines that alpha blending to SRC + DEST */
  17449. Engine.ALPHA_ONEONE = 6;
  17450. /** Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST */
  17451. Engine.ALPHA_PREMULTIPLIED = 7;
  17452. /**
  17453. * Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST
  17454. * Alpha will be set to (1 - SRC ALPHA) * DEST ALPHA
  17455. */
  17456. Engine.ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  17457. /** Defines that alpha blending to CST * SRC + (1 - CST) * DEST */
  17458. Engine.ALPHA_INTERPOLATE = 9;
  17459. /**
  17460. * Defines that alpha blending to SRC + (1 - SRC) * DEST
  17461. * Alpha will be set to SRC ALPHA + (1 - SRC ALPHA) * DEST ALPHA
  17462. */
  17463. Engine.ALPHA_SCREENMODE = 10;
  17464. /** Defines that the ressource is not delayed*/
  17465. Engine.DELAYLOADSTATE_NONE = 0;
  17466. /** Defines that the ressource was successfully delay loaded */
  17467. Engine.DELAYLOADSTATE_LOADED = 1;
  17468. /** Defines that the ressource is currently delay loading */
  17469. Engine.DELAYLOADSTATE_LOADING = 2;
  17470. /** Defines that the ressource is delayed and has not started loading */
  17471. Engine.DELAYLOADSTATE_NOTLOADED = 4;
  17472. // Depht or Stencil test Constants.
  17473. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn */
  17474. Engine.NEVER = 0x0200;
  17475. /** 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 */
  17476. Engine.ALWAYS = 0x0207;
  17477. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than the stored value */
  17478. Engine.LESS = 0x0201;
  17479. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is equals to the stored value */
  17480. Engine.EQUAL = 0x0202;
  17481. /** 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 */
  17482. Engine.LEQUAL = 0x0203;
  17483. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than the stored value */
  17484. Engine.GREATER = 0x0204;
  17485. /** 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 */
  17486. Engine.GEQUAL = 0x0206;
  17487. /** 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 */
  17488. Engine.NOTEQUAL = 0x0205;
  17489. // Stencil Actions Constants.
  17490. /** Passed to stencilOperation to specify that stencil value must be kept */
  17491. Engine.KEEP = 0x1E00;
  17492. /** Passed to stencilOperation to specify that stencil value must be replaced */
  17493. Engine.REPLACE = 0x1E01;
  17494. /** Passed to stencilOperation to specify that stencil value must be incremented */
  17495. Engine.INCR = 0x1E02;
  17496. /** Passed to stencilOperation to specify that stencil value must be decremented */
  17497. Engine.DECR = 0x1E03;
  17498. /** Passed to stencilOperation to specify that stencil value must be inverted */
  17499. Engine.INVERT = 0x150A;
  17500. /** Passed to stencilOperation to specify that stencil value must be incremented with wrapping */
  17501. Engine.INCR_WRAP = 0x8507;
  17502. /** Passed to stencilOperation to specify that stencil value must be decremented with wrapping */
  17503. Engine.DECR_WRAP = 0x8508;
  17504. /** Texture is not repeating outside of 0..1 UVs */
  17505. Engine.TEXTURE_CLAMP_ADDRESSMODE = 0;
  17506. /** Texture is repeating outside of 0..1 UVs */
  17507. Engine.TEXTURE_WRAP_ADDRESSMODE = 1;
  17508. /** Texture is repeating and mirrored */
  17509. Engine.TEXTURE_MIRROR_ADDRESSMODE = 2;
  17510. /** ALPHA */
  17511. Engine.TEXTUREFORMAT_ALPHA = 0;
  17512. /** LUMINANCE */
  17513. Engine.TEXTUREFORMAT_LUMINANCE = 1;
  17514. /** LUMINANCE_ALPHA */
  17515. Engine.TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  17516. /** RGB */
  17517. Engine.TEXTUREFORMAT_RGB = 4;
  17518. /** RGBA */
  17519. Engine.TEXTUREFORMAT_RGBA = 5;
  17520. /** RED */
  17521. Engine.TEXTUREFORMAT_RED = 6;
  17522. /** RED (2nd reference) */
  17523. Engine.TEXTUREFORMAT_R = 6;
  17524. /** RG */
  17525. Engine.TEXTUREFORMAT_RG = 7;
  17526. /** RED_INTEGER */
  17527. Engine.TEXTUREFORMAT_RED_INTEGER = 8;
  17528. /** RED_INTEGER (2nd reference) */
  17529. Engine.TEXTUREFORMAT_R_INTEGER = 8;
  17530. /** RG_INTEGER */
  17531. Engine.TEXTUREFORMAT_RG_INTEGER = 9;
  17532. /** RGB_INTEGER */
  17533. Engine.TEXTUREFORMAT_RGB_INTEGER = 10;
  17534. /** RGBA_INTEGER */
  17535. Engine.TEXTUREFORMAT_RGBA_INTEGER = 11;
  17536. /** UNSIGNED_BYTE */
  17537. Engine.TEXTURETYPE_UNSIGNED_BYTE = 0;
  17538. /** UNSIGNED_BYTE (2nd reference) */
  17539. Engine.TEXTURETYPE_UNSIGNED_INT = 0;
  17540. /** FLOAT */
  17541. Engine.TEXTURETYPE_FLOAT = 1;
  17542. /** HALF_FLOAT */
  17543. Engine.TEXTURETYPE_HALF_FLOAT = 2;
  17544. /** BYTE */
  17545. Engine.TEXTURETYPE_BYTE = 3;
  17546. /** SHORT */
  17547. Engine.TEXTURETYPE_SHORT = 4;
  17548. /** UNSIGNED_SHORT */
  17549. Engine.TEXTURETYPE_UNSIGNED_SHORT = 5;
  17550. /** INT */
  17551. Engine.TEXTURETYPE_INT = 6;
  17552. /** UNSIGNED_INT */
  17553. Engine.TEXTURETYPE_UNSIGNED_INTEGER = 7;
  17554. /** UNSIGNED_SHORT_4_4_4_4 */
  17555. Engine.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4 = 8;
  17556. /** UNSIGNED_SHORT_5_5_5_1 */
  17557. Engine.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1 = 9;
  17558. /** UNSIGNED_SHORT_5_6_5 */
  17559. Engine.TEXTURETYPE_UNSIGNED_SHORT_5_6_5 = 10;
  17560. /** UNSIGNED_INT_2_10_10_10_REV */
  17561. Engine.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV = 11;
  17562. /** UNSIGNED_INT_24_8 */
  17563. Engine.TEXTURETYPE_UNSIGNED_INT_24_8 = 12;
  17564. /** UNSIGNED_INT_10F_11F_11F_REV */
  17565. Engine.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV = 13;
  17566. /** UNSIGNED_INT_5_9_9_9_REV */
  17567. Engine.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV = 14;
  17568. /** FLOAT_32_UNSIGNED_INT_24_8_REV */
  17569. Engine.TEXTURETYPE_FLOAT_32_UNSIGNED_INT_24_8_REV = 15;
  17570. /** nearest is mag = nearest and min = nearest and mip = linear */
  17571. Engine.TEXTURE_NEAREST_SAMPLINGMODE = 1;
  17572. /** Bilinear is mag = linear and min = linear and mip = nearest */
  17573. Engine.TEXTURE_BILINEAR_SAMPLINGMODE = 2;
  17574. /** Trilinear is mag = linear and min = linear and mip = linear */
  17575. Engine.TEXTURE_TRILINEAR_SAMPLINGMODE = 3;
  17576. /** nearest is mag = nearest and min = nearest and mip = linear */
  17577. Engine.TEXTURE_NEAREST_NEAREST_MIPLINEAR = 1;
  17578. /** Bilinear is mag = linear and min = linear and mip = nearest */
  17579. Engine.TEXTURE_LINEAR_LINEAR_MIPNEAREST = 2;
  17580. /** Trilinear is mag = linear and min = linear and mip = linear */
  17581. Engine.TEXTURE_LINEAR_LINEAR_MIPLINEAR = 3;
  17582. /** mag = nearest and min = nearest and mip = nearest */
  17583. Engine.TEXTURE_NEAREST_NEAREST_MIPNEAREST = 4;
  17584. /** mag = nearest and min = linear and mip = nearest */
  17585. Engine.TEXTURE_NEAREST_LINEAR_MIPNEAREST = 5;
  17586. /** mag = nearest and min = linear and mip = linear */
  17587. Engine.TEXTURE_NEAREST_LINEAR_MIPLINEAR = 6;
  17588. /** mag = nearest and min = linear and mip = none */
  17589. Engine.TEXTURE_NEAREST_LINEAR = 7;
  17590. /** mag = nearest and min = nearest and mip = none */
  17591. Engine.TEXTURE_NEAREST_NEAREST = 8;
  17592. /** mag = linear and min = nearest and mip = nearest */
  17593. Engine.TEXTURE_LINEAR_NEAREST_MIPNEAREST = 9;
  17594. /** mag = linear and min = nearest and mip = linear */
  17595. Engine.TEXTURE_LINEAR_NEAREST_MIPLINEAR = 10;
  17596. /** mag = linear and min = linear and mip = none */
  17597. Engine.TEXTURE_LINEAR_LINEAR = 11;
  17598. /** mag = linear and min = nearest and mip = none */
  17599. Engine.TEXTURE_LINEAR_NEAREST = 12;
  17600. /** Explicit coordinates mode */
  17601. Engine.TEXTURE_EXPLICIT_MODE = 0;
  17602. /** Spherical coordinates mode */
  17603. Engine.TEXTURE_SPHERICAL_MODE = 1;
  17604. /** Planar coordinates mode */
  17605. Engine.TEXTURE_PLANAR_MODE = 2;
  17606. /** Cubic coordinates mode */
  17607. Engine.TEXTURE_CUBIC_MODE = 3;
  17608. /** Projection coordinates mode */
  17609. Engine.TEXTURE_PROJECTION_MODE = 4;
  17610. /** Skybox coordinates mode */
  17611. Engine.TEXTURE_SKYBOX_MODE = 5;
  17612. /** Inverse Cubic coordinates mode */
  17613. Engine.TEXTURE_INVCUBIC_MODE = 6;
  17614. /** Equirectangular coordinates mode */
  17615. Engine.TEXTURE_EQUIRECTANGULAR_MODE = 7;
  17616. /** Equirectangular Fixed coordinates mode */
  17617. Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MODE = 8;
  17618. /** Equirectangular Fixed Mirrored coordinates mode */
  17619. Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  17620. // Texture rescaling mode
  17621. /** Defines that texture rescaling will use a floor to find the closer power of 2 size */
  17622. Engine.SCALEMODE_FLOOR = 1;
  17623. /** Defines that texture rescaling will look for the nearest power of 2 size */
  17624. Engine.SCALEMODE_NEAREST = 2;
  17625. /** Defines that texture rescaling will use a ceil to find the closer power of 2 size */
  17626. Engine.SCALEMODE_CEILING = 3;
  17627. // Updatable statics so stick with vars here
  17628. /**
  17629. * Gets or sets the epsilon value used by collision engine
  17630. */
  17631. Engine.CollisionsEpsilon = 0.001;
  17632. /**
  17633. * Gets or sets the relative url used to load code if using the engine in non-minified mode
  17634. */
  17635. Engine.CodeRepository = "src/";
  17636. /**
  17637. * Gets or sets the relative url used to load shaders if using the engine in non-minified mode
  17638. */
  17639. Engine.ShadersRepository = "src/Shaders/";
  17640. return Engine;
  17641. }());
  17642. BABYLON.Engine = Engine;
  17643. })(BABYLON || (BABYLON = {}));
  17644. //# sourceMappingURL=babylon.engine.js.map
  17645. var BABYLON;
  17646. (function (BABYLON) {
  17647. /**
  17648. * Node is the basic class for all scene objects (Mesh, Light Camera).
  17649. */
  17650. var Node = /** @class */ (function () {
  17651. /**
  17652. * Creates a new Node
  17653. * @param {string} name - the name and id to be given to this node
  17654. * @param {BABYLON.Scene} the scene this node will be added to
  17655. */
  17656. function Node(name, scene) {
  17657. if (scene === void 0) { scene = null; }
  17658. /**
  17659. * Gets or sets a string used to store user defined state for the node
  17660. */
  17661. this.state = "";
  17662. /**
  17663. * Gets or sets an object used to store user defined information for the node
  17664. */
  17665. this.metadata = null;
  17666. /**
  17667. * Gets or sets a boolean used to define if the node must be serialized
  17668. */
  17669. this.doNotSerialize = false;
  17670. /** @hidden */
  17671. this._isDisposed = false;
  17672. /**
  17673. * Gets a list of Animations associated with the node
  17674. */
  17675. this.animations = new Array();
  17676. this._ranges = {};
  17677. this._isEnabled = true;
  17678. this._isParentEnabled = true;
  17679. this._isReady = true;
  17680. /** @hidden */
  17681. this._currentRenderId = -1;
  17682. this._parentRenderId = -1;
  17683. this._childRenderId = -1;
  17684. /** @hidden */
  17685. this._worldMatrix = BABYLON.Matrix.Identity();
  17686. /** @hidden */
  17687. this._worldMatrixDeterminant = 0;
  17688. this._animationPropertiesOverride = null;
  17689. /**
  17690. * An event triggered when the mesh is disposed
  17691. */
  17692. this.onDisposeObservable = new BABYLON.Observable();
  17693. // Behaviors
  17694. this._behaviors = new Array();
  17695. this.name = name;
  17696. this.id = name;
  17697. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  17698. this.uniqueId = this._scene.getUniqueId();
  17699. this._initCache();
  17700. this._scene.rootNodes.push(this);
  17701. }
  17702. /**
  17703. * Add a new node constructor
  17704. * @param type defines the type name of the node to construct
  17705. * @param constructorFunc defines the constructor function
  17706. */
  17707. Node.AddNodeConstructor = function (type, constructorFunc) {
  17708. this._NodeConstructors[type] = constructorFunc;
  17709. };
  17710. /**
  17711. * Returns a node constructor based on type name
  17712. * @param type defines the type name
  17713. * @param name defines the new node name
  17714. * @param scene defines the hosting scene
  17715. * @param options defines optional options to transmit to constructors
  17716. * @returns the new constructor or null
  17717. */
  17718. Node.Construct = function (type, name, scene, options) {
  17719. var constructorFunc = this._NodeConstructors[type];
  17720. if (!constructorFunc) {
  17721. return null;
  17722. }
  17723. return constructorFunc(name, scene, options);
  17724. };
  17725. /**
  17726. * Gets a boolean indicating if the node has been disposed
  17727. * @returns true if the node was disposed
  17728. */
  17729. Node.prototype.isDisposed = function () {
  17730. return this._isDisposed;
  17731. };
  17732. Object.defineProperty(Node.prototype, "parent", {
  17733. get: function () {
  17734. return this._parentNode;
  17735. },
  17736. /**
  17737. * Gets or sets the parent of the node
  17738. */
  17739. set: function (parent) {
  17740. if (this._parentNode === parent) {
  17741. return;
  17742. }
  17743. var previousParentNode = this._parentNode;
  17744. // Remove self from list of children of parent
  17745. if (this._parentNode && this._parentNode._children !== undefined && this._parentNode._children !== null) {
  17746. var index = this._parentNode._children.indexOf(this);
  17747. if (index !== -1) {
  17748. this._parentNode._children.splice(index, 1);
  17749. }
  17750. if (!parent) {
  17751. // Need to add this node to the rootNodes
  17752. this._scene.rootNodes.push(this);
  17753. }
  17754. }
  17755. // Store new parent
  17756. this._parentNode = parent;
  17757. // Add as child to new parent
  17758. if (this._parentNode) {
  17759. if (this._parentNode._children === undefined || this._parentNode._children === null) {
  17760. this._parentNode._children = new Array();
  17761. }
  17762. this._parentNode._children.push(this);
  17763. if (!previousParentNode) {
  17764. // Need to remove from rootNodes
  17765. var rootNodeIndex = this._scene.rootNodes.indexOf(this);
  17766. if (rootNodeIndex > -1) {
  17767. this._scene.rootNodes.splice(rootNodeIndex, 1);
  17768. }
  17769. }
  17770. }
  17771. // Enabled state
  17772. this._syncParentEnabledState();
  17773. },
  17774. enumerable: true,
  17775. configurable: true
  17776. });
  17777. Object.defineProperty(Node.prototype, "animationPropertiesOverride", {
  17778. /**
  17779. * Gets or sets the animation properties override
  17780. */
  17781. get: function () {
  17782. if (!this._animationPropertiesOverride) {
  17783. return this._scene.animationPropertiesOverride;
  17784. }
  17785. return this._animationPropertiesOverride;
  17786. },
  17787. set: function (value) {
  17788. this._animationPropertiesOverride = value;
  17789. },
  17790. enumerable: true,
  17791. configurable: true
  17792. });
  17793. /**
  17794. * Gets a string idenfifying the name of the class
  17795. * @returns "Node" string
  17796. */
  17797. Node.prototype.getClassName = function () {
  17798. return "Node";
  17799. };
  17800. Object.defineProperty(Node.prototype, "onDispose", {
  17801. /**
  17802. * Sets a callback that will be raised when the node will be disposed
  17803. */
  17804. set: function (callback) {
  17805. if (this._onDisposeObserver) {
  17806. this.onDisposeObservable.remove(this._onDisposeObserver);
  17807. }
  17808. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  17809. },
  17810. enumerable: true,
  17811. configurable: true
  17812. });
  17813. /**
  17814. * Gets the scene of the node
  17815. * @returns a {BABYLON.Scene}
  17816. */
  17817. Node.prototype.getScene = function () {
  17818. return this._scene;
  17819. };
  17820. /**
  17821. * Gets the engine of the node
  17822. * @returns a {BABYLON.Engine}
  17823. */
  17824. Node.prototype.getEngine = function () {
  17825. return this._scene.getEngine();
  17826. };
  17827. /**
  17828. * Attach a behavior to the node
  17829. * @see http://doc.babylonjs.com/features/behaviour
  17830. * @param behavior defines the behavior to attach
  17831. * @param attachImmediately defines that the behavior must be attached even if the scene is still loading
  17832. * @returns the current Node
  17833. */
  17834. Node.prototype.addBehavior = function (behavior, attachImmediately) {
  17835. var _this = this;
  17836. if (attachImmediately === void 0) { attachImmediately = false; }
  17837. var index = this._behaviors.indexOf(behavior);
  17838. if (index !== -1) {
  17839. return this;
  17840. }
  17841. behavior.init();
  17842. if (this._scene.isLoading && !attachImmediately) {
  17843. // We defer the attach when the scene will be loaded
  17844. this._scene.onDataLoadedObservable.addOnce(function () {
  17845. behavior.attach(_this);
  17846. });
  17847. }
  17848. else {
  17849. behavior.attach(this);
  17850. }
  17851. this._behaviors.push(behavior);
  17852. return this;
  17853. };
  17854. /**
  17855. * Remove an attached behavior
  17856. * @see http://doc.babylonjs.com/features/behaviour
  17857. * @param behavior defines the behavior to attach
  17858. * @returns the current Node
  17859. */
  17860. Node.prototype.removeBehavior = function (behavior) {
  17861. var index = this._behaviors.indexOf(behavior);
  17862. if (index === -1) {
  17863. return this;
  17864. }
  17865. this._behaviors[index].detach();
  17866. this._behaviors.splice(index, 1);
  17867. return this;
  17868. };
  17869. Object.defineProperty(Node.prototype, "behaviors", {
  17870. /**
  17871. * Gets the list of attached behaviors
  17872. * @see http://doc.babylonjs.com/features/behaviour
  17873. */
  17874. get: function () {
  17875. return this._behaviors;
  17876. },
  17877. enumerable: true,
  17878. configurable: true
  17879. });
  17880. /**
  17881. * Gets an attached behavior by name
  17882. * @param name defines the name of the behavior to look for
  17883. * @see http://doc.babylonjs.com/features/behaviour
  17884. * @returns null if behavior was not found else the requested behavior
  17885. */
  17886. Node.prototype.getBehaviorByName = function (name) {
  17887. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  17888. var behavior = _a[_i];
  17889. if (behavior.name === name) {
  17890. return behavior;
  17891. }
  17892. }
  17893. return null;
  17894. };
  17895. /**
  17896. * Returns the latest update of the World matrix
  17897. * @returns a Matrix
  17898. */
  17899. Node.prototype.getWorldMatrix = function () {
  17900. if (this._currentRenderId !== this._scene.getRenderId()) {
  17901. this.computeWorldMatrix();
  17902. }
  17903. return this._worldMatrix;
  17904. };
  17905. /** @hidden */
  17906. Node.prototype._getWorldMatrixDeterminant = function () {
  17907. return this._worldMatrixDeterminant;
  17908. };
  17909. Object.defineProperty(Node.prototype, "worldMatrixFromCache", {
  17910. /**
  17911. * Returns directly the latest state of the mesh World matrix.
  17912. * A Matrix is returned.
  17913. */
  17914. get: function () {
  17915. return this._worldMatrix;
  17916. },
  17917. enumerable: true,
  17918. configurable: true
  17919. });
  17920. // override it in derived class if you add new variables to the cache
  17921. // and call the parent class method
  17922. /** @hidden */
  17923. Node.prototype._initCache = function () {
  17924. this._cache = {};
  17925. this._cache.parent = undefined;
  17926. };
  17927. /** @hidden */
  17928. Node.prototype.updateCache = function (force) {
  17929. if (!force && this.isSynchronized())
  17930. return;
  17931. this._cache.parent = this.parent;
  17932. this._updateCache();
  17933. };
  17934. // override it in derived class if you add new variables to the cache
  17935. // and call the parent class method if !ignoreParentClass
  17936. /** @hidden */
  17937. Node.prototype._updateCache = function (ignoreParentClass) {
  17938. };
  17939. // override it in derived class if you add new variables to the cache
  17940. /** @hidden */
  17941. Node.prototype._isSynchronized = function () {
  17942. return true;
  17943. };
  17944. /** @hidden */
  17945. Node.prototype._markSyncedWithParent = function () {
  17946. if (this._parentNode) {
  17947. this._parentRenderId = this._parentNode._childRenderId;
  17948. }
  17949. };
  17950. /** @hidden */
  17951. Node.prototype.isSynchronizedWithParent = function () {
  17952. if (!this._parentNode) {
  17953. return true;
  17954. }
  17955. if (this._parentRenderId !== this._parentNode._childRenderId) {
  17956. return false;
  17957. }
  17958. return this._parentNode.isSynchronized();
  17959. };
  17960. /** @hidden */
  17961. Node.prototype.isSynchronized = function () {
  17962. if (this._cache.parent != this._parentNode) {
  17963. this._cache.parent = this._parentNode;
  17964. return false;
  17965. }
  17966. if (this._parentNode && !this.isSynchronizedWithParent()) {
  17967. return false;
  17968. }
  17969. return this._isSynchronized();
  17970. };
  17971. /**
  17972. * Is this node ready to be used/rendered
  17973. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  17974. * @return true if the node is ready
  17975. */
  17976. Node.prototype.isReady = function (completeCheck) {
  17977. if (completeCheck === void 0) { completeCheck = false; }
  17978. return this._isReady;
  17979. };
  17980. /**
  17981. * Is this node enabled?
  17982. * 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
  17983. * @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
  17984. * @return whether this node (and its parent) is enabled
  17985. */
  17986. Node.prototype.isEnabled = function (checkAncestors) {
  17987. if (checkAncestors === void 0) { checkAncestors = true; }
  17988. if (checkAncestors === false) {
  17989. return this._isEnabled;
  17990. }
  17991. if (!this._isEnabled) {
  17992. return false;
  17993. }
  17994. return this._isParentEnabled;
  17995. };
  17996. /** @hidden */
  17997. Node.prototype._syncParentEnabledState = function () {
  17998. this._isParentEnabled = this._parentNode ? this._parentNode.isEnabled() : true;
  17999. if (this._children) {
  18000. this._children.forEach(function (c) {
  18001. c._syncParentEnabledState(); // Force children to update accordingly
  18002. });
  18003. }
  18004. };
  18005. /**
  18006. * Set the enabled state of this node
  18007. * @param value defines the new enabled state
  18008. */
  18009. Node.prototype.setEnabled = function (value) {
  18010. this._isEnabled = value;
  18011. this._syncParentEnabledState();
  18012. };
  18013. /**
  18014. * Is this node a descendant of the given node?
  18015. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined
  18016. * @param ancestor defines the parent node to inspect
  18017. * @returns a boolean indicating if this node is a descendant of the given node
  18018. */
  18019. Node.prototype.isDescendantOf = function (ancestor) {
  18020. if (this.parent) {
  18021. if (this.parent === ancestor) {
  18022. return true;
  18023. }
  18024. return this.parent.isDescendantOf(ancestor);
  18025. }
  18026. return false;
  18027. };
  18028. /** @hidden */
  18029. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  18030. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  18031. if (!this._children) {
  18032. return;
  18033. }
  18034. for (var index = 0; index < this._children.length; index++) {
  18035. var item = this._children[index];
  18036. if (!predicate || predicate(item)) {
  18037. results.push(item);
  18038. }
  18039. if (!directDescendantsOnly) {
  18040. item._getDescendants(results, false, predicate);
  18041. }
  18042. }
  18043. };
  18044. /**
  18045. * Will return all nodes that have this node as ascendant
  18046. * @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
  18047. * @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
  18048. * @return all children nodes of all types
  18049. */
  18050. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  18051. var results = new Array();
  18052. this._getDescendants(results, directDescendantsOnly, predicate);
  18053. return results;
  18054. };
  18055. /**
  18056. * Get all child-meshes of this node
  18057. * @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
  18058. * @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
  18059. * @returns an array of {BABYLON.AbstractMesh}
  18060. */
  18061. Node.prototype.getChildMeshes = function (directDescendantsOnly, predicate) {
  18062. var results = [];
  18063. this._getDescendants(results, directDescendantsOnly, function (node) {
  18064. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  18065. });
  18066. return results;
  18067. };
  18068. /**
  18069. * Get all child-transformNodes of this node
  18070. * @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
  18071. * @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
  18072. * @returns an array of {BABYLON.TransformNode}
  18073. */
  18074. Node.prototype.getChildTransformNodes = function (directDescendantsOnly, predicate) {
  18075. var results = [];
  18076. this._getDescendants(results, directDescendantsOnly, function (node) {
  18077. return ((!predicate || predicate(node)) && (node instanceof BABYLON.TransformNode));
  18078. });
  18079. return results;
  18080. };
  18081. /**
  18082. * Get all direct children of this node
  18083. * @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
  18084. * @returns an array of {BABYLON.Node}
  18085. */
  18086. Node.prototype.getChildren = function (predicate) {
  18087. return this.getDescendants(true, predicate);
  18088. };
  18089. /** @hidden */
  18090. Node.prototype._setReady = function (state) {
  18091. if (state === this._isReady) {
  18092. return;
  18093. }
  18094. if (!state) {
  18095. this._isReady = false;
  18096. return;
  18097. }
  18098. if (this.onReady) {
  18099. this.onReady(this);
  18100. }
  18101. this._isReady = true;
  18102. };
  18103. /**
  18104. * Get an animation by name
  18105. * @param name defines the name of the animation to look for
  18106. * @returns null if not found else the requested animation
  18107. */
  18108. Node.prototype.getAnimationByName = function (name) {
  18109. for (var i = 0; i < this.animations.length; i++) {
  18110. var animation = this.animations[i];
  18111. if (animation.name === name) {
  18112. return animation;
  18113. }
  18114. }
  18115. return null;
  18116. };
  18117. /**
  18118. * Creates an animation range for this node
  18119. * @param name defines the name of the range
  18120. * @param from defines the starting key
  18121. * @param to defines the end key
  18122. */
  18123. Node.prototype.createAnimationRange = function (name, from, to) {
  18124. // check name not already in use
  18125. if (!this._ranges[name]) {
  18126. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  18127. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  18128. if (this.animations[i]) {
  18129. this.animations[i].createRange(name, from, to);
  18130. }
  18131. }
  18132. }
  18133. };
  18134. /**
  18135. * Delete a specific animation range
  18136. * @param name defines the name of the range to delete
  18137. * @param deleteFrames defines if animation frames from the range must be deleted as well
  18138. */
  18139. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  18140. if (deleteFrames === void 0) { deleteFrames = true; }
  18141. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  18142. if (this.animations[i]) {
  18143. this.animations[i].deleteRange(name, deleteFrames);
  18144. }
  18145. }
  18146. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  18147. };
  18148. /**
  18149. * Get an animation range by name
  18150. * @param name defines the name of the animation range to look for
  18151. * @returns null if not found else the requested animation range
  18152. */
  18153. Node.prototype.getAnimationRange = function (name) {
  18154. return this._ranges[name];
  18155. };
  18156. /**
  18157. * Will start the animation sequence
  18158. * @param name defines the range frames for animation sequence
  18159. * @param loop defines if the animation should loop (false by default)
  18160. * @param speedRatio defines the speed factor in which to run the animation (1 by default)
  18161. * @param onAnimationEnd defines a function to be executed when the animation ended (undefined by default)
  18162. * @returns the object created for this animation. If range does not exist, it will return null
  18163. */
  18164. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  18165. var range = this.getAnimationRange(name);
  18166. if (!range) {
  18167. return null;
  18168. }
  18169. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  18170. };
  18171. /**
  18172. * Serialize animation ranges into a JSON compatible object
  18173. * @returns serialization object
  18174. */
  18175. Node.prototype.serializeAnimationRanges = function () {
  18176. var serializationRanges = [];
  18177. for (var name in this._ranges) {
  18178. var localRange = this._ranges[name];
  18179. if (!localRange) {
  18180. continue;
  18181. }
  18182. var range = {};
  18183. range.name = name;
  18184. range.from = localRange.from;
  18185. range.to = localRange.to;
  18186. serializationRanges.push(range);
  18187. }
  18188. return serializationRanges;
  18189. };
  18190. /**
  18191. * Computes the world matrix of the node
  18192. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  18193. * @returns the world matrix
  18194. */
  18195. Node.prototype.computeWorldMatrix = function (force) {
  18196. if (!this._worldMatrix) {
  18197. this._worldMatrix = BABYLON.Matrix.Identity();
  18198. }
  18199. return this._worldMatrix;
  18200. };
  18201. /**
  18202. * Releases resources associated with this node.
  18203. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  18204. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  18205. */
  18206. Node.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  18207. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  18208. if (!doNotRecurse) {
  18209. var nodes = this.getDescendants(true);
  18210. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  18211. var node = nodes_1[_i];
  18212. node.dispose(doNotRecurse, disposeMaterialAndTextures);
  18213. }
  18214. }
  18215. else {
  18216. var transformNodes = this.getChildTransformNodes(true);
  18217. for (var _a = 0, transformNodes_1 = transformNodes; _a < transformNodes_1.length; _a++) {
  18218. var transformNode = transformNodes_1[_a];
  18219. transformNode.parent = null;
  18220. transformNode.computeWorldMatrix(true);
  18221. }
  18222. }
  18223. if (!this.parent) {
  18224. var rootNodeIndex = this._scene.rootNodes.indexOf(this);
  18225. if (rootNodeIndex > -1) {
  18226. this._scene.rootNodes.splice(rootNodeIndex, 1);
  18227. }
  18228. }
  18229. else {
  18230. this.parent = null;
  18231. }
  18232. // Callback
  18233. this.onDisposeObservable.notifyObservers(this);
  18234. this.onDisposeObservable.clear();
  18235. // Behaviors
  18236. for (var _b = 0, _c = this._behaviors; _b < _c.length; _b++) {
  18237. var behavior = _c[_b];
  18238. behavior.detach();
  18239. }
  18240. this._behaviors = [];
  18241. this._isDisposed = true;
  18242. };
  18243. /**
  18244. * Parse animation range data from a serialization object and store them into a given node
  18245. * @param node defines where to store the animation ranges
  18246. * @param parsedNode defines the serialization object to read data from
  18247. * @param scene defines the hosting scene
  18248. */
  18249. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  18250. if (parsedNode.ranges) {
  18251. for (var index = 0; index < parsedNode.ranges.length; index++) {
  18252. var data = parsedNode.ranges[index];
  18253. node.createAnimationRange(data.name, data.from, data.to);
  18254. }
  18255. }
  18256. };
  18257. Node._NodeConstructors = {};
  18258. __decorate([
  18259. BABYLON.serialize()
  18260. ], Node.prototype, "name", void 0);
  18261. __decorate([
  18262. BABYLON.serialize()
  18263. ], Node.prototype, "id", void 0);
  18264. __decorate([
  18265. BABYLON.serialize()
  18266. ], Node.prototype, "uniqueId", void 0);
  18267. __decorate([
  18268. BABYLON.serialize()
  18269. ], Node.prototype, "state", void 0);
  18270. __decorate([
  18271. BABYLON.serialize()
  18272. ], Node.prototype, "metadata", void 0);
  18273. return Node;
  18274. }());
  18275. BABYLON.Node = Node;
  18276. })(BABYLON || (BABYLON = {}));
  18277. //# sourceMappingURL=babylon.node.js.map
  18278. var BABYLON;
  18279. (function (BABYLON) {
  18280. // This matrix is used as a value to reset the bounding box.
  18281. var _identityMatrix = BABYLON.Matrix.Identity();
  18282. var _tempRadiusVector = new BABYLON.Vector3(0, 0, 0);
  18283. var BoundingSphere = /** @class */ (function () {
  18284. /**
  18285. * Creates a new bounding sphere
  18286. * @param min defines the minimum vector (in local space)
  18287. * @param max defines the maximum vector (in local space)
  18288. */
  18289. function BoundingSphere(min, max) {
  18290. this.center = BABYLON.Vector3.Zero();
  18291. this.centerWorld = BABYLON.Vector3.Zero();
  18292. this.reConstruct(min, max);
  18293. }
  18294. /**
  18295. * Recreates the entire bounding sphere from scratch
  18296. * @param min defines the new minimum vector (in local space)
  18297. * @param max defines the new maximum vector (in local space)
  18298. */
  18299. BoundingSphere.prototype.reConstruct = function (min, max) {
  18300. this.minimum = min.clone();
  18301. this.maximum = max.clone();
  18302. var distance = BABYLON.Vector3.Distance(min, max);
  18303. BABYLON.Vector3.LerpToRef(min, max, 0.5, this.center);
  18304. this.radius = distance * 0.5;
  18305. this.centerWorld.set(0, 0, 0);
  18306. this._update(_identityMatrix);
  18307. };
  18308. /**
  18309. * Scale the current bounding sphere by applying a scale factor
  18310. * @param factor defines the scale factor to apply
  18311. * @returns the current bounding box
  18312. */
  18313. BoundingSphere.prototype.scale = function (factor) {
  18314. var newRadius = this.radius * factor;
  18315. _tempRadiusVector.set(newRadius, newRadius, newRadius);
  18316. var min = this.center.subtract(_tempRadiusVector);
  18317. var max = this.center.add(_tempRadiusVector);
  18318. this.reConstruct(min, max);
  18319. return this;
  18320. };
  18321. // Methods
  18322. /** @hidden */
  18323. BoundingSphere.prototype._update = function (world) {
  18324. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  18325. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, _tempRadiusVector);
  18326. this.radiusWorld = Math.max(Math.abs(_tempRadiusVector.x), Math.abs(_tempRadiusVector.y), Math.abs(_tempRadiusVector.z)) * this.radius;
  18327. };
  18328. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  18329. for (var i = 0; i < 6; i++) {
  18330. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  18331. return false;
  18332. }
  18333. return true;
  18334. };
  18335. BoundingSphere.prototype.intersectsPoint = function (point) {
  18336. var x = this.centerWorld.x - point.x;
  18337. var y = this.centerWorld.y - point.y;
  18338. var z = this.centerWorld.z - point.z;
  18339. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  18340. if (this.radiusWorld < distance)
  18341. return false;
  18342. return true;
  18343. };
  18344. // Statics
  18345. BoundingSphere.Intersects = function (sphere0, sphere1) {
  18346. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  18347. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  18348. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  18349. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  18350. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  18351. return false;
  18352. return true;
  18353. };
  18354. return BoundingSphere;
  18355. }());
  18356. BABYLON.BoundingSphere = BoundingSphere;
  18357. })(BABYLON || (BABYLON = {}));
  18358. //# sourceMappingURL=babylon.boundingSphere.js.map
  18359. var BABYLON;
  18360. (function (BABYLON) {
  18361. /**
  18362. * Class used to store bounding box information
  18363. */
  18364. var BoundingBox = /** @class */ (function () {
  18365. /**
  18366. * Creates a new bounding box
  18367. * @param min defines the minimum vector (in local space)
  18368. * @param max defines the maximum vector (in local space)
  18369. */
  18370. function BoundingBox(min, max) {
  18371. /**
  18372. * Gets the 8 vectors representing the bounding box in world space
  18373. */
  18374. this.vectorsWorld = new Array();
  18375. this.reConstruct(min, max);
  18376. }
  18377. // Methods
  18378. /**
  18379. * Recreates the entire bounding box from scratch
  18380. * @param min defines the new minimum vector (in local space)
  18381. * @param max defines the new maximum vector (in local space)
  18382. */
  18383. BoundingBox.prototype.reConstruct = function (min, max) {
  18384. this.minimum = min.clone();
  18385. this.maximum = max.clone();
  18386. // Bounding vectors
  18387. this.vectors = [
  18388. this.minimum.clone(),
  18389. this.maximum.clone(),
  18390. this.minimum.clone(),
  18391. this.minimum.clone(),
  18392. this.minimum.clone(),
  18393. this.maximum.clone(),
  18394. this.maximum.clone(),
  18395. this.maximum.clone()
  18396. ];
  18397. this.vectors[2].x = this.maximum.x;
  18398. this.vectors[3].y = this.maximum.y;
  18399. this.vectors[4].z = this.maximum.z;
  18400. this.vectors[5].z = this.minimum.z;
  18401. this.vectors[6].x = this.minimum.x;
  18402. this.vectors[7].y = this.minimum.y;
  18403. // OBB
  18404. this.center = this.maximum.add(this.minimum).scale(0.5);
  18405. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  18406. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  18407. // World
  18408. for (var index = 0; index < this.vectors.length; index++) {
  18409. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  18410. }
  18411. this.minimumWorld = BABYLON.Vector3.Zero();
  18412. this.maximumWorld = BABYLON.Vector3.Zero();
  18413. this.centerWorld = BABYLON.Vector3.Zero();
  18414. this.extendSizeWorld = BABYLON.Vector3.Zero();
  18415. this._update(this._worldMatrix || BABYLON.Matrix.Identity());
  18416. };
  18417. /**
  18418. * Scale the current bounding box by applying a scale factor
  18419. * @param factor defines the scale factor to apply
  18420. * @returns the current bounding box
  18421. */
  18422. BoundingBox.prototype.scale = function (factor) {
  18423. var diff = this.maximum.subtract(this.minimum);
  18424. var distance = diff.length() * factor;
  18425. diff.normalize();
  18426. var newRadius = diff.scale(distance / 2);
  18427. var min = this.center.subtract(newRadius);
  18428. var max = this.center.add(newRadius);
  18429. this.reConstruct(min, max);
  18430. return this;
  18431. };
  18432. /**
  18433. * Gets the world matrix of the bounding box
  18434. * @returns a matrix
  18435. */
  18436. BoundingBox.prototype.getWorldMatrix = function () {
  18437. return this._worldMatrix;
  18438. };
  18439. /**
  18440. * Sets the world matrix stored in the bounding box
  18441. * @param matrix defines the matrix to store
  18442. * @returns current bounding box
  18443. */
  18444. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  18445. this._worldMatrix.copyFrom(matrix);
  18446. return this;
  18447. };
  18448. /** @hidden */
  18449. BoundingBox.prototype._update = function (world) {
  18450. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  18451. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  18452. for (var index = 0; index < this.vectors.length; index++) {
  18453. var v = this.vectorsWorld[index];
  18454. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  18455. if (v.x < this.minimumWorld.x)
  18456. this.minimumWorld.x = v.x;
  18457. if (v.y < this.minimumWorld.y)
  18458. this.minimumWorld.y = v.y;
  18459. if (v.z < this.minimumWorld.z)
  18460. this.minimumWorld.z = v.z;
  18461. if (v.x > this.maximumWorld.x)
  18462. this.maximumWorld.x = v.x;
  18463. if (v.y > this.maximumWorld.y)
  18464. this.maximumWorld.y = v.y;
  18465. if (v.z > this.maximumWorld.z)
  18466. this.maximumWorld.z = v.z;
  18467. }
  18468. // Extend
  18469. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  18470. this.extendSizeWorld.scaleInPlace(0.5);
  18471. // OBB
  18472. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  18473. this.centerWorld.scaleInPlace(0.5);
  18474. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  18475. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  18476. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  18477. this._worldMatrix = world;
  18478. };
  18479. /**
  18480. * Tests if the bounding box is intersecting the frustum planes
  18481. * @param frustumPlanes defines the frustum planes to test
  18482. * @returns true if there is an intersection
  18483. */
  18484. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  18485. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  18486. };
  18487. /**
  18488. * Tests if the bounding box is entirely inside the frustum planes
  18489. * @param frustumPlanes defines the frustum planes to test
  18490. * @returns true if there is an inclusion
  18491. */
  18492. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  18493. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  18494. };
  18495. /**
  18496. * Tests if a point is inside the bounding box
  18497. * @param point defines the point to test
  18498. * @returns true if the point is inside the bounding box
  18499. */
  18500. BoundingBox.prototype.intersectsPoint = function (point) {
  18501. var delta = -BABYLON.Epsilon;
  18502. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  18503. return false;
  18504. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  18505. return false;
  18506. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  18507. return false;
  18508. return true;
  18509. };
  18510. /**
  18511. * Tests if the bounding box intersects with a bounding sphere
  18512. * @param sphere defines the sphere to test
  18513. * @returns true if there is an intersection
  18514. */
  18515. BoundingBox.prototype.intersectsSphere = function (sphere) {
  18516. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  18517. };
  18518. /**
  18519. * Tests if the bounding box intersects with a box defined by a min and max vectors
  18520. * @param min defines the min vector to use
  18521. * @param max defines the max vector to use
  18522. * @returns true if there is an intersection
  18523. */
  18524. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  18525. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  18526. return false;
  18527. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  18528. return false;
  18529. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  18530. return false;
  18531. return true;
  18532. };
  18533. // Statics
  18534. /**
  18535. * Tests if two bounding boxes are intersections
  18536. * @param box0 defines the first box to test
  18537. * @param box1 defines the second box to test
  18538. * @returns true if there is an intersection
  18539. */
  18540. BoundingBox.Intersects = function (box0, box1) {
  18541. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  18542. return false;
  18543. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  18544. return false;
  18545. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  18546. return false;
  18547. return true;
  18548. };
  18549. /**
  18550. * Tests if a bounding box defines by a min/max vectors intersects a sphere
  18551. * @param minPoint defines the minimum vector of the bounding box
  18552. * @param maxPoint defines the maximum vector of the bounding box
  18553. * @param sphereCenter defines the sphere center
  18554. * @param sphereRadius defines the sphere radius
  18555. * @returns true if there is an intersection
  18556. */
  18557. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  18558. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  18559. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  18560. return (num <= (sphereRadius * sphereRadius));
  18561. };
  18562. /**
  18563. * Tests if a bounding box defined with 8 vectors is entirely inside frustum planes
  18564. * @param boundingVectors defines an array of 8 vectors representing a bounding box
  18565. * @param frustumPlanes defines the frustum planes to test
  18566. * @return true if there is an inclusion
  18567. */
  18568. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  18569. for (var p = 0; p < 6; p++) {
  18570. for (var i = 0; i < 8; i++) {
  18571. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  18572. return false;
  18573. }
  18574. }
  18575. }
  18576. return true;
  18577. };
  18578. /**
  18579. * Tests if a bounding box defined with 8 vectors intersects frustum planes
  18580. * @param boundingVectors defines an array of 8 vectors representing a bounding box
  18581. * @param frustumPlanes defines the frustum planes to test
  18582. * @return true if there is an intersection
  18583. */
  18584. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  18585. for (var p = 0; p < 6; p++) {
  18586. var inCount = 8;
  18587. for (var i = 0; i < 8; i++) {
  18588. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  18589. --inCount;
  18590. }
  18591. else {
  18592. break;
  18593. }
  18594. }
  18595. if (inCount === 0)
  18596. return false;
  18597. }
  18598. return true;
  18599. };
  18600. return BoundingBox;
  18601. }());
  18602. BABYLON.BoundingBox = BoundingBox;
  18603. })(BABYLON || (BABYLON = {}));
  18604. //# sourceMappingURL=babylon.boundingBox.js.map
  18605. var BABYLON;
  18606. (function (BABYLON) {
  18607. var computeBoxExtents = function (axis, box) {
  18608. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  18609. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  18610. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  18611. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  18612. var r = r0 + r1 + r2;
  18613. return {
  18614. min: p - r,
  18615. max: p + r
  18616. };
  18617. };
  18618. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  18619. var axisOverlap = function (axis, box0, box1) {
  18620. var result0 = computeBoxExtents(axis, box0);
  18621. var result1 = computeBoxExtents(axis, box1);
  18622. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  18623. };
  18624. var BoundingInfo = /** @class */ (function () {
  18625. function BoundingInfo(minimum, maximum) {
  18626. this.minimum = minimum;
  18627. this.maximum = maximum;
  18628. this._isLocked = false;
  18629. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  18630. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  18631. }
  18632. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  18633. get: function () {
  18634. return this._isLocked;
  18635. },
  18636. set: function (value) {
  18637. this._isLocked = value;
  18638. },
  18639. enumerable: true,
  18640. configurable: true
  18641. });
  18642. // Methods
  18643. BoundingInfo.prototype.update = function (world) {
  18644. if (this._isLocked) {
  18645. return;
  18646. }
  18647. this.boundingBox._update(world);
  18648. this.boundingSphere._update(world);
  18649. };
  18650. /**
  18651. * Recreate the bounding info to be centered around a specific point given a specific extend.
  18652. * @param center New center of the bounding info
  18653. * @param extend New extend of the bounding info
  18654. */
  18655. BoundingInfo.prototype.centerOn = function (center, extend) {
  18656. this.minimum = center.subtract(extend);
  18657. this.maximum = center.add(extend);
  18658. this.boundingBox = new BABYLON.BoundingBox(this.minimum, this.maximum);
  18659. this.boundingSphere = new BABYLON.BoundingSphere(this.minimum, this.maximum);
  18660. return this;
  18661. };
  18662. /**
  18663. * Scale the current bounding info by applying a scale factor
  18664. * @param factor defines the scale factor to apply
  18665. * @returns the current bounding info
  18666. */
  18667. BoundingInfo.prototype.scale = function (factor) {
  18668. this.boundingBox.scale(factor);
  18669. this.boundingSphere.scale(factor);
  18670. return this;
  18671. };
  18672. /**
  18673. * Returns `true` if the bounding info is within the frustum defined by the passed array of planes.
  18674. * @param frustumPlanes defines the frustum to test
  18675. * @param strategy defines the strategy to use for the culling (default is BABYLON.Scene.CULLINGSTRATEGY_STANDARD)
  18676. * @returns true if the bounding info is in the frustum planes
  18677. */
  18678. BoundingInfo.prototype.isInFrustum = function (frustumPlanes, strategy) {
  18679. if (strategy === void 0) { strategy = BABYLON.AbstractMesh.CULLINGSTRATEGY_STANDARD; }
  18680. if (!this.boundingSphere.isInFrustum(frustumPlanes)) {
  18681. return false;
  18682. }
  18683. if (strategy === BABYLON.AbstractMesh.CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY) {
  18684. return true;
  18685. }
  18686. return this.boundingBox.isInFrustum(frustumPlanes);
  18687. };
  18688. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  18689. /**
  18690. * Gets the world distance between the min and max points of the bounding box
  18691. */
  18692. get: function () {
  18693. var boundingBox = this.boundingBox;
  18694. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  18695. return size.length();
  18696. },
  18697. enumerable: true,
  18698. configurable: true
  18699. });
  18700. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  18701. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  18702. };
  18703. /** @hidden */
  18704. BoundingInfo.prototype._checkCollision = function (collider) {
  18705. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  18706. };
  18707. BoundingInfo.prototype.intersectsPoint = function (point) {
  18708. if (!this.boundingSphere.centerWorld) {
  18709. return false;
  18710. }
  18711. if (!this.boundingSphere.intersectsPoint(point)) {
  18712. return false;
  18713. }
  18714. if (!this.boundingBox.intersectsPoint(point)) {
  18715. return false;
  18716. }
  18717. return true;
  18718. };
  18719. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  18720. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  18721. return false;
  18722. }
  18723. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  18724. return false;
  18725. }
  18726. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  18727. return false;
  18728. }
  18729. if (!precise) {
  18730. return true;
  18731. }
  18732. var box0 = this.boundingBox;
  18733. var box1 = boundingInfo.boundingBox;
  18734. if (!axisOverlap(box0.directions[0], box0, box1))
  18735. return false;
  18736. if (!axisOverlap(box0.directions[1], box0, box1))
  18737. return false;
  18738. if (!axisOverlap(box0.directions[2], box0, box1))
  18739. return false;
  18740. if (!axisOverlap(box1.directions[0], box0, box1))
  18741. return false;
  18742. if (!axisOverlap(box1.directions[1], box0, box1))
  18743. return false;
  18744. if (!axisOverlap(box1.directions[2], box0, box1))
  18745. return false;
  18746. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  18747. return false;
  18748. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  18749. return false;
  18750. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  18751. return false;
  18752. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  18753. return false;
  18754. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  18755. return false;
  18756. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  18757. return false;
  18758. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  18759. return false;
  18760. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  18761. return false;
  18762. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  18763. return false;
  18764. return true;
  18765. };
  18766. return BoundingInfo;
  18767. }());
  18768. BABYLON.BoundingInfo = BoundingInfo;
  18769. })(BABYLON || (BABYLON = {}));
  18770. //# sourceMappingURL=babylon.boundingInfo.js.map
  18771. var BABYLON;
  18772. (function (BABYLON) {
  18773. var TransformNode = /** @class */ (function (_super) {
  18774. __extends(TransformNode, _super);
  18775. function TransformNode(name, scene, isPure) {
  18776. if (scene === void 0) { scene = null; }
  18777. if (isPure === void 0) { isPure = true; }
  18778. var _this = _super.call(this, name, scene) || this;
  18779. _this._forward = new BABYLON.Vector3(0, 0, 1);
  18780. _this._forwardInverted = new BABYLON.Vector3(0, 0, -1);
  18781. _this._up = new BABYLON.Vector3(0, 1, 0);
  18782. _this._right = new BABYLON.Vector3(1, 0, 0);
  18783. _this._rightInverted = new BABYLON.Vector3(-1, 0, 0);
  18784. // Properties
  18785. _this._position = BABYLON.Vector3.Zero();
  18786. _this._rotation = BABYLON.Vector3.Zero();
  18787. _this._scaling = BABYLON.Vector3.One();
  18788. _this._isDirty = false;
  18789. /**
  18790. * Set the billboard mode. Default is 0.
  18791. *
  18792. * | Value | Type | Description |
  18793. * | --- | --- | --- |
  18794. * | 0 | BILLBOARDMODE_NONE | |
  18795. * | 1 | BILLBOARDMODE_X | |
  18796. * | 2 | BILLBOARDMODE_Y | |
  18797. * | 4 | BILLBOARDMODE_Z | |
  18798. * | 7 | BILLBOARDMODE_ALL | |
  18799. *
  18800. */
  18801. _this.billboardMode = TransformNode.BILLBOARDMODE_NONE;
  18802. _this.scalingDeterminant = 1;
  18803. _this.infiniteDistance = false;
  18804. /**
  18805. * Gets or sets a boolean indicating that non uniform scaling (when at least one component is different from others) should be ignored.
  18806. * By default the system will update normals to compensate
  18807. */
  18808. _this.ignoreNonUniformScaling = false;
  18809. _this._localWorld = BABYLON.Matrix.Zero();
  18810. _this._absolutePosition = BABYLON.Vector3.Zero();
  18811. _this._pivotMatrix = BABYLON.Matrix.Identity();
  18812. _this._postMultiplyPivotMatrix = false;
  18813. _this._isWorldMatrixFrozen = false;
  18814. /**
  18815. * An event triggered after the world matrix is updated
  18816. */
  18817. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  18818. _this._nonUniformScaling = false;
  18819. if (isPure) {
  18820. _this.getScene().addTransformNode(_this);
  18821. }
  18822. return _this;
  18823. }
  18824. /**
  18825. * Gets a string identifying the name of the class
  18826. * @returns "TransformNode" string
  18827. */
  18828. TransformNode.prototype.getClassName = function () {
  18829. return "TransformNode";
  18830. };
  18831. Object.defineProperty(TransformNode.prototype, "position", {
  18832. /**
  18833. * Gets or set the node position (default is (0.0, 0.0, 0.0))
  18834. */
  18835. get: function () {
  18836. return this._position;
  18837. },
  18838. set: function (newPosition) {
  18839. this._position = newPosition;
  18840. this._isDirty = true;
  18841. },
  18842. enumerable: true,
  18843. configurable: true
  18844. });
  18845. Object.defineProperty(TransformNode.prototype, "rotation", {
  18846. /**
  18847. * Gets or sets the rotation property : a Vector3 defining the rotation value in radians around each local axis X, Y, Z (default is (0.0, 0.0, 0.0)).
  18848. * If rotation quaternion is set, this Vector3 will be ignored and copy from the quaternion
  18849. */
  18850. get: function () {
  18851. return this._rotation;
  18852. },
  18853. set: function (newRotation) {
  18854. this._rotation = newRotation;
  18855. this._isDirty = true;
  18856. },
  18857. enumerable: true,
  18858. configurable: true
  18859. });
  18860. Object.defineProperty(TransformNode.prototype, "scaling", {
  18861. /**
  18862. * Gets or sets the scaling property : a Vector3 defining the node scaling along each local axis X, Y, Z (default is (0.0, 0.0, 0.0)).
  18863. */
  18864. get: function () {
  18865. return this._scaling;
  18866. },
  18867. set: function (newScaling) {
  18868. this._scaling = newScaling;
  18869. this._isDirty = true;
  18870. },
  18871. enumerable: true,
  18872. configurable: true
  18873. });
  18874. Object.defineProperty(TransformNode.prototype, "rotationQuaternion", {
  18875. /**
  18876. * Gets or sets the rotation Quaternion property : this a Quaternion object defining the node rotation by using a unit quaternion (null by default).
  18877. * If set, only the rotationQuaternion is then used to compute the node rotation (ie. node.rotation will be ignored)
  18878. */
  18879. get: function () {
  18880. return this._rotationQuaternion;
  18881. },
  18882. set: function (quaternion) {
  18883. this._rotationQuaternion = quaternion;
  18884. //reset the rotation vector.
  18885. if (quaternion && this.rotation.length()) {
  18886. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  18887. }
  18888. },
  18889. enumerable: true,
  18890. configurable: true
  18891. });
  18892. Object.defineProperty(TransformNode.prototype, "forward", {
  18893. /**
  18894. * The forward direction of that transform in world space.
  18895. */
  18896. get: function () {
  18897. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._forwardInverted : this._forward, this.getWorldMatrix()));
  18898. },
  18899. enumerable: true,
  18900. configurable: true
  18901. });
  18902. Object.defineProperty(TransformNode.prototype, "up", {
  18903. /**
  18904. * The up direction of that transform in world space.
  18905. */
  18906. get: function () {
  18907. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this._up, this.getWorldMatrix()));
  18908. },
  18909. enumerable: true,
  18910. configurable: true
  18911. });
  18912. Object.defineProperty(TransformNode.prototype, "right", {
  18913. /**
  18914. * The right direction of that transform in world space.
  18915. */
  18916. get: function () {
  18917. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._rightInverted : this._right, this.getWorldMatrix()));
  18918. },
  18919. enumerable: true,
  18920. configurable: true
  18921. });
  18922. /**
  18923. * Copies the parameter passed Matrix into the mesh Pose matrix.
  18924. * Returns the TransformNode.
  18925. */
  18926. TransformNode.prototype.updatePoseMatrix = function (matrix) {
  18927. this._poseMatrix.copyFrom(matrix);
  18928. return this;
  18929. };
  18930. /**
  18931. * Returns the mesh Pose matrix.
  18932. * Returned object : Matrix
  18933. */
  18934. TransformNode.prototype.getPoseMatrix = function () {
  18935. return this._poseMatrix;
  18936. };
  18937. /** @hidden */
  18938. TransformNode.prototype._isSynchronized = function () {
  18939. if (this._isDirty) {
  18940. return false;
  18941. }
  18942. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== TransformNode.BILLBOARDMODE_NONE)
  18943. return false;
  18944. if (this._cache.pivotMatrixUpdated) {
  18945. return false;
  18946. }
  18947. if (this.infiniteDistance) {
  18948. return false;
  18949. }
  18950. if (!this._cache.position.equals(this._position))
  18951. return false;
  18952. if (this._rotationQuaternion) {
  18953. if (!this._cache.rotationQuaternion.equals(this._rotationQuaternion))
  18954. return false;
  18955. }
  18956. if (!this._cache.rotation.equals(this._rotation))
  18957. return false;
  18958. if (!this._cache.scaling.equals(this._scaling))
  18959. return false;
  18960. return true;
  18961. };
  18962. /** @hidden */
  18963. TransformNode.prototype._initCache = function () {
  18964. _super.prototype._initCache.call(this);
  18965. this._cache.localMatrixUpdated = false;
  18966. this._cache.position = BABYLON.Vector3.Zero();
  18967. this._cache.scaling = BABYLON.Vector3.Zero();
  18968. this._cache.rotation = BABYLON.Vector3.Zero();
  18969. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  18970. this._cache.billboardMode = -1;
  18971. };
  18972. TransformNode.prototype.markAsDirty = function (property) {
  18973. if (property === "rotation") {
  18974. this.rotationQuaternion = null;
  18975. }
  18976. this._currentRenderId = Number.MAX_VALUE;
  18977. this._isDirty = true;
  18978. return this;
  18979. };
  18980. Object.defineProperty(TransformNode.prototype, "absolutePosition", {
  18981. /**
  18982. * Returns the current mesh absolute position.
  18983. * Returns a Vector3.
  18984. */
  18985. get: function () {
  18986. return this._absolutePosition;
  18987. },
  18988. enumerable: true,
  18989. configurable: true
  18990. });
  18991. /**
  18992. * Sets a new matrix to apply before all other transformation
  18993. * @param matrix defines the transform matrix
  18994. * @returns the current TransformNode
  18995. */
  18996. TransformNode.prototype.setPreTransformMatrix = function (matrix) {
  18997. return this.setPivotMatrix(matrix, false);
  18998. };
  18999. /**
  19000. * Sets a new pivot matrix to the current node
  19001. * @param matrix defines the new pivot matrix to use
  19002. * @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
  19003. * @returns the current TransformNode
  19004. */
  19005. TransformNode.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
  19006. if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = true; }
  19007. this._pivotMatrix = matrix.clone();
  19008. this._cache.pivotMatrixUpdated = true;
  19009. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  19010. if (this._postMultiplyPivotMatrix) {
  19011. if (!this._pivotMatrixInverse) {
  19012. this._pivotMatrixInverse = BABYLON.Matrix.Invert(this._pivotMatrix);
  19013. }
  19014. else {
  19015. this._pivotMatrix.invertToRef(this._pivotMatrixInverse);
  19016. }
  19017. }
  19018. return this;
  19019. };
  19020. /**
  19021. * Returns the mesh pivot matrix.
  19022. * Default : Identity.
  19023. * A Matrix is returned.
  19024. */
  19025. TransformNode.prototype.getPivotMatrix = function () {
  19026. return this._pivotMatrix;
  19027. };
  19028. /**
  19029. * Prevents the World matrix to be computed any longer.
  19030. * Returns the TransformNode.
  19031. */
  19032. TransformNode.prototype.freezeWorldMatrix = function () {
  19033. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  19034. this.computeWorldMatrix(true);
  19035. this._isWorldMatrixFrozen = true;
  19036. return this;
  19037. };
  19038. /**
  19039. * Allows back the World matrix computation.
  19040. * Returns the TransformNode.
  19041. */
  19042. TransformNode.prototype.unfreezeWorldMatrix = function () {
  19043. this._isWorldMatrixFrozen = false;
  19044. this.computeWorldMatrix(true);
  19045. return this;
  19046. };
  19047. Object.defineProperty(TransformNode.prototype, "isWorldMatrixFrozen", {
  19048. /**
  19049. * True if the World matrix has been frozen.
  19050. * Returns a boolean.
  19051. */
  19052. get: function () {
  19053. return this._isWorldMatrixFrozen;
  19054. },
  19055. enumerable: true,
  19056. configurable: true
  19057. });
  19058. /**
  19059. * Retuns the mesh absolute position in the World.
  19060. * Returns a Vector3.
  19061. */
  19062. TransformNode.prototype.getAbsolutePosition = function () {
  19063. this.computeWorldMatrix();
  19064. return this._absolutePosition;
  19065. };
  19066. /**
  19067. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  19068. * Returns the TransformNode.
  19069. */
  19070. TransformNode.prototype.setAbsolutePosition = function (absolutePosition) {
  19071. if (!absolutePosition) {
  19072. return this;
  19073. }
  19074. var absolutePositionX;
  19075. var absolutePositionY;
  19076. var absolutePositionZ;
  19077. if (absolutePosition.x === undefined) {
  19078. if (arguments.length < 3) {
  19079. return this;
  19080. }
  19081. absolutePositionX = arguments[0];
  19082. absolutePositionY = arguments[1];
  19083. absolutePositionZ = arguments[2];
  19084. }
  19085. else {
  19086. absolutePositionX = absolutePosition.x;
  19087. absolutePositionY = absolutePosition.y;
  19088. absolutePositionZ = absolutePosition.z;
  19089. }
  19090. if (this.parent) {
  19091. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  19092. invertParentWorldMatrix.invert();
  19093. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  19094. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  19095. }
  19096. else {
  19097. this.position.x = absolutePositionX;
  19098. this.position.y = absolutePositionY;
  19099. this.position.z = absolutePositionZ;
  19100. }
  19101. return this;
  19102. };
  19103. /**
  19104. * Sets the mesh position in its local space.
  19105. * Returns the TransformNode.
  19106. */
  19107. TransformNode.prototype.setPositionWithLocalVector = function (vector3) {
  19108. this.computeWorldMatrix();
  19109. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  19110. return this;
  19111. };
  19112. /**
  19113. * Returns the mesh position in the local space from the current World matrix values.
  19114. * Returns a new Vector3.
  19115. */
  19116. TransformNode.prototype.getPositionExpressedInLocalSpace = function () {
  19117. this.computeWorldMatrix();
  19118. var invLocalWorldMatrix = this._localWorld.clone();
  19119. invLocalWorldMatrix.invert();
  19120. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  19121. };
  19122. /**
  19123. * Translates the mesh along the passed Vector3 in its local space.
  19124. * Returns the TransformNode.
  19125. */
  19126. TransformNode.prototype.locallyTranslate = function (vector3) {
  19127. this.computeWorldMatrix(true);
  19128. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  19129. return this;
  19130. };
  19131. /**
  19132. * Orients a mesh towards a target point. Mesh must be drawn facing user.
  19133. * @param targetPoint the position (must be in same space as current mesh) to look at
  19134. * @param yawCor optional yaw (y-axis) correction in radians
  19135. * @param pitchCor optional pitch (x-axis) correction in radians
  19136. * @param rollCor optional roll (z-axis) correction in radians
  19137. * @param space the choosen space of the target
  19138. * @returns the TransformNode.
  19139. */
  19140. TransformNode.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  19141. if (yawCor === void 0) { yawCor = 0; }
  19142. if (pitchCor === void 0) { pitchCor = 0; }
  19143. if (rollCor === void 0) { rollCor = 0; }
  19144. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  19145. var dv = TransformNode._lookAtVectorCache;
  19146. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  19147. targetPoint.subtractToRef(pos, dv);
  19148. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  19149. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  19150. var pitch = Math.atan2(dv.y, len);
  19151. if (this.rotationQuaternion) {
  19152. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  19153. }
  19154. else {
  19155. this.rotation.x = pitch + pitchCor;
  19156. this.rotation.y = yaw + yawCor;
  19157. this.rotation.z = rollCor;
  19158. }
  19159. return this;
  19160. };
  19161. /**
  19162. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  19163. * This Vector3 is expressed in the World space.
  19164. */
  19165. TransformNode.prototype.getDirection = function (localAxis) {
  19166. var result = BABYLON.Vector3.Zero();
  19167. this.getDirectionToRef(localAxis, result);
  19168. return result;
  19169. };
  19170. /**
  19171. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  19172. * localAxis is expressed in the mesh local space.
  19173. * result is computed in the Wordl space from the mesh World matrix.
  19174. * Returns the TransformNode.
  19175. */
  19176. TransformNode.prototype.getDirectionToRef = function (localAxis, result) {
  19177. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  19178. return this;
  19179. };
  19180. /**
  19181. * Sets a new pivot point to the current node
  19182. * @param point defines the new pivot point to use
  19183. * @param space defines if the point is in world or local space (local by default)
  19184. * @returns the current TransformNode
  19185. */
  19186. TransformNode.prototype.setPivotPoint = function (point, space) {
  19187. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  19188. if (this.getScene().getRenderId() == 0) {
  19189. this.computeWorldMatrix(true);
  19190. }
  19191. var wm = this.getWorldMatrix();
  19192. if (space == BABYLON.Space.WORLD) {
  19193. var tmat = BABYLON.Tmp.Matrix[0];
  19194. wm.invertToRef(tmat);
  19195. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  19196. }
  19197. return this.setPivotMatrix(BABYLON.Matrix.Translation(-point.x, -point.y, -point.z), true);
  19198. };
  19199. /**
  19200. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  19201. */
  19202. TransformNode.prototype.getPivotPoint = function () {
  19203. var point = BABYLON.Vector3.Zero();
  19204. this.getPivotPointToRef(point);
  19205. return point;
  19206. };
  19207. /**
  19208. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  19209. * Returns the TransformNode.
  19210. */
  19211. TransformNode.prototype.getPivotPointToRef = function (result) {
  19212. result.x = -this._pivotMatrix.m[12];
  19213. result.y = -this._pivotMatrix.m[13];
  19214. result.z = -this._pivotMatrix.m[14];
  19215. return this;
  19216. };
  19217. /**
  19218. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  19219. */
  19220. TransformNode.prototype.getAbsolutePivotPoint = function () {
  19221. var point = BABYLON.Vector3.Zero();
  19222. this.getAbsolutePivotPointToRef(point);
  19223. return point;
  19224. };
  19225. /**
  19226. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  19227. * Returns the TransformNode.
  19228. */
  19229. TransformNode.prototype.getAbsolutePivotPointToRef = function (result) {
  19230. result.x = this._pivotMatrix.m[12];
  19231. result.y = this._pivotMatrix.m[13];
  19232. result.z = this._pivotMatrix.m[14];
  19233. this.getPivotPointToRef(result);
  19234. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  19235. return this;
  19236. };
  19237. /**
  19238. * Defines the passed node as the parent of the current node.
  19239. * The node will remain exactly where it is and its position / rotation will be updated accordingly
  19240. * Returns the TransformNode.
  19241. */
  19242. TransformNode.prototype.setParent = function (node) {
  19243. if (!node && !this.parent) {
  19244. return this;
  19245. }
  19246. if (!node) {
  19247. var rotation = BABYLON.Tmp.Quaternion[0];
  19248. var position = BABYLON.Tmp.Vector3[0];
  19249. var scale = BABYLON.Tmp.Vector3[1];
  19250. if (this.parent && this.parent.computeWorldMatrix) {
  19251. this.parent.computeWorldMatrix(true);
  19252. }
  19253. this.computeWorldMatrix(true);
  19254. this.getWorldMatrix().decompose(scale, rotation, position);
  19255. if (this.rotationQuaternion) {
  19256. this.rotationQuaternion.copyFrom(rotation);
  19257. }
  19258. else {
  19259. rotation.toEulerAnglesToRef(this.rotation);
  19260. }
  19261. this.scaling.x = scale.x;
  19262. this.scaling.y = scale.y;
  19263. this.scaling.z = scale.z;
  19264. this.position.x = position.x;
  19265. this.position.y = position.y;
  19266. this.position.z = position.z;
  19267. }
  19268. else {
  19269. var rotation = BABYLON.Tmp.Quaternion[0];
  19270. var position = BABYLON.Tmp.Vector3[0];
  19271. var scale = BABYLON.Tmp.Vector3[1];
  19272. var diffMatrix = BABYLON.Tmp.Matrix[0];
  19273. var invParentMatrix = BABYLON.Tmp.Matrix[1];
  19274. this.computeWorldMatrix(true);
  19275. node.computeWorldMatrix(true);
  19276. node.getWorldMatrix().invertToRef(invParentMatrix);
  19277. this.getWorldMatrix().multiplyToRef(invParentMatrix, diffMatrix);
  19278. diffMatrix.decompose(scale, rotation, position);
  19279. if (this.rotationQuaternion) {
  19280. this.rotationQuaternion.copyFrom(rotation);
  19281. }
  19282. else {
  19283. rotation.toEulerAnglesToRef(this.rotation);
  19284. }
  19285. this.position.x = position.x;
  19286. this.position.y = position.y;
  19287. this.position.z = position.z;
  19288. this.scaling.x = scale.x;
  19289. this.scaling.y = scale.y;
  19290. this.scaling.z = scale.z;
  19291. }
  19292. this.parent = node;
  19293. return this;
  19294. };
  19295. Object.defineProperty(TransformNode.prototype, "nonUniformScaling", {
  19296. get: function () {
  19297. return this._nonUniformScaling;
  19298. },
  19299. enumerable: true,
  19300. configurable: true
  19301. });
  19302. /** @hidden */
  19303. TransformNode.prototype._updateNonUniformScalingState = function (value) {
  19304. if (this._nonUniformScaling === value) {
  19305. return false;
  19306. }
  19307. this._nonUniformScaling = value;
  19308. return true;
  19309. };
  19310. /**
  19311. * Attach the current TransformNode to another TransformNode associated with a bone
  19312. * @param bone Bone affecting the TransformNode
  19313. * @param affectedTransformNode TransformNode associated with the bone
  19314. */
  19315. TransformNode.prototype.attachToBone = function (bone, affectedTransformNode) {
  19316. this._transformToBoneReferal = affectedTransformNode;
  19317. this.parent = bone;
  19318. if (bone.getWorldMatrix().determinant() < 0) {
  19319. this.scalingDeterminant *= -1;
  19320. }
  19321. return this;
  19322. };
  19323. TransformNode.prototype.detachFromBone = function () {
  19324. if (!this.parent) {
  19325. return this;
  19326. }
  19327. if (this.parent.getWorldMatrix().determinant() < 0) {
  19328. this.scalingDeterminant *= -1;
  19329. }
  19330. this._transformToBoneReferal = null;
  19331. this.parent = null;
  19332. return this;
  19333. };
  19334. /**
  19335. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  19336. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  19337. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  19338. * The passed axis is also normalized.
  19339. * Returns the TransformNode.
  19340. */
  19341. TransformNode.prototype.rotate = function (axis, amount, space) {
  19342. axis.normalize();
  19343. if (!this.rotationQuaternion) {
  19344. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  19345. this.rotation = BABYLON.Vector3.Zero();
  19346. }
  19347. var rotationQuaternion;
  19348. if (!space || space === BABYLON.Space.LOCAL) {
  19349. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  19350. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  19351. }
  19352. else {
  19353. if (this.parent) {
  19354. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  19355. invertParentWorldMatrix.invert();
  19356. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  19357. }
  19358. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  19359. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  19360. }
  19361. return this;
  19362. };
  19363. /**
  19364. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  19365. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  19366. * The passed axis is also normalized.
  19367. * Returns the TransformNode.
  19368. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  19369. */
  19370. TransformNode.prototype.rotateAround = function (point, axis, amount) {
  19371. axis.normalize();
  19372. if (!this.rotationQuaternion) {
  19373. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  19374. this.rotation.copyFromFloats(0, 0, 0);
  19375. }
  19376. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  19377. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  19378. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  19379. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  19380. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  19381. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  19382. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  19383. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  19384. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  19385. return this;
  19386. };
  19387. /**
  19388. * Translates the mesh along the axis vector for the passed distance in the given space.
  19389. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  19390. * Returns the TransformNode.
  19391. */
  19392. TransformNode.prototype.translate = function (axis, distance, space) {
  19393. var displacementVector = axis.scale(distance);
  19394. if (!space || space === BABYLON.Space.LOCAL) {
  19395. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  19396. this.setPositionWithLocalVector(tempV3);
  19397. }
  19398. else {
  19399. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  19400. }
  19401. return this;
  19402. };
  19403. /**
  19404. * Adds a rotation step to the mesh current rotation.
  19405. * x, y, z are Euler angles expressed in radians.
  19406. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  19407. * This means this rotation is made in the mesh local space only.
  19408. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  19409. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  19410. * ```javascript
  19411. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  19412. * ```
  19413. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  19414. * 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.
  19415. * Returns the TransformNode.
  19416. */
  19417. TransformNode.prototype.addRotation = function (x, y, z) {
  19418. var rotationQuaternion;
  19419. if (this.rotationQuaternion) {
  19420. rotationQuaternion = this.rotationQuaternion;
  19421. }
  19422. else {
  19423. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  19424. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  19425. }
  19426. var accumulation = BABYLON.Tmp.Quaternion[0];
  19427. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  19428. rotationQuaternion.multiplyInPlace(accumulation);
  19429. if (!this.rotationQuaternion) {
  19430. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  19431. }
  19432. return this;
  19433. };
  19434. /**
  19435. * Computes the world matrix of the node
  19436. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  19437. * @returns the world matrix
  19438. */
  19439. TransformNode.prototype.computeWorldMatrix = function (force) {
  19440. if (this._isWorldMatrixFrozen) {
  19441. return this._worldMatrix;
  19442. }
  19443. if (!force && this.isSynchronized()) {
  19444. this._currentRenderId = this.getScene().getRenderId();
  19445. return this._worldMatrix;
  19446. }
  19447. this._updateCache();
  19448. this._cache.position.copyFrom(this.position);
  19449. this._cache.scaling.copyFrom(this.scaling);
  19450. this._cache.pivotMatrixUpdated = false;
  19451. this._cache.billboardMode = this.billboardMode;
  19452. this._currentRenderId = this.getScene().getRenderId();
  19453. this._childRenderId = this.getScene().getRenderId();
  19454. this._isDirty = false;
  19455. // Scaling
  19456. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  19457. // Rotation
  19458. //rotate, if quaternion is set and rotation was used
  19459. if (this.rotationQuaternion) {
  19460. var len = this.rotation.length();
  19461. if (len) {
  19462. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  19463. this.rotation.copyFromFloats(0, 0, 0);
  19464. }
  19465. }
  19466. if (this.rotationQuaternion) {
  19467. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  19468. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  19469. }
  19470. else {
  19471. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  19472. this._cache.rotation.copyFrom(this.rotation);
  19473. }
  19474. // Translation
  19475. var camera = this.getScene().activeCamera;
  19476. if (this.infiniteDistance && !this.parent && camera) {
  19477. var cameraWorldMatrix = camera.getWorldMatrix();
  19478. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  19479. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  19480. }
  19481. else {
  19482. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  19483. }
  19484. // Composing transformations
  19485. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  19486. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  19487. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  19488. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE && camera) {
  19489. if ((this.billboardMode & TransformNode.BILLBOARDMODE_ALL) !== TransformNode.BILLBOARDMODE_ALL) {
  19490. // Need to decompose each rotation here
  19491. var currentPosition = BABYLON.Tmp.Vector3[3];
  19492. if (this.parent && this.parent.getWorldMatrix) {
  19493. if (this._transformToBoneReferal) {
  19494. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19495. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  19496. }
  19497. else {
  19498. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  19499. }
  19500. }
  19501. else {
  19502. currentPosition.copyFrom(this.position);
  19503. }
  19504. currentPosition.subtractInPlace(camera.globalPosition);
  19505. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  19506. if ((this.billboardMode & TransformNode.BILLBOARDMODE_X) === TransformNode.BILLBOARDMODE_X) {
  19507. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  19508. }
  19509. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Y) === TransformNode.BILLBOARDMODE_Y) {
  19510. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  19511. }
  19512. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Z) === TransformNode.BILLBOARDMODE_Z) {
  19513. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  19514. }
  19515. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  19516. }
  19517. else {
  19518. BABYLON.Tmp.Matrix[1].copyFrom(camera.getViewMatrix());
  19519. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  19520. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  19521. }
  19522. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  19523. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  19524. }
  19525. // Post multiply inverse of pivotMatrix
  19526. if (this._postMultiplyPivotMatrix) {
  19527. BABYLON.Tmp.Matrix[5].multiplyToRef(this._pivotMatrixInverse, BABYLON.Tmp.Matrix[5]);
  19528. }
  19529. // Local world
  19530. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  19531. // Parent
  19532. if (this.parent && this.parent.getWorldMatrix) {
  19533. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE) {
  19534. if (this._transformToBoneReferal) {
  19535. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19536. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  19537. }
  19538. else {
  19539. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  19540. }
  19541. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  19542. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  19543. this._worldMatrix.copyFrom(this._localWorld);
  19544. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  19545. }
  19546. else {
  19547. if (this._transformToBoneReferal) {
  19548. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19549. BABYLON.Tmp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix);
  19550. }
  19551. else {
  19552. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  19553. }
  19554. }
  19555. this._markSyncedWithParent();
  19556. }
  19557. else {
  19558. this._worldMatrix.copyFrom(this._localWorld);
  19559. }
  19560. // Normal matrix
  19561. if (!this.ignoreNonUniformScaling) {
  19562. if (this.scaling.isNonUniform) {
  19563. this._updateNonUniformScalingState(true);
  19564. }
  19565. else if (this.parent && this.parent._nonUniformScaling) {
  19566. this._updateNonUniformScalingState(this.parent._nonUniformScaling);
  19567. }
  19568. else {
  19569. this._updateNonUniformScalingState(false);
  19570. }
  19571. }
  19572. else {
  19573. this._updateNonUniformScalingState(false);
  19574. }
  19575. this._afterComputeWorldMatrix();
  19576. // Absolute position
  19577. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  19578. // Callbacks
  19579. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  19580. if (!this._poseMatrix) {
  19581. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  19582. }
  19583. // Cache the determinant
  19584. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  19585. return this._worldMatrix;
  19586. };
  19587. TransformNode.prototype._afterComputeWorldMatrix = function () {
  19588. };
  19589. /**
  19590. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  19591. * @param func: callback function to add
  19592. *
  19593. * Returns the TransformNode.
  19594. */
  19595. TransformNode.prototype.registerAfterWorldMatrixUpdate = function (func) {
  19596. this.onAfterWorldMatrixUpdateObservable.add(func);
  19597. return this;
  19598. };
  19599. /**
  19600. * Removes a registered callback function.
  19601. * Returns the TransformNode.
  19602. */
  19603. TransformNode.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  19604. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  19605. return this;
  19606. };
  19607. /**
  19608. * Clone the current transform node
  19609. * Returns the new transform node
  19610. * @param name Name of the new clone
  19611. * @param newParent New parent for the clone
  19612. * @param doNotCloneChildren Do not clone children hierarchy
  19613. */
  19614. TransformNode.prototype.clone = function (name, newParent, doNotCloneChildren) {
  19615. var _this = this;
  19616. var result = BABYLON.SerializationHelper.Clone(function () { return new TransformNode(name, _this.getScene()); }, this);
  19617. result.name = name;
  19618. result.id = name;
  19619. if (newParent) {
  19620. result.parent = newParent;
  19621. }
  19622. if (!doNotCloneChildren) {
  19623. // Children
  19624. var directDescendants = this.getDescendants(true);
  19625. for (var index = 0; index < directDescendants.length; index++) {
  19626. var child = directDescendants[index];
  19627. if (child.clone) {
  19628. child.clone(name + "." + child.name, result);
  19629. }
  19630. }
  19631. }
  19632. return result;
  19633. };
  19634. TransformNode.prototype.serialize = function (currentSerializationObject) {
  19635. var serializationObject = BABYLON.SerializationHelper.Serialize(this, currentSerializationObject);
  19636. serializationObject.type = this.getClassName();
  19637. // Parent
  19638. if (this.parent) {
  19639. serializationObject.parentId = this.parent.id;
  19640. }
  19641. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  19642. serializationObject.tags = BABYLON.Tags.GetTags(this);
  19643. }
  19644. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  19645. serializationObject.isEnabled = this.isEnabled();
  19646. // Parent
  19647. if (this.parent) {
  19648. serializationObject.parentId = this.parent.id;
  19649. }
  19650. return serializationObject;
  19651. };
  19652. // Statics
  19653. /**
  19654. * Returns a new TransformNode object parsed from the source provided.
  19655. * The parameter `parsedMesh` is the source.
  19656. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  19657. */
  19658. TransformNode.Parse = function (parsedTransformNode, scene, rootUrl) {
  19659. var transformNode = BABYLON.SerializationHelper.Parse(function () { return new TransformNode(parsedTransformNode.name, scene); }, parsedTransformNode, scene, rootUrl);
  19660. if (BABYLON.Tags) {
  19661. BABYLON.Tags.AddTagsTo(transformNode, parsedTransformNode.tags);
  19662. }
  19663. if (parsedTransformNode.localMatrix) {
  19664. transformNode.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.localMatrix));
  19665. }
  19666. else if (parsedTransformNode.pivotMatrix) {
  19667. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.pivotMatrix));
  19668. }
  19669. transformNode.setEnabled(parsedTransformNode.isEnabled);
  19670. // Parent
  19671. if (parsedTransformNode.parentId) {
  19672. transformNode._waitingParentId = parsedTransformNode.parentId;
  19673. }
  19674. return transformNode;
  19675. };
  19676. /**
  19677. * Releases resources associated with this transform node.
  19678. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  19679. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  19680. */
  19681. TransformNode.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  19682. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  19683. // Animations
  19684. this.getScene().stopAnimation(this);
  19685. // Remove from scene
  19686. this.getScene().removeTransformNode(this);
  19687. this.onAfterWorldMatrixUpdateObservable.clear();
  19688. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  19689. };
  19690. // Statics
  19691. TransformNode.BILLBOARDMODE_NONE = 0;
  19692. TransformNode.BILLBOARDMODE_X = 1;
  19693. TransformNode.BILLBOARDMODE_Y = 2;
  19694. TransformNode.BILLBOARDMODE_Z = 4;
  19695. TransformNode.BILLBOARDMODE_ALL = 7;
  19696. TransformNode._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  19697. TransformNode._rotationAxisCache = new BABYLON.Quaternion();
  19698. __decorate([
  19699. BABYLON.serializeAsVector3("position")
  19700. ], TransformNode.prototype, "_position", void 0);
  19701. __decorate([
  19702. BABYLON.serializeAsVector3("rotation")
  19703. ], TransformNode.prototype, "_rotation", void 0);
  19704. __decorate([
  19705. BABYLON.serializeAsQuaternion("rotationQuaternion")
  19706. ], TransformNode.prototype, "_rotationQuaternion", void 0);
  19707. __decorate([
  19708. BABYLON.serializeAsVector3("scaling")
  19709. ], TransformNode.prototype, "_scaling", void 0);
  19710. __decorate([
  19711. BABYLON.serialize()
  19712. ], TransformNode.prototype, "billboardMode", void 0);
  19713. __decorate([
  19714. BABYLON.serialize()
  19715. ], TransformNode.prototype, "scalingDeterminant", void 0);
  19716. __decorate([
  19717. BABYLON.serialize()
  19718. ], TransformNode.prototype, "infiniteDistance", void 0);
  19719. __decorate([
  19720. BABYLON.serialize()
  19721. ], TransformNode.prototype, "ignoreNonUniformScaling", void 0);
  19722. return TransformNode;
  19723. }(BABYLON.Node));
  19724. BABYLON.TransformNode = TransformNode;
  19725. })(BABYLON || (BABYLON = {}));
  19726. //# sourceMappingURL=babylon.transformNode.js.map
  19727. var BABYLON;
  19728. (function (BABYLON) {
  19729. /**
  19730. * Class used to store all common mesh properties
  19731. */
  19732. var AbstractMesh = /** @class */ (function (_super) {
  19733. __extends(AbstractMesh, _super);
  19734. // Constructor
  19735. /**
  19736. * Creates a new AbstractMesh
  19737. * @param name defines the name of the mesh
  19738. * @param scene defines the hosting scene
  19739. */
  19740. function AbstractMesh(name, scene) {
  19741. if (scene === void 0) { scene = null; }
  19742. var _this = _super.call(this, name, scene, false) || this;
  19743. _this._facetNb = 0; // facet number
  19744. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  19745. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  19746. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  19747. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  19748. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  19749. _this._subDiv = {
  19750. max: 1,
  19751. X: 1,
  19752. Y: 1,
  19753. Z: 1
  19754. };
  19755. _this._facetDepthSort = false; // is the facet depth sort to be computed
  19756. _this._facetDepthSortEnabled = false; // is the facet depth sort initialized
  19757. /** Gets ot sets the culling strategy to use to find visible meshes */
  19758. _this.cullingStrategy = AbstractMesh.CULLINGSTRATEGY_STANDARD;
  19759. // Events
  19760. /**
  19761. * An event triggered when this mesh collides with another one
  19762. */
  19763. _this.onCollideObservable = new BABYLON.Observable();
  19764. /**
  19765. * An event triggered when the collision's position changes
  19766. */
  19767. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  19768. /**
  19769. * An event triggered when material is changed
  19770. */
  19771. _this.onMaterialChangedObservable = new BABYLON.Observable();
  19772. // Properties
  19773. /**
  19774. * Gets or sets the orientation for POV movement & rotation
  19775. */
  19776. _this.definedFacingForward = true;
  19777. /**
  19778. * This property determines the type of occlusion query algorithm to run in WebGl, you can use:
  19779. * * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED.
  19780. * * 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.
  19781. * @see http://doc.babylonjs.com/features/occlusionquery
  19782. */
  19783. _this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  19784. /**
  19785. * 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:
  19786. * * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh.
  19787. * * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh.
  19788. * * 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.
  19789. * @see http://doc.babylonjs.com/features/occlusionquery
  19790. */
  19791. _this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;
  19792. /**
  19793. * 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.
  19794. * The default value is -1 which means don't break the query and wait till the result
  19795. * @see http://doc.babylonjs.com/features/occlusionquery
  19796. */
  19797. _this.occlusionRetryCount = -1;
  19798. /** @hidden */
  19799. _this._occlusionInternalRetryCounter = 0;
  19800. /** @hidden */
  19801. _this._isOccluded = false;
  19802. /** @hidden */
  19803. _this._isOcclusionQueryInProgress = false;
  19804. _this._visibility = 1.0;
  19805. /** Gets or sets the alpha index used to sort transparent meshes
  19806. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#alpha-index
  19807. */
  19808. _this.alphaIndex = Number.MAX_VALUE;
  19809. /**
  19810. * Gets or sets a boolean indicating if the mesh is visible (renderable). Default is true
  19811. */
  19812. _this.isVisible = true;
  19813. /**
  19814. * Gets or sets a boolean indicating if the mesh can be picked (by scene.pick for instance or through actions). Default is true
  19815. */
  19816. _this.isPickable = true;
  19817. /** Gets or sets a boolean indicating that bounding boxes of subMeshes must be rendered as well (false by default) */
  19818. _this.showSubMeshesBoundingBox = false;
  19819. /** Gets or sets a boolean indicating if the mesh must be considered as a ray blocker for lens flares (false by default)
  19820. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  19821. */
  19822. _this.isBlocker = false;
  19823. /**
  19824. * Gets or sets a boolean indicating that pointer move events must be supported on this mesh (false by default)
  19825. */
  19826. _this.enablePointerMoveEvents = false;
  19827. /**
  19828. * Specifies the rendering group id for this mesh (0 by default)
  19829. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#rendering-groups
  19830. */
  19831. _this.renderingGroupId = 0;
  19832. _this._receiveShadows = false;
  19833. /** Defines color to use when rendering outline */
  19834. _this.outlineColor = BABYLON.Color3.Red();
  19835. /** Define width to use when rendering outline */
  19836. _this.outlineWidth = 0.02;
  19837. /** Defines color to use when rendering overlay */
  19838. _this.overlayColor = BABYLON.Color3.Red();
  19839. /** Defines alpha to use when rendering overlay */
  19840. _this.overlayAlpha = 0.5;
  19841. _this._hasVertexAlpha = false;
  19842. _this._useVertexColors = true;
  19843. _this._computeBonesUsingShaders = true;
  19844. _this._numBoneInfluencers = 4;
  19845. _this._applyFog = true;
  19846. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes selection (true by default) */
  19847. _this.useOctreeForRenderingSelection = true;
  19848. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes picking (true by default) */
  19849. _this.useOctreeForPicking = true;
  19850. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes collision (true by default) */
  19851. _this.useOctreeForCollisions = true;
  19852. _this._layerMask = 0x0FFFFFFF;
  19853. /**
  19854. * True if the mesh must be rendered in any case (this will shortcut the frustum clipping phase)
  19855. */
  19856. _this.alwaysSelectAsActiveMesh = false;
  19857. /**
  19858. * Gets or sets the current action manager
  19859. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  19860. */
  19861. _this.actionManager = null;
  19862. // Collisions
  19863. _this._checkCollisions = false;
  19864. _this._collisionMask = -1;
  19865. _this._collisionGroup = -1;
  19866. /**
  19867. * Gets or sets the ellipsoid used to impersonate this mesh when using collision engine (default is (0.5, 1, 0.5))
  19868. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  19869. */
  19870. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  19871. /**
  19872. * Gets or sets the ellipsoid offset used to impersonate this mesh when using collision engine (default is (0, 0, 0))
  19873. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  19874. */
  19875. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  19876. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  19877. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  19878. // Edges
  19879. /**
  19880. * Defines edge width used when edgesRenderer is enabled
  19881. * @see https://www.babylonjs-playground.com/#10OJSG#13
  19882. */
  19883. _this.edgesWidth = 1;
  19884. /**
  19885. * Defines edge color used when edgesRenderer is enabled
  19886. * @see https://www.babylonjs-playground.com/#10OJSG#13
  19887. */
  19888. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  19889. // Cache
  19890. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  19891. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  19892. /** @hidden */
  19893. _this._renderId = 0;
  19894. /** @hidden */
  19895. _this._intersectionsInProgress = new Array();
  19896. /** @hidden */
  19897. _this._unIndexed = false;
  19898. /** @hidden */
  19899. _this._lightSources = new Array();
  19900. /**
  19901. * An event triggered when the mesh is rebuilt.
  19902. */
  19903. _this.onRebuildObservable = new BABYLON.Observable();
  19904. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  19905. if (collidedMesh === void 0) { collidedMesh = null; }
  19906. //TODO move this to the collision coordinator!
  19907. if (_this.getScene().workerCollisions)
  19908. newPosition.multiplyInPlace(_this._collider._radius);
  19909. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  19910. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  19911. _this.position.addInPlace(_this._diffPositionForCollisions);
  19912. }
  19913. if (collidedMesh) {
  19914. _this.onCollideObservable.notifyObservers(collidedMesh);
  19915. }
  19916. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  19917. };
  19918. _this.getScene().addMesh(_this);
  19919. _this._resyncLightSources();
  19920. return _this;
  19921. }
  19922. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  19923. /**
  19924. * No billboard
  19925. */
  19926. get: function () {
  19927. return BABYLON.TransformNode.BILLBOARDMODE_NONE;
  19928. },
  19929. enumerable: true,
  19930. configurable: true
  19931. });
  19932. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  19933. /** Billboard on X axis */
  19934. get: function () {
  19935. return BABYLON.TransformNode.BILLBOARDMODE_X;
  19936. },
  19937. enumerable: true,
  19938. configurable: true
  19939. });
  19940. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  19941. /** Billboard on Y axis */
  19942. get: function () {
  19943. return BABYLON.TransformNode.BILLBOARDMODE_Y;
  19944. },
  19945. enumerable: true,
  19946. configurable: true
  19947. });
  19948. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  19949. /** Billboard on Z axis */
  19950. get: function () {
  19951. return BABYLON.TransformNode.BILLBOARDMODE_Z;
  19952. },
  19953. enumerable: true,
  19954. configurable: true
  19955. });
  19956. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  19957. /** Billboard on all axes */
  19958. get: function () {
  19959. return BABYLON.TransformNode.BILLBOARDMODE_ALL;
  19960. },
  19961. enumerable: true,
  19962. configurable: true
  19963. });
  19964. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  19965. /**
  19966. * Gets the number of facets in the mesh
  19967. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet
  19968. */
  19969. get: function () {
  19970. return this._facetNb;
  19971. },
  19972. enumerable: true,
  19973. configurable: true
  19974. });
  19975. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  19976. /**
  19977. * Gets or set the number (integer) of subdivisions per axis in the partioning space
  19978. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning
  19979. */
  19980. get: function () {
  19981. return this._partitioningSubdivisions;
  19982. },
  19983. set: function (nb) {
  19984. this._partitioningSubdivisions = nb;
  19985. },
  19986. enumerable: true,
  19987. configurable: true
  19988. });
  19989. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  19990. /**
  19991. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  19992. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box
  19993. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning
  19994. */
  19995. get: function () {
  19996. return this._partitioningBBoxRatio;
  19997. },
  19998. set: function (ratio) {
  19999. this._partitioningBBoxRatio = ratio;
  20000. },
  20001. enumerable: true,
  20002. configurable: true
  20003. });
  20004. Object.defineProperty(AbstractMesh.prototype, "mustDepthSortFacets", {
  20005. /**
  20006. * Gets or sets a boolean indicating that the facets must be depth sorted on next call to `updateFacetData()`.
  20007. * Works only for updatable meshes.
  20008. * Doesn't work with multi-materials
  20009. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort
  20010. */
  20011. get: function () {
  20012. return this._facetDepthSort;
  20013. },
  20014. set: function (sort) {
  20015. this._facetDepthSort = sort;
  20016. },
  20017. enumerable: true,
  20018. configurable: true
  20019. });
  20020. Object.defineProperty(AbstractMesh.prototype, "facetDepthSortFrom", {
  20021. /**
  20022. * The location (Vector3) where the facet depth sort must be computed from.
  20023. * By default, the active camera position.
  20024. * Used only when facet depth sort is enabled
  20025. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort
  20026. */
  20027. get: function () {
  20028. return this._facetDepthSortFrom;
  20029. },
  20030. set: function (location) {
  20031. this._facetDepthSortFrom = location;
  20032. },
  20033. enumerable: true,
  20034. configurable: true
  20035. });
  20036. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  20037. /**
  20038. * gets a boolean indicating if facetData is enabled
  20039. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet
  20040. */
  20041. get: function () {
  20042. return this._facetDataEnabled;
  20043. },
  20044. enumerable: true,
  20045. configurable: true
  20046. });
  20047. /** @hidden */
  20048. AbstractMesh.prototype._updateNonUniformScalingState = function (value) {
  20049. if (!_super.prototype._updateNonUniformScalingState.call(this, value)) {
  20050. return false;
  20051. }
  20052. this._markSubMeshesAsMiscDirty();
  20053. return true;
  20054. };
  20055. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  20056. /** Set a function to call when this mesh collides with another one */
  20057. set: function (callback) {
  20058. if (this._onCollideObserver) {
  20059. this.onCollideObservable.remove(this._onCollideObserver);
  20060. }
  20061. this._onCollideObserver = this.onCollideObservable.add(callback);
  20062. },
  20063. enumerable: true,
  20064. configurable: true
  20065. });
  20066. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  20067. /** Set a function to call when the collision's position changes */
  20068. set: function (callback) {
  20069. if (this._onCollisionPositionChangeObserver) {
  20070. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  20071. }
  20072. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  20073. },
  20074. enumerable: true,
  20075. configurable: true
  20076. });
  20077. Object.defineProperty(AbstractMesh.prototype, "isOccluded", {
  20078. /**
  20079. * 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
  20080. * @see http://doc.babylonjs.com/features/occlusionquery
  20081. */
  20082. get: function () {
  20083. return this._isOccluded;
  20084. },
  20085. set: function (value) {
  20086. this._isOccluded = value;
  20087. },
  20088. enumerable: true,
  20089. configurable: true
  20090. });
  20091. Object.defineProperty(AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  20092. /**
  20093. * Flag to check the progress status of the query
  20094. * @see http://doc.babylonjs.com/features/occlusionquery
  20095. */
  20096. get: function () {
  20097. return this._isOcclusionQueryInProgress;
  20098. },
  20099. enumerable: true,
  20100. configurable: true
  20101. });
  20102. Object.defineProperty(AbstractMesh.prototype, "visibility", {
  20103. /**
  20104. * Gets or sets mesh visibility between 0 and 1 (default is 1)
  20105. */
  20106. get: function () {
  20107. return this._visibility;
  20108. },
  20109. /**
  20110. * Gets or sets mesh visibility between 0 and 1 (default is 1)
  20111. */
  20112. set: function (value) {
  20113. if (this._visibility === value) {
  20114. return;
  20115. }
  20116. this._visibility = value;
  20117. this._markSubMeshesAsMiscDirty();
  20118. },
  20119. enumerable: true,
  20120. configurable: true
  20121. });
  20122. Object.defineProperty(AbstractMesh.prototype, "material", {
  20123. /** Gets or sets current material */
  20124. get: function () {
  20125. return this._material;
  20126. },
  20127. set: function (value) {
  20128. if (this._material === value) {
  20129. return;
  20130. }
  20131. this._material = value;
  20132. if (this.onMaterialChangedObservable.hasObservers) {
  20133. this.onMaterialChangedObservable.notifyObservers(this);
  20134. }
  20135. if (!this.subMeshes) {
  20136. return;
  20137. }
  20138. this._unBindEffect();
  20139. },
  20140. enumerable: true,
  20141. configurable: true
  20142. });
  20143. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  20144. /**
  20145. * Gets or sets a boolean indicating that this mesh can receive realtime shadows
  20146. * @see http://doc.babylonjs.com/babylon101/shadows
  20147. */
  20148. get: function () {
  20149. return this._receiveShadows;
  20150. },
  20151. set: function (value) {
  20152. if (this._receiveShadows === value) {
  20153. return;
  20154. }
  20155. this._receiveShadows = value;
  20156. this._markSubMeshesAsLightDirty();
  20157. },
  20158. enumerable: true,
  20159. configurable: true
  20160. });
  20161. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  20162. /** Gets or sets a boolean indicating that this mesh contains vertex color data with alpha values */
  20163. get: function () {
  20164. return this._hasVertexAlpha;
  20165. },
  20166. set: function (value) {
  20167. if (this._hasVertexAlpha === value) {
  20168. return;
  20169. }
  20170. this._hasVertexAlpha = value;
  20171. this._markSubMeshesAsAttributesDirty();
  20172. this._markSubMeshesAsMiscDirty();
  20173. },
  20174. enumerable: true,
  20175. configurable: true
  20176. });
  20177. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  20178. /** 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) */
  20179. get: function () {
  20180. return this._useVertexColors;
  20181. },
  20182. set: function (value) {
  20183. if (this._useVertexColors === value) {
  20184. return;
  20185. }
  20186. this._useVertexColors = value;
  20187. this._markSubMeshesAsAttributesDirty();
  20188. },
  20189. enumerable: true,
  20190. configurable: true
  20191. });
  20192. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  20193. /**
  20194. * Gets or sets a boolean indicating that bone animations must be computed by the CPU (false by default)
  20195. */
  20196. get: function () {
  20197. return this._computeBonesUsingShaders;
  20198. },
  20199. set: function (value) {
  20200. if (this._computeBonesUsingShaders === value) {
  20201. return;
  20202. }
  20203. this._computeBonesUsingShaders = value;
  20204. this._markSubMeshesAsAttributesDirty();
  20205. },
  20206. enumerable: true,
  20207. configurable: true
  20208. });
  20209. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  20210. /** Gets or sets the number of allowed bone influences per vertex (4 by default) */
  20211. get: function () {
  20212. return this._numBoneInfluencers;
  20213. },
  20214. set: function (value) {
  20215. if (this._numBoneInfluencers === value) {
  20216. return;
  20217. }
  20218. this._numBoneInfluencers = value;
  20219. this._markSubMeshesAsAttributesDirty();
  20220. },
  20221. enumerable: true,
  20222. configurable: true
  20223. });
  20224. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  20225. /** Gets or sets a boolean indicating that this mesh will allow fog to be rendered on it (true by default) */
  20226. get: function () {
  20227. return this._applyFog;
  20228. },
  20229. set: function (value) {
  20230. if (this._applyFog === value) {
  20231. return;
  20232. }
  20233. this._applyFog = value;
  20234. this._markSubMeshesAsMiscDirty();
  20235. },
  20236. enumerable: true,
  20237. configurable: true
  20238. });
  20239. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  20240. /**
  20241. * Gets or sets the current layer mask (default is 0x0FFFFFFF)
  20242. * @see http://doc.babylonjs.com/how_to/layermasks_and_multi-cam_textures
  20243. */
  20244. get: function () {
  20245. return this._layerMask;
  20246. },
  20247. set: function (value) {
  20248. if (value === this._layerMask) {
  20249. return;
  20250. }
  20251. this._layerMask = value;
  20252. this._resyncLightSources();
  20253. },
  20254. enumerable: true,
  20255. configurable: true
  20256. });
  20257. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  20258. /**
  20259. * Gets or sets a collision mask used to mask collisions (default is -1).
  20260. * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0
  20261. */
  20262. get: function () {
  20263. return this._collisionMask;
  20264. },
  20265. set: function (mask) {
  20266. this._collisionMask = !isNaN(mask) ? mask : -1;
  20267. },
  20268. enumerable: true,
  20269. configurable: true
  20270. });
  20271. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  20272. /**
  20273. * Gets or sets the current collision group mask (-1 by default).
  20274. * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0
  20275. */
  20276. get: function () {
  20277. return this._collisionGroup;
  20278. },
  20279. set: function (mask) {
  20280. this._collisionGroup = !isNaN(mask) ? mask : -1;
  20281. },
  20282. enumerable: true,
  20283. configurable: true
  20284. });
  20285. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  20286. /** @hidden */
  20287. get: function () {
  20288. return null;
  20289. },
  20290. enumerable: true,
  20291. configurable: true
  20292. });
  20293. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  20294. get: function () {
  20295. return this._skeleton;
  20296. },
  20297. /**
  20298. * Gets or sets a skeleton to apply skining transformations
  20299. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  20300. */
  20301. set: function (value) {
  20302. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  20303. this._skeleton._unregisterMeshWithPoseMatrix(this);
  20304. }
  20305. if (value && value.needInitialSkinMatrix) {
  20306. value._registerMeshWithPoseMatrix(this);
  20307. }
  20308. this._skeleton = value;
  20309. if (!this._skeleton) {
  20310. this._bonesTransformMatrices = null;
  20311. }
  20312. this._markSubMeshesAsAttributesDirty();
  20313. },
  20314. enumerable: true,
  20315. configurable: true
  20316. });
  20317. /**
  20318. * Returns the string "AbstractMesh"
  20319. * @returns "AbstractMesh"
  20320. */
  20321. AbstractMesh.prototype.getClassName = function () {
  20322. return "AbstractMesh";
  20323. };
  20324. /**
  20325. * Gets a string representation of the current mesh
  20326. * @param fullDetails defines a boolean indicating if full details must be included
  20327. * @returns a string representation of the current mesh
  20328. */
  20329. AbstractMesh.prototype.toString = function (fullDetails) {
  20330. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  20331. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  20332. if (this._skeleton) {
  20333. ret += ", skeleton: " + this._skeleton.name;
  20334. }
  20335. if (fullDetails) {
  20336. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  20337. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  20338. }
  20339. return ret;
  20340. };
  20341. /** @hidden */
  20342. AbstractMesh.prototype._rebuild = function () {
  20343. this.onRebuildObservable.notifyObservers(this);
  20344. if (this._occlusionQuery) {
  20345. this._occlusionQuery = null;
  20346. }
  20347. if (!this.subMeshes) {
  20348. return;
  20349. }
  20350. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20351. var subMesh = _a[_i];
  20352. subMesh._rebuild();
  20353. }
  20354. };
  20355. /** @hidden */
  20356. AbstractMesh.prototype._resyncLightSources = function () {
  20357. this._lightSources.length = 0;
  20358. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  20359. var light = _a[_i];
  20360. if (!light.isEnabled()) {
  20361. continue;
  20362. }
  20363. if (light.canAffectMesh(this)) {
  20364. this._lightSources.push(light);
  20365. }
  20366. }
  20367. this._markSubMeshesAsLightDirty();
  20368. };
  20369. /** @hidden */
  20370. AbstractMesh.prototype._resyncLighSource = function (light) {
  20371. var isIn = light.isEnabled() && light.canAffectMesh(this);
  20372. var index = this._lightSources.indexOf(light);
  20373. if (index === -1) {
  20374. if (!isIn) {
  20375. return;
  20376. }
  20377. this._lightSources.push(light);
  20378. }
  20379. else {
  20380. if (isIn) {
  20381. return;
  20382. }
  20383. this._lightSources.splice(index, 1);
  20384. }
  20385. this._markSubMeshesAsLightDirty();
  20386. };
  20387. /** @hidden */
  20388. AbstractMesh.prototype._unBindEffect = function () {
  20389. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20390. var subMesh = _a[_i];
  20391. subMesh.setEffect(null);
  20392. }
  20393. };
  20394. /** @hidden */
  20395. AbstractMesh.prototype._removeLightSource = function (light) {
  20396. var index = this._lightSources.indexOf(light);
  20397. if (index === -1) {
  20398. return;
  20399. }
  20400. this._lightSources.splice(index, 1);
  20401. this._markSubMeshesAsLightDirty();
  20402. };
  20403. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  20404. if (!this.subMeshes) {
  20405. return;
  20406. }
  20407. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20408. var subMesh = _a[_i];
  20409. if (subMesh._materialDefines) {
  20410. func(subMesh._materialDefines);
  20411. }
  20412. }
  20413. };
  20414. /** @hidden */
  20415. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  20416. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  20417. };
  20418. /** @hidden */
  20419. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  20420. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  20421. };
  20422. /** @hidden */
  20423. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  20424. if (!this.subMeshes) {
  20425. return;
  20426. }
  20427. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20428. var subMesh = _a[_i];
  20429. var material = subMesh.getMaterial();
  20430. if (material) {
  20431. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  20432. }
  20433. }
  20434. };
  20435. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  20436. /**
  20437. * Gets or sets a Vector3 depicting the mesh scaling along each local axis X, Y, Z. Default is (1.0, 1.0, 1.0)
  20438. */
  20439. get: function () {
  20440. return this._scaling;
  20441. },
  20442. set: function (newScaling) {
  20443. this._scaling = newScaling;
  20444. if (this.physicsImpostor) {
  20445. this.physicsImpostor.forceUpdate();
  20446. }
  20447. },
  20448. enumerable: true,
  20449. configurable: true
  20450. });
  20451. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  20452. // Methods
  20453. /**
  20454. * Returns true if the mesh is blocked. Implemented by child classes
  20455. */
  20456. get: function () {
  20457. return false;
  20458. },
  20459. enumerable: true,
  20460. configurable: true
  20461. });
  20462. /**
  20463. * Returns the mesh itself by default. Implemented by child classes
  20464. * @param camera defines the camera to use to pick the right LOD level
  20465. * @returns the currentAbstractMesh
  20466. */
  20467. AbstractMesh.prototype.getLOD = function (camera) {
  20468. return this;
  20469. };
  20470. /**
  20471. * Returns 0 by default. Implemented by child classes
  20472. * @returns an integer
  20473. */
  20474. AbstractMesh.prototype.getTotalVertices = function () {
  20475. return 0;
  20476. };
  20477. /**
  20478. * Returns null by default. Implemented by child classes
  20479. * @returns null
  20480. */
  20481. AbstractMesh.prototype.getIndices = function () {
  20482. return null;
  20483. };
  20484. /**
  20485. * Returns the array of the requested vertex data kind. Implemented by child classes
  20486. * @param kind defines the vertex data kind to use
  20487. * @returns null
  20488. */
  20489. AbstractMesh.prototype.getVerticesData = function (kind) {
  20490. return null;
  20491. };
  20492. /**
  20493. * Sets the vertex data of the mesh geometry for the requested `kind`.
  20494. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  20495. * Note that a new underlying VertexBuffer object is created each call.
  20496. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  20497. * @param kind defines vertex data kind:
  20498. * * BABYLON.VertexBuffer.PositionKind
  20499. * * BABYLON.VertexBuffer.UVKind
  20500. * * BABYLON.VertexBuffer.UV2Kind
  20501. * * BABYLON.VertexBuffer.UV3Kind
  20502. * * BABYLON.VertexBuffer.UV4Kind
  20503. * * BABYLON.VertexBuffer.UV5Kind
  20504. * * BABYLON.VertexBuffer.UV6Kind
  20505. * * BABYLON.VertexBuffer.ColorKind
  20506. * * BABYLON.VertexBuffer.MatricesIndicesKind
  20507. * * BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20508. * * BABYLON.VertexBuffer.MatricesWeightsKind
  20509. * * BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20510. * @param data defines the data source
  20511. * @param updatable defines if the data must be flagged as updatable (or static)
  20512. * @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
  20513. * @returns the current mesh
  20514. */
  20515. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  20516. return this;
  20517. };
  20518. /**
  20519. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  20520. * If the mesh has no geometry, it is simply returned as it is.
  20521. * @param kind defines vertex data kind:
  20522. * * BABYLON.VertexBuffer.PositionKind
  20523. * * BABYLON.VertexBuffer.UVKind
  20524. * * BABYLON.VertexBuffer.UV2Kind
  20525. * * BABYLON.VertexBuffer.UV3Kind
  20526. * * BABYLON.VertexBuffer.UV4Kind
  20527. * * BABYLON.VertexBuffer.UV5Kind
  20528. * * BABYLON.VertexBuffer.UV6Kind
  20529. * * BABYLON.VertexBuffer.ColorKind
  20530. * * BABYLON.VertexBuffer.MatricesIndicesKind
  20531. * * BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20532. * * BABYLON.VertexBuffer.MatricesWeightsKind
  20533. * * BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20534. * @param data defines the data source
  20535. * @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
  20536. * @param makeItUnique If true, a new global geometry is created from this data and is set to the mesh
  20537. * @returns the current mesh
  20538. */
  20539. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  20540. return this;
  20541. };
  20542. /**
  20543. * Sets the mesh indices,
  20544. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  20545. * @param indices Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  20546. * @param totalVertices Defines the total number of vertices
  20547. * @returns the current mesh
  20548. */
  20549. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  20550. return this;
  20551. };
  20552. /**
  20553. * Gets a boolean indicating if specific vertex data is present
  20554. * @param kind defines the vertex data kind to use
  20555. * @returns true is data kind is present
  20556. */
  20557. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  20558. return false;
  20559. };
  20560. /**
  20561. * Returns the mesh BoundingInfo object or creates a new one and returns if it was undefined
  20562. * @returns a BoundingInfo
  20563. */
  20564. AbstractMesh.prototype.getBoundingInfo = function () {
  20565. if (this._masterMesh) {
  20566. return this._masterMesh.getBoundingInfo();
  20567. }
  20568. if (!this._boundingInfo) {
  20569. // this._boundingInfo is being created here
  20570. this._updateBoundingInfo();
  20571. }
  20572. // cannot be null.
  20573. return this._boundingInfo;
  20574. };
  20575. /**
  20576. * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units)
  20577. * @param includeDescendants Use the hierarchy's bounding box instead of the mesh's bounding box
  20578. * @returns the current mesh
  20579. */
  20580. AbstractMesh.prototype.normalizeToUnitCube = function (includeDescendants) {
  20581. if (includeDescendants === void 0) { includeDescendants = true; }
  20582. var boundingVectors = this.getHierarchyBoundingVectors(includeDescendants);
  20583. var sizeVec = boundingVectors.max.subtract(boundingVectors.min);
  20584. var maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);
  20585. if (maxDimension === 0) {
  20586. return this;
  20587. }
  20588. var scale = 1 / maxDimension;
  20589. this.scaling.scaleInPlace(scale);
  20590. return this;
  20591. };
  20592. /**
  20593. * Overwrite the current bounding info
  20594. * @param boundingInfo defines the new bounding info
  20595. * @returns the current mesh
  20596. */
  20597. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  20598. this._boundingInfo = boundingInfo;
  20599. return this;
  20600. };
  20601. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  20602. /** Gets a boolean indicating if this mesh has skinning data and an attached skeleton */
  20603. get: function () {
  20604. return (this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind));
  20605. },
  20606. enumerable: true,
  20607. configurable: true
  20608. });
  20609. /** @hidden */
  20610. AbstractMesh.prototype._preActivate = function () {
  20611. };
  20612. /** @hidden */
  20613. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  20614. };
  20615. /** @hidden */
  20616. AbstractMesh.prototype._activate = function (renderId) {
  20617. this._renderId = renderId;
  20618. };
  20619. /**
  20620. * Gets the current world matrix
  20621. * @returns a Matrix
  20622. */
  20623. AbstractMesh.prototype.getWorldMatrix = function () {
  20624. if (this._masterMesh) {
  20625. return this._masterMesh.getWorldMatrix();
  20626. }
  20627. return _super.prototype.getWorldMatrix.call(this);
  20628. };
  20629. /** @hidden */
  20630. AbstractMesh.prototype._getWorldMatrixDeterminant = function () {
  20631. if (this._masterMesh) {
  20632. return this._masterMesh._getWorldMatrixDeterminant();
  20633. }
  20634. return _super.prototype._getWorldMatrixDeterminant.call(this);
  20635. };
  20636. // ================================== Point of View Movement =================================
  20637. /**
  20638. * Perform relative position change from the point of view of behind the front of the mesh.
  20639. * This is performed taking into account the meshes current rotation, so you do not have to care.
  20640. * Supports definition of mesh facing forward or backward
  20641. * @param amountRight defines the distance on the right axis
  20642. * @param amountUp defines the distance on the up axis
  20643. * @param amountForward defines the distance on the forward axis
  20644. * @returns the current mesh
  20645. */
  20646. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  20647. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  20648. return this;
  20649. };
  20650. /**
  20651. * Calculate relative position change from the point of view of behind the front of the mesh.
  20652. * This is performed taking into account the meshes current rotation, so you do not have to care.
  20653. * Supports definition of mesh facing forward or backward
  20654. * @param amountRight defines the distance on the right axis
  20655. * @param amountUp defines the distance on the up axis
  20656. * @param amountForward defines the distance on the forward axis
  20657. * @returns the new displacement vector
  20658. */
  20659. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  20660. var rotMatrix = new BABYLON.Matrix();
  20661. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  20662. rotQuaternion.toRotationMatrix(rotMatrix);
  20663. var translationDelta = BABYLON.Vector3.Zero();
  20664. var defForwardMult = this.definedFacingForward ? -1 : 1;
  20665. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  20666. return translationDelta;
  20667. };
  20668. // ================================== Point of View Rotation =================================
  20669. /**
  20670. * Perform relative rotation change from the point of view of behind the front of the mesh.
  20671. * Supports definition of mesh facing forward or backward
  20672. * @param flipBack defines the flip
  20673. * @param twirlClockwise defines the twirl
  20674. * @param tiltRight defines the tilt
  20675. * @returns the current mesh
  20676. */
  20677. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  20678. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  20679. return this;
  20680. };
  20681. /**
  20682. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  20683. * Supports definition of mesh facing forward or backward.
  20684. * @param flipBack defines the flip
  20685. * @param twirlClockwise defines the twirl
  20686. * @param tiltRight defines the tilt
  20687. * @returns the new rotation vector
  20688. */
  20689. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  20690. var defForwardMult = this.definedFacingForward ? 1 : -1;
  20691. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  20692. };
  20693. /**
  20694. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  20695. * @param includeDescendants Include bounding info from descendants as well (true by default)
  20696. * @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
  20697. * @returns the new bounding vectors
  20698. */
  20699. AbstractMesh.prototype.getHierarchyBoundingVectors = function (includeDescendants, predicate) {
  20700. if (includeDescendants === void 0) { includeDescendants = true; }
  20701. if (predicate === void 0) { predicate = null; }
  20702. // Ensures that all world matrix will be recomputed.
  20703. this.getScene().incrementRenderId();
  20704. this.computeWorldMatrix(true);
  20705. var min;
  20706. var max;
  20707. var boundingInfo = this.getBoundingInfo();
  20708. if (!this.subMeshes) {
  20709. min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  20710. max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  20711. }
  20712. else {
  20713. min = boundingInfo.boundingBox.minimumWorld;
  20714. max = boundingInfo.boundingBox.maximumWorld;
  20715. }
  20716. if (includeDescendants) {
  20717. var descendants = this.getDescendants(false);
  20718. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  20719. var descendant = descendants_1[_i];
  20720. var childMesh = descendant;
  20721. childMesh.computeWorldMatrix(true);
  20722. // Filters meshes based on custom predicate function.
  20723. if (predicate && !predicate(childMesh)) {
  20724. continue;
  20725. }
  20726. //make sure we have the needed params to get mix and max
  20727. if (!childMesh.getBoundingInfo || childMesh.getTotalVertices() === 0) {
  20728. continue;
  20729. }
  20730. var childBoundingInfo = childMesh.getBoundingInfo();
  20731. var boundingBox = childBoundingInfo.boundingBox;
  20732. var minBox = boundingBox.minimumWorld;
  20733. var maxBox = boundingBox.maximumWorld;
  20734. BABYLON.Tools.CheckExtends(minBox, min, max);
  20735. BABYLON.Tools.CheckExtends(maxBox, min, max);
  20736. }
  20737. }
  20738. return {
  20739. min: min,
  20740. max: max
  20741. };
  20742. };
  20743. /** @hidden */
  20744. AbstractMesh.prototype._updateBoundingInfo = function () {
  20745. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  20746. this._boundingInfo.update(this.worldMatrixFromCache);
  20747. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  20748. return this;
  20749. };
  20750. /** @hidden */
  20751. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  20752. if (!this.subMeshes) {
  20753. return this;
  20754. }
  20755. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  20756. var subMesh = this.subMeshes[subIndex];
  20757. if (!subMesh.IsGlobal) {
  20758. subMesh.updateBoundingInfo(matrix);
  20759. }
  20760. }
  20761. return this;
  20762. };
  20763. /** @hidden */
  20764. AbstractMesh.prototype._afterComputeWorldMatrix = function () {
  20765. // Bounding info
  20766. this._updateBoundingInfo();
  20767. };
  20768. /**
  20769. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  20770. * A mesh is in the frustum if its bounding box intersects the frustum
  20771. * @param frustumPlanes defines the frustum to test
  20772. * @returns true if the mesh is in the frustum planes
  20773. */
  20774. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  20775. return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes, this.cullingStrategy);
  20776. };
  20777. /**
  20778. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  20779. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  20780. * @param frustumPlanes defines the frustum to test
  20781. * @returns true if the mesh is completely in the frustum planes
  20782. */
  20783. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  20784. return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  20785. };
  20786. /**
  20787. * True if the mesh intersects another mesh or a SolidParticle object
  20788. * @param mesh defines a target mesh or SolidParticle to test
  20789. * @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)
  20790. * @param includeDescendants Can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
  20791. * @returns true if there is an intersection
  20792. */
  20793. AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {
  20794. if (precise === void 0) { precise = false; }
  20795. if (!this._boundingInfo || !mesh._boundingInfo) {
  20796. return false;
  20797. }
  20798. if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
  20799. return true;
  20800. }
  20801. if (includeDescendants) {
  20802. for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
  20803. var child = _a[_i];
  20804. if (child.intersectsMesh(mesh, precise, true)) {
  20805. return true;
  20806. }
  20807. }
  20808. }
  20809. return false;
  20810. };
  20811. /**
  20812. * Returns true if the passed point (Vector3) is inside the mesh bounding box
  20813. * @param point defines the point to test
  20814. * @returns true if there is an intersection
  20815. */
  20816. AbstractMesh.prototype.intersectsPoint = function (point) {
  20817. if (!this._boundingInfo) {
  20818. return false;
  20819. }
  20820. return this._boundingInfo.intersectsPoint(point);
  20821. };
  20822. /**
  20823. * Gets the position of the current mesh in camera space
  20824. * @param camera defines the camera to use
  20825. * @returns a position
  20826. */
  20827. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  20828. if (camera === void 0) { camera = null; }
  20829. if (!camera) {
  20830. camera = this.getScene().activeCamera;
  20831. }
  20832. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  20833. };
  20834. /**
  20835. * Returns the distance from the mesh to the active camera
  20836. * @param camera defines the camera to use
  20837. * @returns the distance
  20838. */
  20839. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  20840. if (camera === void 0) { camera = null; }
  20841. if (!camera) {
  20842. camera = this.getScene().activeCamera;
  20843. }
  20844. return this.absolutePosition.subtract(camera.position).length();
  20845. };
  20846. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  20847. // Collisions
  20848. /**
  20849. * Gets or sets a boolean indicating that this mesh can be used in the collision engine
  20850. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20851. */
  20852. get: function () {
  20853. return this._checkCollisions;
  20854. },
  20855. set: function (collisionEnabled) {
  20856. this._checkCollisions = collisionEnabled;
  20857. if (this.getScene().workerCollisions) {
  20858. this.getScene().collisionCoordinator.onMeshUpdated(this);
  20859. }
  20860. },
  20861. enumerable: true,
  20862. configurable: true
  20863. });
  20864. Object.defineProperty(AbstractMesh.prototype, "collider", {
  20865. /**
  20866. * Gets Collider object used to compute collisions (not physics)
  20867. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20868. */
  20869. get: function () {
  20870. return this._collider;
  20871. },
  20872. enumerable: true,
  20873. configurable: true
  20874. });
  20875. /**
  20876. * Move the mesh using collision engine
  20877. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20878. * @param displacement defines the requested displacement vector
  20879. * @returns the current mesh
  20880. */
  20881. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  20882. var globalPosition = this.getAbsolutePosition();
  20883. globalPosition.addToRef(this.ellipsoidOffset, this._oldPositionForCollisions);
  20884. if (!this._collider) {
  20885. this._collider = new BABYLON.Collider();
  20886. }
  20887. this._collider._radius = this.ellipsoid;
  20888. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  20889. return this;
  20890. };
  20891. // Collisions
  20892. /** @hidden */
  20893. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  20894. this._generatePointsArray();
  20895. if (!this._positions) {
  20896. return this;
  20897. }
  20898. // Transformation
  20899. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  20900. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  20901. subMesh._lastColliderWorldVertices = [];
  20902. subMesh._trianglePlanes = [];
  20903. var start = subMesh.verticesStart;
  20904. var end = (subMesh.verticesStart + subMesh.verticesCount);
  20905. for (var i = start; i < end; i++) {
  20906. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  20907. }
  20908. }
  20909. // Collide
  20910. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  20911. if (collider.collisionFound) {
  20912. collider.collidedMesh = this;
  20913. }
  20914. return this;
  20915. };
  20916. /** @hidden */
  20917. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  20918. var subMeshes = this._scene.getCollidingSubMeshCandidates(this, collider);
  20919. var len = subMeshes.length;
  20920. for (var index = 0; index < len; index++) {
  20921. var subMesh = subMeshes.data[index];
  20922. // Bounding test
  20923. if (len > 1 && !subMesh._checkCollision(collider))
  20924. continue;
  20925. this._collideForSubMesh(subMesh, transformMatrix, collider);
  20926. }
  20927. return this;
  20928. };
  20929. /** @hidden */
  20930. AbstractMesh.prototype._checkCollision = function (collider) {
  20931. // Bounding box test
  20932. if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider))
  20933. return this;
  20934. // Transformation matrix
  20935. BABYLON.Matrix.ScalingToRef(1.0 / collider._radius.x, 1.0 / collider._radius.y, 1.0 / collider._radius.z, this._collisionsScalingMatrix);
  20936. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  20937. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  20938. return this;
  20939. };
  20940. // Picking
  20941. /** @hidden */
  20942. AbstractMesh.prototype._generatePointsArray = function () {
  20943. return false;
  20944. };
  20945. /**
  20946. * Checks if the passed Ray intersects with the mesh
  20947. * @param ray defines the ray to use
  20948. * @param fastCheck defines if fast mode (but less precise) must be used (false by default)
  20949. * @returns the picking info
  20950. * @see http://doc.babylonjs.com/babylon101/intersect_collisions_-_mesh
  20951. */
  20952. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  20953. var pickingInfo = new BABYLON.PickingInfo();
  20954. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  20955. return pickingInfo;
  20956. }
  20957. if (!this._generatePointsArray()) {
  20958. return pickingInfo;
  20959. }
  20960. var intersectInfo = null;
  20961. var subMeshes = this._scene.getIntersectingSubMeshCandidates(this, ray);
  20962. var len = subMeshes.length;
  20963. for (var index = 0; index < len; index++) {
  20964. var subMesh = subMeshes.data[index];
  20965. // Bounding test
  20966. if (len > 1 && !subMesh.canIntersects(ray))
  20967. continue;
  20968. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  20969. if (currentIntersectInfo) {
  20970. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  20971. intersectInfo = currentIntersectInfo;
  20972. intersectInfo.subMeshId = index;
  20973. if (fastCheck) {
  20974. break;
  20975. }
  20976. }
  20977. }
  20978. }
  20979. if (intersectInfo) {
  20980. // Get picked point
  20981. var world = this.getWorldMatrix();
  20982. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  20983. var direction = ray.direction.clone();
  20984. direction = direction.scale(intersectInfo.distance);
  20985. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  20986. var pickedPoint = worldOrigin.add(worldDirection);
  20987. // Return result
  20988. pickingInfo.hit = true;
  20989. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  20990. pickingInfo.pickedPoint = pickedPoint;
  20991. pickingInfo.pickedMesh = this;
  20992. pickingInfo.bu = intersectInfo.bu || 0;
  20993. pickingInfo.bv = intersectInfo.bv || 0;
  20994. pickingInfo.faceId = intersectInfo.faceId;
  20995. pickingInfo.subMeshId = intersectInfo.subMeshId;
  20996. return pickingInfo;
  20997. }
  20998. return pickingInfo;
  20999. };
  21000. /**
  21001. * Clones the current mesh
  21002. * @param name defines the mesh name
  21003. * @param newParent defines the new mesh parent
  21004. * @param doNotCloneChildren defines a boolean indicating that children must not be cloned (false by default)
  21005. * @returns the new mesh
  21006. */
  21007. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  21008. return null;
  21009. };
  21010. /**
  21011. * Disposes all the submeshes of the current meshnp
  21012. * @returns the current mesh
  21013. */
  21014. AbstractMesh.prototype.releaseSubMeshes = function () {
  21015. if (this.subMeshes) {
  21016. while (this.subMeshes.length) {
  21017. this.subMeshes[0].dispose();
  21018. }
  21019. }
  21020. else {
  21021. this.subMeshes = new Array();
  21022. }
  21023. return this;
  21024. };
  21025. /**
  21026. * Releases resources associated with this abstract mesh.
  21027. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  21028. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  21029. */
  21030. AbstractMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  21031. var _this = this;
  21032. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  21033. var index;
  21034. // Smart Array Retainers.
  21035. this.getScene().freeActiveMeshes();
  21036. this.getScene().freeRenderingGroups();
  21037. // Action manager
  21038. if (this.actionManager !== undefined && this.actionManager !== null) {
  21039. this.actionManager.dispose();
  21040. this.actionManager = null;
  21041. }
  21042. // Skeleton
  21043. this._skeleton = null;
  21044. // Intersections in progress
  21045. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  21046. var other = this._intersectionsInProgress[index];
  21047. var pos = other._intersectionsInProgress.indexOf(this);
  21048. other._intersectionsInProgress.splice(pos, 1);
  21049. }
  21050. this._intersectionsInProgress = [];
  21051. // Lights
  21052. var lights = this.getScene().lights;
  21053. lights.forEach(function (light) {
  21054. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  21055. if (meshIndex !== -1) {
  21056. light.includedOnlyMeshes.splice(meshIndex, 1);
  21057. }
  21058. meshIndex = light.excludedMeshes.indexOf(_this);
  21059. if (meshIndex !== -1) {
  21060. light.excludedMeshes.splice(meshIndex, 1);
  21061. }
  21062. // Shadow generators
  21063. var generator = light.getShadowGenerator();
  21064. if (generator) {
  21065. var shadowMap = generator.getShadowMap();
  21066. if (shadowMap && shadowMap.renderList) {
  21067. meshIndex = shadowMap.renderList.indexOf(_this);
  21068. if (meshIndex !== -1) {
  21069. shadowMap.renderList.splice(meshIndex, 1);
  21070. }
  21071. }
  21072. }
  21073. });
  21074. // SubMeshes
  21075. if (this.getClassName() !== "InstancedMesh") {
  21076. this.releaseSubMeshes();
  21077. }
  21078. // Query
  21079. var engine = this.getScene().getEngine();
  21080. if (this._occlusionQuery) {
  21081. this._isOcclusionQueryInProgress = false;
  21082. engine.deleteQuery(this._occlusionQuery);
  21083. this._occlusionQuery = null;
  21084. }
  21085. // Engine
  21086. engine.wipeCaches();
  21087. // Remove from scene
  21088. this.getScene().removeMesh(this);
  21089. if (disposeMaterialAndTextures) {
  21090. if (this.material) {
  21091. this.material.dispose(false, true);
  21092. }
  21093. }
  21094. if (!doNotRecurse) {
  21095. // Particles
  21096. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  21097. if (this.getScene().particleSystems[index].emitter === this) {
  21098. this.getScene().particleSystems[index].dispose();
  21099. index--;
  21100. }
  21101. }
  21102. }
  21103. // facet data
  21104. if (this._facetDataEnabled) {
  21105. this.disableFacetData();
  21106. }
  21107. this.onAfterWorldMatrixUpdateObservable.clear();
  21108. this.onCollideObservable.clear();
  21109. this.onCollisionPositionChangeObservable.clear();
  21110. this.onRebuildObservable.clear();
  21111. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  21112. };
  21113. /**
  21114. * Adds the passed mesh as a child to the current mesh
  21115. * @param mesh defines the child mesh
  21116. * @returns the current mesh
  21117. */
  21118. AbstractMesh.prototype.addChild = function (mesh) {
  21119. mesh.setParent(this);
  21120. return this;
  21121. };
  21122. /**
  21123. * Removes the passed mesh from the current mesh children list
  21124. * @param mesh defines the child mesh
  21125. * @returns the current mesh
  21126. */
  21127. AbstractMesh.prototype.removeChild = function (mesh) {
  21128. mesh.setParent(null);
  21129. return this;
  21130. };
  21131. // Facet data
  21132. /** @hidden */
  21133. AbstractMesh.prototype._initFacetData = function () {
  21134. if (!this._facetNormals) {
  21135. this._facetNormals = new Array();
  21136. }
  21137. if (!this._facetPositions) {
  21138. this._facetPositions = new Array();
  21139. }
  21140. if (!this._facetPartitioning) {
  21141. this._facetPartitioning = new Array();
  21142. }
  21143. this._facetNb = (this.getIndices().length / 3) | 0;
  21144. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  21145. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  21146. for (var f = 0; f < this._facetNb; f++) {
  21147. this._facetNormals[f] = BABYLON.Vector3.Zero();
  21148. this._facetPositions[f] = BABYLON.Vector3.Zero();
  21149. }
  21150. this._facetDataEnabled = true;
  21151. return this;
  21152. };
  21153. /**
  21154. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  21155. * This method can be called within the render loop.
  21156. * 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
  21157. * @returns the current mesh
  21158. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21159. */
  21160. AbstractMesh.prototype.updateFacetData = function () {
  21161. if (!this._facetDataEnabled) {
  21162. this._initFacetData();
  21163. }
  21164. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21165. var indices = this.getIndices();
  21166. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21167. var bInfo = this.getBoundingInfo();
  21168. if (this._facetDepthSort && !this._facetDepthSortEnabled) {
  21169. // init arrays, matrix and sort function on first call
  21170. this._facetDepthSortEnabled = true;
  21171. if (indices instanceof Uint16Array) {
  21172. this._depthSortedIndices = new Uint16Array(indices);
  21173. }
  21174. else if (indices instanceof Uint32Array) {
  21175. this._depthSortedIndices = new Uint32Array(indices);
  21176. }
  21177. else {
  21178. var needs32bits = false;
  21179. for (var i = 0; i < indices.length; i++) {
  21180. if (indices[i] > 65535) {
  21181. needs32bits = true;
  21182. break;
  21183. }
  21184. }
  21185. if (needs32bits) {
  21186. this._depthSortedIndices = new Uint32Array(indices);
  21187. }
  21188. else {
  21189. this._depthSortedIndices = new Uint16Array(indices);
  21190. }
  21191. }
  21192. this._facetDepthSortFunction = function (f1, f2) {
  21193. return (f2.sqDistance - f1.sqDistance);
  21194. };
  21195. if (!this._facetDepthSortFrom) {
  21196. var camera = this.getScene().activeCamera;
  21197. this._facetDepthSortFrom = (camera) ? camera.position : BABYLON.Vector3.Zero();
  21198. }
  21199. this._depthSortedFacets = [];
  21200. for (var f = 0; f < this._facetNb; f++) {
  21201. var depthSortedFacet = { ind: f * 3, sqDistance: 0.0 };
  21202. this._depthSortedFacets.push(depthSortedFacet);
  21203. }
  21204. this._invertedMatrix = BABYLON.Matrix.Identity();
  21205. this._facetDepthSortOrigin = BABYLON.Vector3.Zero();
  21206. }
  21207. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  21208. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  21209. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  21210. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  21211. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  21212. this._subDiv.max = this._partitioningSubdivisions;
  21213. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  21214. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  21215. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  21216. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  21217. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  21218. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  21219. // set the parameters for ComputeNormals()
  21220. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  21221. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  21222. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  21223. this._facetParameters.bInfo = bInfo;
  21224. this._facetParameters.bbSize = this._bbSize;
  21225. this._facetParameters.subDiv = this._subDiv;
  21226. this._facetParameters.ratio = this.partitioningBBoxRatio;
  21227. this._facetParameters.depthSort = this._facetDepthSort;
  21228. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  21229. this.computeWorldMatrix(true);
  21230. this._worldMatrix.invertToRef(this._invertedMatrix);
  21231. BABYLON.Vector3.TransformCoordinatesToRef(this._facetDepthSortFrom, this._invertedMatrix, this._facetDepthSortOrigin);
  21232. this._facetParameters.distanceTo = this._facetDepthSortOrigin;
  21233. }
  21234. this._facetParameters.depthSortedFacets = this._depthSortedFacets;
  21235. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  21236. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  21237. this._depthSortedFacets.sort(this._facetDepthSortFunction);
  21238. var l = (this._depthSortedIndices.length / 3) | 0;
  21239. for (var f = 0; f < l; f++) {
  21240. var sind = this._depthSortedFacets[f].ind;
  21241. this._depthSortedIndices[f * 3] = indices[sind];
  21242. this._depthSortedIndices[f * 3 + 1] = indices[sind + 1];
  21243. this._depthSortedIndices[f * 3 + 2] = indices[sind + 2];
  21244. }
  21245. this.updateIndices(this._depthSortedIndices);
  21246. }
  21247. return this;
  21248. };
  21249. /**
  21250. * Returns the facetLocalNormals array.
  21251. * The normals are expressed in the mesh local spac
  21252. * @returns an array of Vector3
  21253. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21254. */
  21255. AbstractMesh.prototype.getFacetLocalNormals = function () {
  21256. if (!this._facetNormals) {
  21257. this.updateFacetData();
  21258. }
  21259. return this._facetNormals;
  21260. };
  21261. /**
  21262. * Returns the facetLocalPositions array.
  21263. * The facet positions are expressed in the mesh local space
  21264. * @returns an array of Vector3
  21265. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21266. */
  21267. AbstractMesh.prototype.getFacetLocalPositions = function () {
  21268. if (!this._facetPositions) {
  21269. this.updateFacetData();
  21270. }
  21271. return this._facetPositions;
  21272. };
  21273. /**
  21274. * Returns the facetLocalPartioning array
  21275. * @returns an array of array of numbers
  21276. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21277. */
  21278. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  21279. if (!this._facetPartitioning) {
  21280. this.updateFacetData();
  21281. }
  21282. return this._facetPartitioning;
  21283. };
  21284. /**
  21285. * Returns the i-th facet position in the world system.
  21286. * This method allocates a new Vector3 per call
  21287. * @param i defines the facet index
  21288. * @returns a new Vector3
  21289. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21290. */
  21291. AbstractMesh.prototype.getFacetPosition = function (i) {
  21292. var pos = BABYLON.Vector3.Zero();
  21293. this.getFacetPositionToRef(i, pos);
  21294. return pos;
  21295. };
  21296. /**
  21297. * Sets the reference Vector3 with the i-th facet position in the world system
  21298. * @param i defines the facet index
  21299. * @param ref defines the target vector
  21300. * @returns the current mesh
  21301. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21302. */
  21303. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  21304. var localPos = (this.getFacetLocalPositions())[i];
  21305. var world = this.getWorldMatrix();
  21306. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  21307. return this;
  21308. };
  21309. /**
  21310. * Returns the i-th facet normal in the world system.
  21311. * This method allocates a new Vector3 per call
  21312. * @param i defines the facet index
  21313. * @returns a new Vector3
  21314. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21315. */
  21316. AbstractMesh.prototype.getFacetNormal = function (i) {
  21317. var norm = BABYLON.Vector3.Zero();
  21318. this.getFacetNormalToRef(i, norm);
  21319. return norm;
  21320. };
  21321. /**
  21322. * Sets the reference Vector3 with the i-th facet normal in the world system
  21323. * @param i defines the facet index
  21324. * @param ref defines the target vector
  21325. * @returns the current mesh
  21326. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21327. */
  21328. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  21329. var localNorm = (this.getFacetLocalNormals())[i];
  21330. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  21331. return this;
  21332. };
  21333. /**
  21334. * 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)
  21335. * @param x defines x coordinate
  21336. * @param y defines y coordinate
  21337. * @param z defines z coordinate
  21338. * @returns the array of facet indexes
  21339. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21340. */
  21341. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  21342. var bInfo = this.getBoundingInfo();
  21343. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  21344. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  21345. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  21346. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  21347. return null;
  21348. }
  21349. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  21350. };
  21351. /**
  21352. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found
  21353. * @param projected sets as the (x,y,z) world projection on the facet
  21354. * @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
  21355. * @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
  21356. * @param x defines x coordinate
  21357. * @param y defines y coordinate
  21358. * @param z defines z coordinate
  21359. * @returns the face index if found (or null instead)
  21360. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21361. */
  21362. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  21363. if (checkFace === void 0) { checkFace = false; }
  21364. if (facing === void 0) { facing = true; }
  21365. var world = this.getWorldMatrix();
  21366. var invMat = BABYLON.Tmp.Matrix[5];
  21367. world.invertToRef(invMat);
  21368. var invVect = BABYLON.Tmp.Vector3[8];
  21369. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  21370. var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  21371. if (projected) {
  21372. // tranform the local computed projected vector to world coordinates
  21373. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  21374. }
  21375. return closest;
  21376. };
  21377. /**
  21378. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found
  21379. * @param projected sets as the (x,y,z) local projection on the facet
  21380. * @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
  21381. * @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
  21382. * @param x defines x coordinate
  21383. * @param y defines y coordinate
  21384. * @param z defines z coordinate
  21385. * @returns the face index if found (or null instead)
  21386. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21387. */
  21388. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  21389. if (checkFace === void 0) { checkFace = false; }
  21390. if (facing === void 0) { facing = true; }
  21391. var closest = null;
  21392. var tmpx = 0.0;
  21393. var tmpy = 0.0;
  21394. var tmpz = 0.0;
  21395. var d = 0.0; // tmp dot facet normal * facet position
  21396. var t0 = 0.0;
  21397. var projx = 0.0;
  21398. var projy = 0.0;
  21399. var projz = 0.0;
  21400. // Get all the facets in the same partitioning block than (x, y, z)
  21401. var facetPositions = this.getFacetLocalPositions();
  21402. var facetNormals = this.getFacetLocalNormals();
  21403. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  21404. if (!facetsInBlock) {
  21405. return null;
  21406. }
  21407. // Get the closest facet to (x, y, z)
  21408. var shortest = Number.MAX_VALUE; // init distance vars
  21409. var tmpDistance = shortest;
  21410. var fib; // current facet in the block
  21411. var norm; // current facet normal
  21412. var p0; // current facet barycenter position
  21413. // loop on all the facets in the current partitioning block
  21414. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  21415. fib = facetsInBlock[idx];
  21416. norm = facetNormals[fib];
  21417. p0 = facetPositions[fib];
  21418. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  21419. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  21420. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  21421. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  21422. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  21423. projx = x + norm.x * t0;
  21424. projy = y + norm.y * t0;
  21425. projz = z + norm.z * t0;
  21426. tmpx = projx - x;
  21427. tmpy = projy - y;
  21428. tmpz = projz - z;
  21429. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  21430. if (tmpDistance < shortest) { // just keep the closest facet to (x, y, z)
  21431. shortest = tmpDistance;
  21432. closest = fib;
  21433. if (projected) {
  21434. projected.x = projx;
  21435. projected.y = projy;
  21436. projected.z = projz;
  21437. }
  21438. }
  21439. }
  21440. }
  21441. return closest;
  21442. };
  21443. /**
  21444. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  21445. * @returns the parameters
  21446. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21447. */
  21448. AbstractMesh.prototype.getFacetDataParameters = function () {
  21449. return this._facetParameters;
  21450. };
  21451. /**
  21452. * Disables the feature FacetData and frees the related memory
  21453. * @returns the current mesh
  21454. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21455. */
  21456. AbstractMesh.prototype.disableFacetData = function () {
  21457. if (this._facetDataEnabled) {
  21458. this._facetDataEnabled = false;
  21459. this._facetPositions = new Array();
  21460. this._facetNormals = new Array();
  21461. this._facetPartitioning = new Array();
  21462. this._facetParameters = null;
  21463. this._depthSortedIndices = new Uint32Array(0);
  21464. }
  21465. return this;
  21466. };
  21467. /**
  21468. * Updates the AbstractMesh indices array
  21469. * @param indices defines the data source
  21470. * @returns the current mesh
  21471. */
  21472. AbstractMesh.prototype.updateIndices = function (indices) {
  21473. return this;
  21474. };
  21475. /**
  21476. * Creates new normals data for the mesh
  21477. * @param updatable defines if the normal vertex buffer must be flagged as updatable
  21478. * @returns the current mesh
  21479. */
  21480. AbstractMesh.prototype.createNormals = function (updatable) {
  21481. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21482. var indices = this.getIndices();
  21483. var normals;
  21484. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  21485. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21486. }
  21487. else {
  21488. normals = [];
  21489. }
  21490. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  21491. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  21492. return this;
  21493. };
  21494. /**
  21495. * Align the mesh with a normal
  21496. * @param normal defines the normal to use
  21497. * @param upDirection can be used to redefined the up vector to use (will use the (0, 1, 0) by default)
  21498. * @returns the current mesh
  21499. */
  21500. AbstractMesh.prototype.alignWithNormal = function (normal, upDirection) {
  21501. if (!upDirection) {
  21502. upDirection = BABYLON.Axis.Y;
  21503. }
  21504. var axisX = BABYLON.Tmp.Vector3[0];
  21505. var axisZ = BABYLON.Tmp.Vector3[1];
  21506. BABYLON.Vector3.CrossToRef(upDirection, normal, axisZ);
  21507. BABYLON.Vector3.CrossToRef(normal, axisZ, axisX);
  21508. if (this.rotationQuaternion) {
  21509. BABYLON.Quaternion.RotationQuaternionFromAxisToRef(axisX, normal, axisZ, this.rotationQuaternion);
  21510. }
  21511. else {
  21512. BABYLON.Vector3.RotationFromAxisToRef(axisX, normal, axisZ, this.rotation);
  21513. }
  21514. return this;
  21515. };
  21516. /** @hidden */
  21517. AbstractMesh.prototype._checkOcclusionQuery = function () {
  21518. this._isOccluded = false;
  21519. };
  21520. /** No occlusion */
  21521. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  21522. /** Occlusion set to optimisitic */
  21523. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  21524. /** Occlusion set to strict */
  21525. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  21526. /** Use an accurante occlusion algorithm */
  21527. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  21528. /** Use a conservative occlusion algorithm */
  21529. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  21530. /** Default culling strategy with bounding box and bounding sphere and then frustum culling */
  21531. AbstractMesh.CULLINGSTRATEGY_STANDARD = 0;
  21532. /** Culling strategy with bounding sphere only and then frustum culling */
  21533. AbstractMesh.CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY = 1;
  21534. return AbstractMesh;
  21535. }(BABYLON.TransformNode));
  21536. BABYLON.AbstractMesh = AbstractMesh;
  21537. })(BABYLON || (BABYLON = {}));
  21538. //# sourceMappingURL=babylon.abstractMesh.js.map
  21539. var BABYLON;
  21540. (function (BABYLON) {
  21541. /**
  21542. * Base class of all the lights in Babylon. It groups all the generic information about lights.
  21543. * Lights are used, as you would expect, to affect how meshes are seen, in terms of both illumination and colour.
  21544. * 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.
  21545. */
  21546. var Light = /** @class */ (function (_super) {
  21547. __extends(Light, _super);
  21548. /**
  21549. * Creates a Light object in the scene.
  21550. * Documentation : http://doc.babylonjs.com/tutorials/lights
  21551. * @param name The firendly name of the light
  21552. * @param scene The scene the light belongs too
  21553. */
  21554. function Light(name, scene) {
  21555. var _this = _super.call(this, name, scene) || this;
  21556. /**
  21557. * Diffuse gives the basic color to an object.
  21558. */
  21559. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  21560. /**
  21561. * Specular produces a highlight color on an object.
  21562. * Note: This is note affecting PBR materials.
  21563. */
  21564. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  21565. /**
  21566. * Defines the falloff type for this light. This lets overrriding how punctual light are
  21567. * falling off base on range or angle.
  21568. * This can be set to any values in Light.FALLOFF_x.
  21569. *
  21570. * Note: This is only usefull for PBR Materials at the moment. This could be extended if required to
  21571. * other types of materials.
  21572. */
  21573. _this.falloffType = Light.FALLOFF_DEFAULT;
  21574. /**
  21575. * Strength of the light.
  21576. * Note: By default it is define in the framework own unit.
  21577. * Note: In PBR materials the intensityMode can be use to chose what unit the intensity is defined in.
  21578. */
  21579. _this.intensity = 1.0;
  21580. _this._range = Number.MAX_VALUE;
  21581. _this._inverseSquaredRange = 0;
  21582. /**
  21583. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  21584. * of light.
  21585. */
  21586. _this._photometricScale = 1.0;
  21587. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  21588. _this._radius = 0.00001;
  21589. /**
  21590. * Defines the rendering priority of the lights. It can help in case of fallback or number of lights
  21591. * exceeding the number allowed of the materials.
  21592. */
  21593. _this.renderPriority = 0;
  21594. _this._shadowEnabled = true;
  21595. _this._excludeWithLayerMask = 0;
  21596. _this._includeOnlyWithLayerMask = 0;
  21597. _this._lightmapMode = 0;
  21598. /**
  21599. * @hidden Internal use only.
  21600. */
  21601. _this._excludedMeshesIds = new Array();
  21602. /**
  21603. * @hidden Internal use only.
  21604. */
  21605. _this._includedOnlyMeshesIds = new Array();
  21606. _this.getScene().addLight(_this);
  21607. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  21608. _this._buildUniformLayout();
  21609. _this.includedOnlyMeshes = new Array();
  21610. _this.excludedMeshes = new Array();
  21611. _this._resyncMeshes();
  21612. return _this;
  21613. }
  21614. Object.defineProperty(Light.prototype, "range", {
  21615. /**
  21616. * Defines how far from the source the light is impacting in scene units.
  21617. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  21618. */
  21619. get: function () {
  21620. return this._range;
  21621. },
  21622. /**
  21623. * Defines how far from the source the light is impacting in scene units.
  21624. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  21625. */
  21626. set: function (value) {
  21627. this._range = value;
  21628. this._inverseSquaredRange = 1.0 / (this.range * this.range);
  21629. },
  21630. enumerable: true,
  21631. configurable: true
  21632. });
  21633. Object.defineProperty(Light.prototype, "intensityMode", {
  21634. /**
  21635. * Gets the photometric scale used to interpret the intensity.
  21636. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  21637. */
  21638. get: function () {
  21639. return this._intensityMode;
  21640. },
  21641. /**
  21642. * Sets the photometric scale used to interpret the intensity.
  21643. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  21644. */
  21645. set: function (value) {
  21646. this._intensityMode = value;
  21647. this._computePhotometricScale();
  21648. },
  21649. enumerable: true,
  21650. configurable: true
  21651. });
  21652. ;
  21653. ;
  21654. Object.defineProperty(Light.prototype, "radius", {
  21655. /**
  21656. * Gets the light radius used by PBR Materials to simulate soft area lights.
  21657. */
  21658. get: function () {
  21659. return this._radius;
  21660. },
  21661. /**
  21662. * sets the light radius used by PBR Materials to simulate soft area lights.
  21663. */
  21664. set: function (value) {
  21665. this._radius = value;
  21666. this._computePhotometricScale();
  21667. },
  21668. enumerable: true,
  21669. configurable: true
  21670. });
  21671. ;
  21672. ;
  21673. Object.defineProperty(Light.prototype, "shadowEnabled", {
  21674. /**
  21675. * Gets wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  21676. * the current shadow generator.
  21677. */
  21678. get: function () {
  21679. return this._shadowEnabled;
  21680. },
  21681. /**
  21682. * Sets wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  21683. * the current shadow generator.
  21684. */
  21685. set: function (value) {
  21686. if (this._shadowEnabled === value) {
  21687. return;
  21688. }
  21689. this._shadowEnabled = value;
  21690. this._markMeshesAsLightDirty();
  21691. },
  21692. enumerable: true,
  21693. configurable: true
  21694. });
  21695. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  21696. /**
  21697. * Gets the only meshes impacted by this light.
  21698. */
  21699. get: function () {
  21700. return this._includedOnlyMeshes;
  21701. },
  21702. /**
  21703. * Sets the only meshes impacted by this light.
  21704. */
  21705. set: function (value) {
  21706. this._includedOnlyMeshes = value;
  21707. this._hookArrayForIncludedOnly(value);
  21708. },
  21709. enumerable: true,
  21710. configurable: true
  21711. });
  21712. Object.defineProperty(Light.prototype, "excludedMeshes", {
  21713. /**
  21714. * Gets the meshes not impacted by this light.
  21715. */
  21716. get: function () {
  21717. return this._excludedMeshes;
  21718. },
  21719. /**
  21720. * Sets the meshes not impacted by this light.
  21721. */
  21722. set: function (value) {
  21723. this._excludedMeshes = value;
  21724. this._hookArrayForExcluded(value);
  21725. },
  21726. enumerable: true,
  21727. configurable: true
  21728. });
  21729. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  21730. /**
  21731. * Gets the layer id use to find what meshes are not impacted by the light.
  21732. * Inactive if 0
  21733. */
  21734. get: function () {
  21735. return this._excludeWithLayerMask;
  21736. },
  21737. /**
  21738. * Sets the layer id use to find what meshes are not impacted by the light.
  21739. * Inactive if 0
  21740. */
  21741. set: function (value) {
  21742. this._excludeWithLayerMask = value;
  21743. this._resyncMeshes();
  21744. },
  21745. enumerable: true,
  21746. configurable: true
  21747. });
  21748. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  21749. /**
  21750. * Gets the layer id use to find what meshes are impacted by the light.
  21751. * Inactive if 0
  21752. */
  21753. get: function () {
  21754. return this._includeOnlyWithLayerMask;
  21755. },
  21756. /**
  21757. * Sets the layer id use to find what meshes are impacted by the light.
  21758. * Inactive if 0
  21759. */
  21760. set: function (value) {
  21761. this._includeOnlyWithLayerMask = value;
  21762. this._resyncMeshes();
  21763. },
  21764. enumerable: true,
  21765. configurable: true
  21766. });
  21767. Object.defineProperty(Light.prototype, "lightmapMode", {
  21768. /**
  21769. * Gets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  21770. */
  21771. get: function () {
  21772. return this._lightmapMode;
  21773. },
  21774. /**
  21775. * Sets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  21776. */
  21777. set: function (value) {
  21778. if (this._lightmapMode === value) {
  21779. return;
  21780. }
  21781. this._lightmapMode = value;
  21782. this._markMeshesAsLightDirty();
  21783. },
  21784. enumerable: true,
  21785. configurable: true
  21786. });
  21787. /**
  21788. * Returns the string "Light".
  21789. * @returns the class name
  21790. */
  21791. Light.prototype.getClassName = function () {
  21792. return "Light";
  21793. };
  21794. /**
  21795. * Converts the light information to a readable string for debug purpose.
  21796. * @param fullDetails Supports for multiple levels of logging within scene loading
  21797. * @returns the human readable light info
  21798. */
  21799. Light.prototype.toString = function (fullDetails) {
  21800. var ret = "Name: " + this.name;
  21801. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  21802. if (this.animations) {
  21803. for (var i = 0; i < this.animations.length; i++) {
  21804. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  21805. }
  21806. }
  21807. if (fullDetails) {
  21808. }
  21809. return ret;
  21810. };
  21811. /** @hidden */
  21812. Light.prototype._syncParentEnabledState = function () {
  21813. _super.prototype._syncParentEnabledState.call(this);
  21814. this._resyncMeshes();
  21815. };
  21816. /**
  21817. * Set the enabled state of this node.
  21818. * @param value - the new enabled state
  21819. */
  21820. Light.prototype.setEnabled = function (value) {
  21821. _super.prototype.setEnabled.call(this, value);
  21822. this._resyncMeshes();
  21823. };
  21824. /**
  21825. * Returns the Light associated shadow generator if any.
  21826. * @return the associated shadow generator.
  21827. */
  21828. Light.prototype.getShadowGenerator = function () {
  21829. return this._shadowGenerator;
  21830. };
  21831. /**
  21832. * Returns a Vector3, the absolute light position in the World.
  21833. * @returns the world space position of the light
  21834. */
  21835. Light.prototype.getAbsolutePosition = function () {
  21836. return BABYLON.Vector3.Zero();
  21837. };
  21838. /**
  21839. * Specifies if the light will affect the passed mesh.
  21840. * @param mesh The mesh to test against the light
  21841. * @return true the mesh is affected otherwise, false.
  21842. */
  21843. Light.prototype.canAffectMesh = function (mesh) {
  21844. if (!mesh) {
  21845. return true;
  21846. }
  21847. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  21848. return false;
  21849. }
  21850. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  21851. return false;
  21852. }
  21853. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  21854. return false;
  21855. }
  21856. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  21857. return false;
  21858. }
  21859. return true;
  21860. };
  21861. /**
  21862. * Sort function to order lights for rendering.
  21863. * @param a First Light object to compare to second.
  21864. * @param b Second Light object to compare first.
  21865. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  21866. */
  21867. Light.CompareLightsPriority = function (a, b) {
  21868. //shadow-casting lights have priority over non-shadow-casting lights
  21869. //the renderPrioirty is a secondary sort criterion
  21870. if (a.shadowEnabled !== b.shadowEnabled) {
  21871. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  21872. }
  21873. return b.renderPriority - a.renderPriority;
  21874. };
  21875. /**
  21876. * Releases resources associated with this node.
  21877. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  21878. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  21879. */
  21880. Light.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  21881. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  21882. if (this._shadowGenerator) {
  21883. this._shadowGenerator.dispose();
  21884. this._shadowGenerator = null;
  21885. }
  21886. // Animations
  21887. this.getScene().stopAnimation(this);
  21888. // Remove from meshes
  21889. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  21890. var mesh = _a[_i];
  21891. mesh._removeLightSource(this);
  21892. }
  21893. this._uniformBuffer.dispose();
  21894. // Remove from scene
  21895. this.getScene().removeLight(this);
  21896. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  21897. };
  21898. /**
  21899. * Returns the light type ID (integer).
  21900. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  21901. */
  21902. Light.prototype.getTypeID = function () {
  21903. return 0;
  21904. };
  21905. /**
  21906. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  21907. * @returns the scaled intensity in intensity mode unit
  21908. */
  21909. Light.prototype.getScaledIntensity = function () {
  21910. return this._photometricScale * this.intensity;
  21911. };
  21912. /**
  21913. * Returns a new Light object, named "name", from the current one.
  21914. * @param name The name of the cloned light
  21915. * @returns the new created light
  21916. */
  21917. Light.prototype.clone = function (name) {
  21918. var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
  21919. if (!constructor) {
  21920. return null;
  21921. }
  21922. return BABYLON.SerializationHelper.Clone(constructor, this);
  21923. };
  21924. /**
  21925. * Serializes the current light into a Serialization object.
  21926. * @returns the serialized object.
  21927. */
  21928. Light.prototype.serialize = function () {
  21929. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  21930. // Type
  21931. serializationObject.type = this.getTypeID();
  21932. // Parent
  21933. if (this.parent) {
  21934. serializationObject.parentId = this.parent.id;
  21935. }
  21936. // Inclusion / exclusions
  21937. if (this.excludedMeshes.length > 0) {
  21938. serializationObject.excludedMeshesIds = [];
  21939. this.excludedMeshes.forEach(function (mesh) {
  21940. serializationObject.excludedMeshesIds.push(mesh.id);
  21941. });
  21942. }
  21943. if (this.includedOnlyMeshes.length > 0) {
  21944. serializationObject.includedOnlyMeshesIds = [];
  21945. this.includedOnlyMeshes.forEach(function (mesh) {
  21946. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  21947. });
  21948. }
  21949. // Animations
  21950. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  21951. serializationObject.ranges = this.serializeAnimationRanges();
  21952. return serializationObject;
  21953. };
  21954. /**
  21955. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  21956. * This new light is named "name" and added to the passed scene.
  21957. * @param type Type according to the types available in Light.LIGHTTYPEID_x
  21958. * @param name The friendly name of the light
  21959. * @param scene The scene the new light will belong to
  21960. * @returns the constructor function
  21961. */
  21962. Light.GetConstructorFromName = function (type, name, scene) {
  21963. var constructorFunc = BABYLON.Node.Construct("Light_Type_" + type, name, scene);
  21964. if (constructorFunc) {
  21965. return constructorFunc;
  21966. }
  21967. // Default to no light for none present once.
  21968. return null;
  21969. };
  21970. /**
  21971. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  21972. * @param parsedLight The JSON representation of the light
  21973. * @param scene The scene to create the parsed light in
  21974. * @returns the created light after parsing
  21975. */
  21976. Light.Parse = function (parsedLight, scene) {
  21977. var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
  21978. if (!constructor) {
  21979. return null;
  21980. }
  21981. var light = BABYLON.SerializationHelper.Parse(constructor, parsedLight, scene);
  21982. // Inclusion / exclusions
  21983. if (parsedLight.excludedMeshesIds) {
  21984. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  21985. }
  21986. if (parsedLight.includedOnlyMeshesIds) {
  21987. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  21988. }
  21989. // Parent
  21990. if (parsedLight.parentId) {
  21991. light._waitingParentId = parsedLight.parentId;
  21992. }
  21993. // Animations
  21994. if (parsedLight.animations) {
  21995. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  21996. var parsedAnimation = parsedLight.animations[animationIndex];
  21997. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  21998. }
  21999. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  22000. }
  22001. if (parsedLight.autoAnimate) {
  22002. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  22003. }
  22004. return light;
  22005. };
  22006. Light.prototype._hookArrayForExcluded = function (array) {
  22007. var _this = this;
  22008. var oldPush = array.push;
  22009. array.push = function () {
  22010. var items = [];
  22011. for (var _i = 0; _i < arguments.length; _i++) {
  22012. items[_i] = arguments[_i];
  22013. }
  22014. var result = oldPush.apply(array, items);
  22015. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  22016. var item = items_1[_a];
  22017. item._resyncLighSource(_this);
  22018. }
  22019. return result;
  22020. };
  22021. var oldSplice = array.splice;
  22022. array.splice = function (index, deleteCount) {
  22023. var deleted = oldSplice.apply(array, [index, deleteCount]);
  22024. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  22025. var item = deleted_1[_i];
  22026. item._resyncLighSource(_this);
  22027. }
  22028. return deleted;
  22029. };
  22030. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  22031. var item = array_1[_i];
  22032. item._resyncLighSource(this);
  22033. }
  22034. };
  22035. Light.prototype._hookArrayForIncludedOnly = function (array) {
  22036. var _this = this;
  22037. var oldPush = array.push;
  22038. array.push = function () {
  22039. var items = [];
  22040. for (var _i = 0; _i < arguments.length; _i++) {
  22041. items[_i] = arguments[_i];
  22042. }
  22043. var result = oldPush.apply(array, items);
  22044. _this._resyncMeshes();
  22045. return result;
  22046. };
  22047. var oldSplice = array.splice;
  22048. array.splice = function (index, deleteCount) {
  22049. var deleted = oldSplice.apply(array, [index, deleteCount]);
  22050. _this._resyncMeshes();
  22051. return deleted;
  22052. };
  22053. this._resyncMeshes();
  22054. };
  22055. Light.prototype._resyncMeshes = function () {
  22056. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  22057. var mesh = _a[_i];
  22058. mesh._resyncLighSource(this);
  22059. }
  22060. };
  22061. /**
  22062. * Forces the meshes to update their light related information in their rendering used effects
  22063. * @hidden Internal Use Only
  22064. */
  22065. Light.prototype._markMeshesAsLightDirty = function () {
  22066. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  22067. var mesh = _a[_i];
  22068. if (mesh._lightSources.indexOf(this) !== -1) {
  22069. mesh._markSubMeshesAsLightDirty();
  22070. }
  22071. }
  22072. };
  22073. /**
  22074. * Recomputes the cached photometric scale if needed.
  22075. */
  22076. Light.prototype._computePhotometricScale = function () {
  22077. this._photometricScale = this._getPhotometricScale();
  22078. this.getScene().resetCachedMaterial();
  22079. };
  22080. /**
  22081. * Returns the Photometric Scale according to the light type and intensity mode.
  22082. */
  22083. Light.prototype._getPhotometricScale = function () {
  22084. var photometricScale = 0.0;
  22085. var lightTypeID = this.getTypeID();
  22086. //get photometric mode
  22087. var photometricMode = this.intensityMode;
  22088. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  22089. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  22090. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  22091. }
  22092. else {
  22093. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  22094. }
  22095. }
  22096. //compute photometric scale
  22097. switch (lightTypeID) {
  22098. case Light.LIGHTTYPEID_POINTLIGHT:
  22099. case Light.LIGHTTYPEID_SPOTLIGHT:
  22100. switch (photometricMode) {
  22101. case Light.INTENSITYMODE_LUMINOUSPOWER:
  22102. photometricScale = 1.0 / (4.0 * Math.PI);
  22103. break;
  22104. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  22105. photometricScale = 1.0;
  22106. break;
  22107. case Light.INTENSITYMODE_LUMINANCE:
  22108. photometricScale = this.radius * this.radius;
  22109. break;
  22110. }
  22111. break;
  22112. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  22113. switch (photometricMode) {
  22114. case Light.INTENSITYMODE_ILLUMINANCE:
  22115. photometricScale = 1.0;
  22116. break;
  22117. case Light.INTENSITYMODE_LUMINANCE:
  22118. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  22119. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  22120. var apexAngleRadians = this.radius;
  22121. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  22122. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  22123. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  22124. photometricScale = solidAngle;
  22125. break;
  22126. }
  22127. break;
  22128. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  22129. // No fall off in hemisperic light.
  22130. photometricScale = 1.0;
  22131. break;
  22132. }
  22133. return photometricScale;
  22134. };
  22135. /**
  22136. * Reorder the light in the scene according to their defined priority.
  22137. * @hidden Internal Use Only
  22138. */
  22139. Light.prototype._reorderLightsInScene = function () {
  22140. var scene = this.getScene();
  22141. if (this._renderPriority != 0) {
  22142. scene.requireLightSorting = true;
  22143. }
  22144. this.getScene().sortLightsByPriority();
  22145. };
  22146. /**
  22147. * Falloff Default: light is falling off following the material specification:
  22148. * standard material is using standard falloff whereas pbr material can request special falloff per materials.
  22149. */
  22150. Light.FALLOFF_DEFAULT = 0;
  22151. /**
  22152. * Falloff Physical: light is falling off following the inverse squared distance law.
  22153. */
  22154. Light.FALLOFF_PHYSICAL = 1;
  22155. /**
  22156. * Falloff gltf: light is falling off as described in the gltf moving to PBR document
  22157. * to enhance interoperability with other engines.
  22158. */
  22159. Light.FALLOFF_GLTF = 2;
  22160. /**
  22161. * Falloff Standard: light is falling off like in the standard material
  22162. * to enhance interoperability with other materials.
  22163. */
  22164. Light.FALLOFF_STANDARD = 3;
  22165. //lightmapMode Consts
  22166. /**
  22167. * If every light affecting the material is in this lightmapMode,
  22168. * material.lightmapTexture adds or multiplies
  22169. * (depends on material.useLightmapAsShadowmap)
  22170. * after every other light calculations.
  22171. */
  22172. Light.LIGHTMAP_DEFAULT = 0;
  22173. /**
  22174. * material.lightmapTexture as only diffuse lighting from this light
  22175. * adds only specular lighting from this light
  22176. * adds dynamic shadows
  22177. */
  22178. Light.LIGHTMAP_SPECULAR = 1;
  22179. /**
  22180. * material.lightmapTexture as only lighting
  22181. * no light calculation from this light
  22182. * only adds dynamic shadows from this light
  22183. */
  22184. Light.LIGHTMAP_SHADOWSONLY = 2;
  22185. // Intensity Mode Consts
  22186. /**
  22187. * Each light type uses the default quantity according to its type:
  22188. * point/spot lights use luminous intensity
  22189. * directional lights use illuminance
  22190. */
  22191. Light.INTENSITYMODE_AUTOMATIC = 0;
  22192. /**
  22193. * lumen (lm)
  22194. */
  22195. Light.INTENSITYMODE_LUMINOUSPOWER = 1;
  22196. /**
  22197. * candela (lm/sr)
  22198. */
  22199. Light.INTENSITYMODE_LUMINOUSINTENSITY = 2;
  22200. /**
  22201. * lux (lm/m^2)
  22202. */
  22203. Light.INTENSITYMODE_ILLUMINANCE = 3;
  22204. /**
  22205. * nit (cd/m^2)
  22206. */
  22207. Light.INTENSITYMODE_LUMINANCE = 4;
  22208. // Light types ids const.
  22209. /**
  22210. * Light type const id of the point light.
  22211. */
  22212. Light.LIGHTTYPEID_POINTLIGHT = 0;
  22213. /**
  22214. * Light type const id of the directional light.
  22215. */
  22216. Light.LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  22217. /**
  22218. * Light type const id of the spot light.
  22219. */
  22220. Light.LIGHTTYPEID_SPOTLIGHT = 2;
  22221. /**
  22222. * Light type const id of the hemispheric light.
  22223. */
  22224. Light.LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  22225. __decorate([
  22226. BABYLON.serializeAsColor3()
  22227. ], Light.prototype, "diffuse", void 0);
  22228. __decorate([
  22229. BABYLON.serializeAsColor3()
  22230. ], Light.prototype, "specular", void 0);
  22231. __decorate([
  22232. BABYLON.serialize()
  22233. ], Light.prototype, "falloffType", void 0);
  22234. __decorate([
  22235. BABYLON.serialize()
  22236. ], Light.prototype, "intensity", void 0);
  22237. __decorate([
  22238. BABYLON.serialize()
  22239. ], Light.prototype, "range", null);
  22240. __decorate([
  22241. BABYLON.serialize()
  22242. ], Light.prototype, "intensityMode", null);
  22243. __decorate([
  22244. BABYLON.serialize()
  22245. ], Light.prototype, "radius", null);
  22246. __decorate([
  22247. BABYLON.serialize()
  22248. ], Light.prototype, "_renderPriority", void 0);
  22249. __decorate([
  22250. BABYLON.expandToProperty("_reorderLightsInScene")
  22251. ], Light.prototype, "renderPriority", void 0);
  22252. __decorate([
  22253. BABYLON.serialize("shadowEnabled")
  22254. ], Light.prototype, "_shadowEnabled", void 0);
  22255. __decorate([
  22256. BABYLON.serialize("excludeWithLayerMask")
  22257. ], Light.prototype, "_excludeWithLayerMask", void 0);
  22258. __decorate([
  22259. BABYLON.serialize("includeOnlyWithLayerMask")
  22260. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  22261. __decorate([
  22262. BABYLON.serialize("lightmapMode")
  22263. ], Light.prototype, "_lightmapMode", void 0);
  22264. return Light;
  22265. }(BABYLON.Node));
  22266. BABYLON.Light = Light;
  22267. })(BABYLON || (BABYLON = {}));
  22268. //# sourceMappingURL=babylon.light.js.map
  22269. var BABYLON;
  22270. (function (BABYLON) {
  22271. /**
  22272. * This is the base class of all the camera used in the application.
  22273. * @see http://doc.babylonjs.com/features/cameras
  22274. */
  22275. var Camera = /** @class */ (function (_super) {
  22276. __extends(Camera, _super);
  22277. /**
  22278. * Instantiates a new camera object.
  22279. * This should not be used directly but through the inherited cameras: ArcRotate, Free...
  22280. * @see http://doc.babylonjs.com/features/cameras
  22281. * @param name Defines the name of the camera in the scene
  22282. * @param position Defines the position of the camera
  22283. * @param scene Defines the scene the camera belongs too
  22284. * @param setActiveOnSceneIfNoneActive Defines if the camera should be set as active after creation if no other camera have been defined in the scene
  22285. */
  22286. function Camera(name, position, scene, setActiveOnSceneIfNoneActive) {
  22287. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  22288. var _this = _super.call(this, name, scene) || this;
  22289. /**
  22290. * The vector the camera should consider as up.
  22291. * (default is Vector3(0, 1, 0) aka Vector3.Up())
  22292. */
  22293. _this.upVector = BABYLON.Vector3.Up();
  22294. /**
  22295. * Define the current limit on the left side for an orthographic camera
  22296. * In scene unit
  22297. */
  22298. _this.orthoLeft = null;
  22299. /**
  22300. * Define the current limit on the right side for an orthographic camera
  22301. * In scene unit
  22302. */
  22303. _this.orthoRight = null;
  22304. /**
  22305. * Define the current limit on the bottom side for an orthographic camera
  22306. * In scene unit
  22307. */
  22308. _this.orthoBottom = null;
  22309. /**
  22310. * Define the current limit on the top side for an orthographic camera
  22311. * In scene unit
  22312. */
  22313. _this.orthoTop = null;
  22314. /**
  22315. * Field Of View is set in Radians. (default is 0.8)
  22316. */
  22317. _this.fov = 0.8;
  22318. /**
  22319. * Define the minimum distance the camera can see from.
  22320. * This is important to note that the depth buffer are not infinite and the closer it starts
  22321. * the more your scene might encounter depth fighting issue.
  22322. */
  22323. _this.minZ = 1;
  22324. /**
  22325. * Define the maximum distance the camera can see to.
  22326. * This is important to note that the depth buffer are not infinite and the further it end
  22327. * the more your scene might encounter depth fighting issue.
  22328. */
  22329. _this.maxZ = 10000.0;
  22330. /**
  22331. * Define the default inertia of the camera.
  22332. * This helps giving a smooth feeling to the camera movement.
  22333. */
  22334. _this.inertia = 0.9;
  22335. /**
  22336. * Define the mode of the camera (Camera.PERSPECTIVE_CAMERA or Camera.PERSPECTIVE_ORTHOGRAPHIC)
  22337. */
  22338. _this.mode = Camera.PERSPECTIVE_CAMERA;
  22339. /**
  22340. * Define wether the camera is intermediate.
  22341. * This is usefull to not present the output directly to the screen in case of rig without post process for instance
  22342. */
  22343. _this.isIntermediate = false;
  22344. /**
  22345. * Define the viewport of the camera.
  22346. * This correspond to the portion of the screen the camera will render to in normalized 0 to 1 unit.
  22347. */
  22348. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  22349. /**
  22350. * Restricts the camera to viewing objects with the same layerMask.
  22351. * A camera with a layerMask of 1 will render mesh.layerMask & camera.layerMask!== 0
  22352. */
  22353. _this.layerMask = 0x0FFFFFFF;
  22354. /**
  22355. * fovMode sets the camera frustum bounds to the viewport bounds. (default is FOVMODE_VERTICAL_FIXED)
  22356. */
  22357. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  22358. /**
  22359. * Rig mode of the camera.
  22360. * This is usefull to create the camera with two "eyes" instead of one to create VR or stereoscopic scenes.
  22361. * This is normally controlled byt the camera themselves as internal use.
  22362. */
  22363. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  22364. /**
  22365. * Defines the list of custom render target the camera should render to.
  22366. * This is pretty helpfull if you wish to make a camera render to a texture you could reuse somewhere
  22367. * else in the scene.
  22368. */
  22369. _this.customRenderTargets = new Array();
  22370. /**
  22371. * Observable triggered when the camera view matrix has changed.
  22372. */
  22373. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  22374. /**
  22375. * Observable triggered when the camera Projection matrix has changed.
  22376. */
  22377. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  22378. /**
  22379. * Observable triggered when the inputs have been processed.
  22380. */
  22381. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  22382. /**
  22383. * Observable triggered when reset has been called and applied to the camera.
  22384. */
  22385. _this.onRestoreStateObservable = new BABYLON.Observable();
  22386. /** @hidden */
  22387. _this._rigCameras = new Array();
  22388. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  22389. /** @hidden */
  22390. _this._skipRendering = false;
  22391. /** @hidden */
  22392. _this._projectionMatrix = new BABYLON.Matrix();
  22393. /** @hidden */
  22394. _this._postProcesses = new Array();
  22395. /** @hidden */
  22396. _this._activeMeshes = new BABYLON.SmartArray(256);
  22397. _this._globalPosition = BABYLON.Vector3.Zero();
  22398. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  22399. _this._doNotComputeProjectionMatrix = false;
  22400. _this._transformMatrix = BABYLON.Matrix.Zero();
  22401. _this._refreshFrustumPlanes = true;
  22402. _this.getScene().addCamera(_this);
  22403. if (setActiveOnSceneIfNoneActive && !_this.getScene().activeCamera) {
  22404. _this.getScene().activeCamera = _this;
  22405. }
  22406. _this.position = position;
  22407. return _this;
  22408. }
  22409. /**
  22410. * Store current camera state (fov, position, etc..)
  22411. * @returns the camera
  22412. */
  22413. Camera.prototype.storeState = function () {
  22414. this._stateStored = true;
  22415. this._storedFov = this.fov;
  22416. return this;
  22417. };
  22418. /**
  22419. * Restores the camera state values if it has been stored. You must call storeState() first
  22420. */
  22421. Camera.prototype._restoreStateValues = function () {
  22422. if (!this._stateStored) {
  22423. return false;
  22424. }
  22425. this.fov = this._storedFov;
  22426. return true;
  22427. };
  22428. /**
  22429. * Restored camera state. You must call storeState() first.
  22430. * @returns true if restored and false otherwise
  22431. */
  22432. Camera.prototype.restoreState = function () {
  22433. if (this._restoreStateValues()) {
  22434. this.onRestoreStateObservable.notifyObservers(this);
  22435. return true;
  22436. }
  22437. return false;
  22438. };
  22439. /**
  22440. * Gets the class name of the camera.
  22441. * @returns the class name
  22442. */
  22443. Camera.prototype.getClassName = function () {
  22444. return "Camera";
  22445. };
  22446. /**
  22447. * Gets a string representation of the camera usefull for debug purpose.
  22448. * @param fullDetails Defines that a more verboe level of logging is required
  22449. * @returns the string representation
  22450. */
  22451. Camera.prototype.toString = function (fullDetails) {
  22452. var ret = "Name: " + this.name;
  22453. ret += ", type: " + this.getClassName();
  22454. if (this.animations) {
  22455. for (var i = 0; i < this.animations.length; i++) {
  22456. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  22457. }
  22458. }
  22459. if (fullDetails) {
  22460. }
  22461. return ret;
  22462. };
  22463. Object.defineProperty(Camera.prototype, "globalPosition", {
  22464. /**
  22465. * Gets the current world space position of the camera.
  22466. */
  22467. get: function () {
  22468. return this._globalPosition;
  22469. },
  22470. enumerable: true,
  22471. configurable: true
  22472. });
  22473. /**
  22474. * Gets the list of active meshes this frame (meshes no culled or excluded by lod s in the frame)
  22475. * @returns the active meshe list
  22476. */
  22477. Camera.prototype.getActiveMeshes = function () {
  22478. return this._activeMeshes;
  22479. };
  22480. /**
  22481. * Check wether a mesh is part of the current active mesh list of the camera
  22482. * @param mesh Defines the mesh to check
  22483. * @returns true if active, false otherwise
  22484. */
  22485. Camera.prototype.isActiveMesh = function (mesh) {
  22486. return (this._activeMeshes.indexOf(mesh) !== -1);
  22487. };
  22488. /**
  22489. * Is this camera ready to be used/rendered
  22490. * @param completeCheck defines if a complete check (including post processes) has to be done (false by default)
  22491. * @return true if the camera is ready
  22492. */
  22493. Camera.prototype.isReady = function (completeCheck) {
  22494. if (completeCheck === void 0) { completeCheck = false; }
  22495. if (completeCheck) {
  22496. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  22497. var pp = _a[_i];
  22498. if (pp && !pp.isReady()) {
  22499. return false;
  22500. }
  22501. }
  22502. }
  22503. return _super.prototype.isReady.call(this, completeCheck);
  22504. };
  22505. /** @hidden */
  22506. Camera.prototype._initCache = function () {
  22507. _super.prototype._initCache.call(this);
  22508. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  22509. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  22510. this._cache.mode = undefined;
  22511. this._cache.minZ = undefined;
  22512. this._cache.maxZ = undefined;
  22513. this._cache.fov = undefined;
  22514. this._cache.fovMode = undefined;
  22515. this._cache.aspectRatio = undefined;
  22516. this._cache.orthoLeft = undefined;
  22517. this._cache.orthoRight = undefined;
  22518. this._cache.orthoBottom = undefined;
  22519. this._cache.orthoTop = undefined;
  22520. this._cache.renderWidth = undefined;
  22521. this._cache.renderHeight = undefined;
  22522. };
  22523. /** @hidden */
  22524. Camera.prototype._updateCache = function (ignoreParentClass) {
  22525. if (!ignoreParentClass) {
  22526. _super.prototype._updateCache.call(this);
  22527. }
  22528. this._cache.position.copyFrom(this.position);
  22529. this._cache.upVector.copyFrom(this.upVector);
  22530. };
  22531. /** @hidden */
  22532. Camera.prototype._isSynchronized = function () {
  22533. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  22534. };
  22535. /** @hidden */
  22536. Camera.prototype._isSynchronizedViewMatrix = function () {
  22537. if (!_super.prototype._isSynchronized.call(this))
  22538. return false;
  22539. return this._cache.position.equals(this.position)
  22540. && this._cache.upVector.equals(this.upVector)
  22541. && this.isSynchronizedWithParent();
  22542. };
  22543. /** @hidden */
  22544. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  22545. var check = this._cache.mode === this.mode
  22546. && this._cache.minZ === this.minZ
  22547. && this._cache.maxZ === this.maxZ;
  22548. if (!check) {
  22549. return false;
  22550. }
  22551. var engine = this.getEngine();
  22552. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  22553. check = this._cache.fov === this.fov
  22554. && this._cache.fovMode === this.fovMode
  22555. && this._cache.aspectRatio === engine.getAspectRatio(this);
  22556. }
  22557. else {
  22558. check = this._cache.orthoLeft === this.orthoLeft
  22559. && this._cache.orthoRight === this.orthoRight
  22560. && this._cache.orthoBottom === this.orthoBottom
  22561. && this._cache.orthoTop === this.orthoTop
  22562. && this._cache.renderWidth === engine.getRenderWidth()
  22563. && this._cache.renderHeight === engine.getRenderHeight();
  22564. }
  22565. return check;
  22566. };
  22567. /**
  22568. * Attach the input controls to a specific dom element to get the input from.
  22569. * @param element Defines the element the controls should be listened from
  22570. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  22571. */
  22572. Camera.prototype.attachControl = function (element, noPreventDefault) {
  22573. };
  22574. /**
  22575. * Detach the current controls from the specified dom element.
  22576. * @param element Defines the element to stop listening the inputs from
  22577. */
  22578. Camera.prototype.detachControl = function (element) {
  22579. };
  22580. /**
  22581. * Update the camera state according to the different inputs gathered during the frame.
  22582. */
  22583. Camera.prototype.update = function () {
  22584. this._checkInputs();
  22585. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22586. this._updateRigCameras();
  22587. }
  22588. };
  22589. /** @hidden */
  22590. Camera.prototype._checkInputs = function () {
  22591. this.onAfterCheckInputsObservable.notifyObservers(this);
  22592. };
  22593. Object.defineProperty(Camera.prototype, "rigCameras", {
  22594. /** @hidden */
  22595. get: function () {
  22596. return this._rigCameras;
  22597. },
  22598. enumerable: true,
  22599. configurable: true
  22600. });
  22601. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  22602. get: function () {
  22603. return this._rigPostProcess;
  22604. },
  22605. enumerable: true,
  22606. configurable: true
  22607. });
  22608. /**
  22609. * Internal, gets the first post proces.
  22610. * @returns the first post process to be run on this camera.
  22611. */
  22612. Camera.prototype._getFirstPostProcess = function () {
  22613. for (var ppIndex = 0; ppIndex < this._postProcesses.length; ppIndex++) {
  22614. if (this._postProcesses[ppIndex] !== null) {
  22615. return this._postProcesses[ppIndex];
  22616. }
  22617. }
  22618. return null;
  22619. };
  22620. Camera.prototype._cascadePostProcessesToRigCams = function () {
  22621. // invalidate framebuffer
  22622. var firstPostProcess = this._getFirstPostProcess();
  22623. if (firstPostProcess) {
  22624. firstPostProcess.markTextureDirty();
  22625. }
  22626. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  22627. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  22628. var cam = this._rigCameras[i];
  22629. var rigPostProcess = cam._rigPostProcess;
  22630. // for VR rig, there does not have to be a post process
  22631. if (rigPostProcess) {
  22632. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  22633. if (isPass) {
  22634. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  22635. cam.isIntermediate = this._postProcesses.length === 0;
  22636. }
  22637. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  22638. rigPostProcess.markTextureDirty();
  22639. }
  22640. else {
  22641. cam._postProcesses = this._postProcesses.slice(0);
  22642. }
  22643. }
  22644. };
  22645. /**
  22646. * Attach a post process to the camera.
  22647. * @see http://doc.babylonjs.com/how_to/how_to_use_postprocesses#attach-postprocess
  22648. * @param postProcess The post process to attach to the camera
  22649. * @param insertAt The position of the post process in case several of them are in use in the scene
  22650. * @returns the position the post process has been inserted at
  22651. */
  22652. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  22653. if (insertAt === void 0) { insertAt = null; }
  22654. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  22655. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  22656. return 0;
  22657. }
  22658. if (insertAt == null || insertAt < 0) {
  22659. this._postProcesses.push(postProcess);
  22660. }
  22661. else if (this._postProcesses[insertAt] === null) {
  22662. this._postProcesses[insertAt] = postProcess;
  22663. }
  22664. else {
  22665. this._postProcesses.splice(insertAt, 0, postProcess);
  22666. }
  22667. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  22668. return this._postProcesses.indexOf(postProcess);
  22669. };
  22670. /**
  22671. * Detach a post process to the camera.
  22672. * @see http://doc.babylonjs.com/how_to/how_to_use_postprocesses#attach-postprocess
  22673. * @param postProcess The post process to detach from the camera
  22674. */
  22675. Camera.prototype.detachPostProcess = function (postProcess) {
  22676. var idx = this._postProcesses.indexOf(postProcess);
  22677. if (idx !== -1) {
  22678. this._postProcesses[idx] = null;
  22679. }
  22680. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  22681. };
  22682. /**
  22683. * Gets the current world matrix of the camera
  22684. */
  22685. Camera.prototype.getWorldMatrix = function () {
  22686. if (this._isSynchronizedViewMatrix()) {
  22687. return this._worldMatrix;
  22688. }
  22689. // Getting the the view matrix will also compute the world matrix.
  22690. this.getViewMatrix();
  22691. return this._worldMatrix;
  22692. };
  22693. /** @hidden */
  22694. Camera.prototype._getViewMatrix = function () {
  22695. return BABYLON.Matrix.Identity();
  22696. };
  22697. /**
  22698. * Gets the current view matrix of the camera.
  22699. * @param force forces the camera to recompute the matrix without looking at the cached state
  22700. * @returns the view matrix
  22701. */
  22702. Camera.prototype.getViewMatrix = function (force) {
  22703. if (!force && this._isSynchronizedViewMatrix()) {
  22704. return this._computedViewMatrix;
  22705. }
  22706. this.updateCache();
  22707. this._computedViewMatrix = this._getViewMatrix();
  22708. this._currentRenderId = this.getScene().getRenderId();
  22709. this._childRenderId = this._currentRenderId;
  22710. this._refreshFrustumPlanes = true;
  22711. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  22712. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  22713. }
  22714. this.onViewMatrixChangedObservable.notifyObservers(this);
  22715. this._computedViewMatrix.invertToRef(this._worldMatrix);
  22716. return this._computedViewMatrix;
  22717. };
  22718. /**
  22719. * Freeze the projection matrix.
  22720. * It will prevent the cache check of the camera projection compute and can speed up perf
  22721. * if no parameter of the camera are meant to change
  22722. * @param projection Defines manually a projection if necessary
  22723. */
  22724. Camera.prototype.freezeProjectionMatrix = function (projection) {
  22725. this._doNotComputeProjectionMatrix = true;
  22726. if (projection !== undefined) {
  22727. this._projectionMatrix = projection;
  22728. }
  22729. };
  22730. ;
  22731. /**
  22732. * Unfreeze the projection matrix if it has previously been freezed by freezeProjectionMatrix.
  22733. */
  22734. Camera.prototype.unfreezeProjectionMatrix = function () {
  22735. this._doNotComputeProjectionMatrix = false;
  22736. };
  22737. ;
  22738. /**
  22739. * Gets the current projection matrix of the camera.
  22740. * @param force forces the camera to recompute the matrix without looking at the cached state
  22741. * @returns the projection matrix
  22742. */
  22743. Camera.prototype.getProjectionMatrix = function (force) {
  22744. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  22745. return this._projectionMatrix;
  22746. }
  22747. // Cache
  22748. this._cache.mode = this.mode;
  22749. this._cache.minZ = this.minZ;
  22750. this._cache.maxZ = this.maxZ;
  22751. // Matrix
  22752. this._refreshFrustumPlanes = true;
  22753. var engine = this.getEngine();
  22754. var scene = this.getScene();
  22755. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  22756. this._cache.fov = this.fov;
  22757. this._cache.fovMode = this.fovMode;
  22758. this._cache.aspectRatio = engine.getAspectRatio(this);
  22759. if (this.minZ <= 0) {
  22760. this.minZ = 0.1;
  22761. }
  22762. if (scene.useRightHandedSystem) {
  22763. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  22764. }
  22765. else {
  22766. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  22767. }
  22768. }
  22769. else {
  22770. var halfWidth = engine.getRenderWidth() / 2.0;
  22771. var halfHeight = engine.getRenderHeight() / 2.0;
  22772. if (scene.useRightHandedSystem) {
  22773. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  22774. }
  22775. else {
  22776. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  22777. }
  22778. this._cache.orthoLeft = this.orthoLeft;
  22779. this._cache.orthoRight = this.orthoRight;
  22780. this._cache.orthoBottom = this.orthoBottom;
  22781. this._cache.orthoTop = this.orthoTop;
  22782. this._cache.renderWidth = engine.getRenderWidth();
  22783. this._cache.renderHeight = engine.getRenderHeight();
  22784. }
  22785. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  22786. return this._projectionMatrix;
  22787. };
  22788. /**
  22789. * Gets the transformation matrix (ie. the multiplication of view by projection matrices)
  22790. * @returns a Matrix
  22791. */
  22792. Camera.prototype.getTransformationMatrix = function () {
  22793. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  22794. return this._transformMatrix;
  22795. };
  22796. Camera.prototype._updateFrustumPlanes = function () {
  22797. if (!this._refreshFrustumPlanes) {
  22798. return;
  22799. }
  22800. this.getTransformationMatrix();
  22801. if (!this._frustumPlanes) {
  22802. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  22803. }
  22804. else {
  22805. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  22806. }
  22807. this._refreshFrustumPlanes = false;
  22808. };
  22809. /**
  22810. * Checks if a cullable object (mesh...) is in the camera frustum
  22811. * This checks the bounding box center. See isCompletelyInFrustum for a full bounding check
  22812. * @param target The object to check
  22813. * @returns true if the object is in frustum otherwise false
  22814. */
  22815. Camera.prototype.isInFrustum = function (target) {
  22816. this._updateFrustumPlanes();
  22817. return target.isInFrustum(this._frustumPlanes);
  22818. };
  22819. /**
  22820. * Checks if a cullable object (mesh...) is in the camera frustum
  22821. * Unlike isInFrustum this cheks the full bounding box
  22822. * @param target The object to check
  22823. * @returns true if the object is in frustum otherwise false
  22824. */
  22825. Camera.prototype.isCompletelyInFrustum = function (target) {
  22826. this._updateFrustumPlanes();
  22827. return target.isCompletelyInFrustum(this._frustumPlanes);
  22828. };
  22829. /**
  22830. * Gets a ray in the forward direction from the camera.
  22831. * @param length Defines the length of the ray to create
  22832. * @param transform Defines the transform to apply to the ray, by default the world matrx is used to create a workd space ray
  22833. * @param origin Defines the start point of the ray which defaults to the camera position
  22834. * @returns the forward ray
  22835. */
  22836. Camera.prototype.getForwardRay = function (length, transform, origin) {
  22837. if (length === void 0) { length = 100; }
  22838. if (!transform) {
  22839. transform = this.getWorldMatrix();
  22840. }
  22841. if (!origin) {
  22842. origin = this.position;
  22843. }
  22844. var forward = new BABYLON.Vector3(0, 0, 1);
  22845. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  22846. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  22847. return new BABYLON.Ray(origin, direction, length);
  22848. };
  22849. /**
  22850. * Releases resources associated with this node.
  22851. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  22852. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  22853. */
  22854. Camera.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  22855. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  22856. // Observables
  22857. this.onViewMatrixChangedObservable.clear();
  22858. this.onProjectionMatrixChangedObservable.clear();
  22859. this.onAfterCheckInputsObservable.clear();
  22860. this.onRestoreStateObservable.clear();
  22861. // Inputs
  22862. if (this.inputs) {
  22863. this.inputs.clear();
  22864. }
  22865. // Animations
  22866. this.getScene().stopAnimation(this);
  22867. // Remove from scene
  22868. this.getScene().removeCamera(this);
  22869. while (this._rigCameras.length > 0) {
  22870. var camera = this._rigCameras.pop();
  22871. if (camera) {
  22872. camera.dispose();
  22873. }
  22874. }
  22875. // Postprocesses
  22876. if (this._rigPostProcess) {
  22877. this._rigPostProcess.dispose(this);
  22878. this._rigPostProcess = null;
  22879. this._postProcesses = [];
  22880. }
  22881. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22882. this._rigPostProcess = null;
  22883. this._postProcesses = [];
  22884. }
  22885. else {
  22886. var i = this._postProcesses.length;
  22887. while (--i >= 0) {
  22888. var postProcess = this._postProcesses[i];
  22889. if (postProcess) {
  22890. postProcess.dispose(this);
  22891. }
  22892. }
  22893. }
  22894. // Render targets
  22895. var i = this.customRenderTargets.length;
  22896. while (--i >= 0) {
  22897. this.customRenderTargets[i].dispose();
  22898. }
  22899. this.customRenderTargets = [];
  22900. // Active Meshes
  22901. this._activeMeshes.dispose();
  22902. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  22903. };
  22904. Object.defineProperty(Camera.prototype, "leftCamera", {
  22905. /**
  22906. * Gets the left camera of a rig setup in case of Rigged Camera
  22907. */
  22908. get: function () {
  22909. if (this._rigCameras.length < 1) {
  22910. return null;
  22911. }
  22912. return this._rigCameras[0];
  22913. },
  22914. enumerable: true,
  22915. configurable: true
  22916. });
  22917. Object.defineProperty(Camera.prototype, "rightCamera", {
  22918. /**
  22919. * Gets the right camera of a rig setup in case of Rigged Camera
  22920. */
  22921. get: function () {
  22922. if (this._rigCameras.length < 2) {
  22923. return null;
  22924. }
  22925. return this._rigCameras[1];
  22926. },
  22927. enumerable: true,
  22928. configurable: true
  22929. });
  22930. /**
  22931. * Gets the left camera target of a rig setup in case of Rigged Camera
  22932. * @returns the target position
  22933. */
  22934. Camera.prototype.getLeftTarget = function () {
  22935. if (this._rigCameras.length < 1) {
  22936. return null;
  22937. }
  22938. return this._rigCameras[0].getTarget();
  22939. };
  22940. /**
  22941. * Gets the right camera target of a rig setup in case of Rigged Camera
  22942. * @returns the target position
  22943. */
  22944. Camera.prototype.getRightTarget = function () {
  22945. if (this._rigCameras.length < 2) {
  22946. return null;
  22947. }
  22948. return this._rigCameras[1].getTarget();
  22949. };
  22950. /**
  22951. * @hidden
  22952. */
  22953. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  22954. if (this.cameraRigMode === mode) {
  22955. return;
  22956. }
  22957. while (this._rigCameras.length > 0) {
  22958. var camera = this._rigCameras.pop();
  22959. if (camera) {
  22960. camera.dispose();
  22961. }
  22962. }
  22963. this.cameraRigMode = mode;
  22964. this._cameraRigParams = {};
  22965. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  22966. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  22967. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  22968. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  22969. // create the rig cameras, unless none
  22970. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22971. var leftCamera = this.createRigCamera(this.name + "_L", 0);
  22972. var rightCamera = this.createRigCamera(this.name + "_R", 1);
  22973. if (leftCamera && rightCamera) {
  22974. this._rigCameras.push(leftCamera);
  22975. this._rigCameras.push(rightCamera);
  22976. }
  22977. }
  22978. switch (this.cameraRigMode) {
  22979. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  22980. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  22981. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  22982. break;
  22983. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  22984. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  22985. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  22986. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  22987. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  22988. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  22989. break;
  22990. case Camera.RIG_MODE_VR:
  22991. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  22992. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  22993. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  22994. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22995. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  22996. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  22997. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  22998. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  22999. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  23000. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  23001. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  23002. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  23003. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  23004. if (metrics.compensateDistortion) {
  23005. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  23006. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  23007. }
  23008. break;
  23009. case Camera.RIG_MODE_WEBVR:
  23010. if (rigParams.vrDisplay) {
  23011. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  23012. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  23013. //Left eye
  23014. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  23015. this._rigCameras[0].setCameraRigParameter("left", true);
  23016. //leaving this for future reference
  23017. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  23018. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  23019. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  23020. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  23021. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  23022. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  23023. this._rigCameras[0].parent = this;
  23024. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  23025. //Right eye
  23026. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  23027. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  23028. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  23029. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  23030. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  23031. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  23032. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  23033. this._rigCameras[1].parent = this;
  23034. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  23035. if (Camera.UseAlternateWebVRRendering) {
  23036. this._rigCameras[1]._skipRendering = true;
  23037. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  23038. }
  23039. }
  23040. break;
  23041. }
  23042. this._cascadePostProcessesToRigCams();
  23043. this.update();
  23044. };
  23045. Camera.prototype._getVRProjectionMatrix = function () {
  23046. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  23047. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  23048. return this._projectionMatrix;
  23049. };
  23050. Camera.prototype._updateCameraRotationMatrix = function () {
  23051. //Here for WebVR
  23052. };
  23053. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  23054. //Here for WebVR
  23055. };
  23056. /**
  23057. * This function MUST be overwritten by the different WebVR cameras available.
  23058. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  23059. */
  23060. Camera.prototype._getWebVRProjectionMatrix = function () {
  23061. return BABYLON.Matrix.Identity();
  23062. };
  23063. /**
  23064. * This function MUST be overwritten by the different WebVR cameras available.
  23065. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  23066. */
  23067. Camera.prototype._getWebVRViewMatrix = function () {
  23068. return BABYLON.Matrix.Identity();
  23069. };
  23070. /** @hidden */
  23071. Camera.prototype.setCameraRigParameter = function (name, value) {
  23072. if (!this._cameraRigParams) {
  23073. this._cameraRigParams = {};
  23074. }
  23075. this._cameraRigParams[name] = value;
  23076. //provisionnally:
  23077. if (name === "interaxialDistance") {
  23078. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  23079. }
  23080. };
  23081. /**
  23082. * needs to be overridden by children so sub has required properties to be copied
  23083. * @hidden
  23084. */
  23085. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  23086. return null;
  23087. };
  23088. /**
  23089. * May need to be overridden by children
  23090. * @hidden
  23091. */
  23092. Camera.prototype._updateRigCameras = function () {
  23093. for (var i = 0; i < this._rigCameras.length; i++) {
  23094. this._rigCameras[i].minZ = this.minZ;
  23095. this._rigCameras[i].maxZ = this.maxZ;
  23096. this._rigCameras[i].fov = this.fov;
  23097. }
  23098. // only update viewport when ANAGLYPH
  23099. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  23100. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  23101. }
  23102. };
  23103. /** @hidden */
  23104. Camera.prototype._setupInputs = function () {
  23105. };
  23106. /**
  23107. * Serialiaze the camera setup to a json represention
  23108. * @returns the JSON representation
  23109. */
  23110. Camera.prototype.serialize = function () {
  23111. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  23112. // Type
  23113. serializationObject.type = this.getClassName();
  23114. // Parent
  23115. if (this.parent) {
  23116. serializationObject.parentId = this.parent.id;
  23117. }
  23118. if (this.inputs) {
  23119. this.inputs.serialize(serializationObject);
  23120. }
  23121. // Animations
  23122. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  23123. serializationObject.ranges = this.serializeAnimationRanges();
  23124. return serializationObject;
  23125. };
  23126. /**
  23127. * Clones the current camera.
  23128. * @param name The cloned camera name
  23129. * @returns the cloned camera
  23130. */
  23131. Camera.prototype.clone = function (name) {
  23132. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  23133. };
  23134. /**
  23135. * Gets the direction of the camera relative to a given local axis.
  23136. * @param localAxis Defines the reference axis to provide a relative direction.
  23137. * @return the direction
  23138. */
  23139. Camera.prototype.getDirection = function (localAxis) {
  23140. var result = BABYLON.Vector3.Zero();
  23141. this.getDirectionToRef(localAxis, result);
  23142. return result;
  23143. };
  23144. /**
  23145. * Gets the direction of the camera relative to a given local axis into a passed vector.
  23146. * @param localAxis Defines the reference axis to provide a relative direction.
  23147. * @param result Defines the vector to store the result in
  23148. */
  23149. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  23150. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  23151. };
  23152. /**
  23153. * Gets a camera constructor for a given camera type
  23154. * @param type The type of the camera to construct (should be equal to one of the camera class name)
  23155. * @param name The name of the camera the result will be able to instantiate
  23156. * @param scene The scene the result will construct the camera in
  23157. * @param interaxial_distance In case of stereoscopic setup, the distance between both eyes
  23158. * @param isStereoscopicSideBySide In case of stereoscopic setup, should the sereo be side b side
  23159. * @returns a factory method to construc the camera
  23160. */
  23161. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  23162. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  23163. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  23164. var constructorFunc = BABYLON.Node.Construct(type, name, scene, {
  23165. interaxial_distance: interaxial_distance,
  23166. isStereoscopicSideBySide: isStereoscopicSideBySide
  23167. });
  23168. if (constructorFunc) {
  23169. return constructorFunc;
  23170. }
  23171. // Default to universal camera
  23172. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  23173. };
  23174. /**
  23175. * Compute the world matrix of the camera.
  23176. * @returns the camera workd matrix
  23177. */
  23178. Camera.prototype.computeWorldMatrix = function () {
  23179. return this.getWorldMatrix();
  23180. };
  23181. /**
  23182. * Parse a JSON and creates the camera from the parsed information
  23183. * @param parsedCamera The JSON to parse
  23184. * @param scene The scene to instantiate the camera in
  23185. * @returns the newly constructed camera
  23186. */
  23187. Camera.Parse = function (parsedCamera, scene) {
  23188. var type = parsedCamera.type;
  23189. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  23190. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  23191. // Parent
  23192. if (parsedCamera.parentId) {
  23193. camera._waitingParentId = parsedCamera.parentId;
  23194. }
  23195. //If camera has an input manager, let it parse inputs settings
  23196. if (camera.inputs) {
  23197. camera.inputs.parse(parsedCamera);
  23198. camera._setupInputs();
  23199. }
  23200. if (camera.setPosition) { // need to force position
  23201. camera.position.copyFromFloats(0, 0, 0);
  23202. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  23203. }
  23204. // Target
  23205. if (parsedCamera.target) {
  23206. if (camera.setTarget) {
  23207. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  23208. }
  23209. }
  23210. // Apply 3d rig, when found
  23211. if (parsedCamera.cameraRigMode) {
  23212. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  23213. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  23214. }
  23215. // Animations
  23216. if (parsedCamera.animations) {
  23217. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  23218. var parsedAnimation = parsedCamera.animations[animationIndex];
  23219. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  23220. }
  23221. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  23222. }
  23223. if (parsedCamera.autoAnimate) {
  23224. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  23225. }
  23226. return camera;
  23227. };
  23228. /**
  23229. * This is the default projection mode used by the cameras.
  23230. * It helps recreating a feeling of perspective and better appreciate depth.
  23231. * This is the best way to simulate real life cameras.
  23232. */
  23233. Camera.PERSPECTIVE_CAMERA = 0;
  23234. /**
  23235. * This helps creating camera with an orthographic mode.
  23236. * Orthographic is commonly used in engineering as a means to produce object specifications that communicate dimensions unambiguously, each line of 1 unit length (cm, meter..whatever) will appear to have the same length everywhere on the drawing. This allows the drafter to dimension only a subset of lines and let the reader know that other lines of that length on the drawing are also that length in reality. Every parallel line in the drawing is also parallel in the object.
  23237. */
  23238. Camera.ORTHOGRAPHIC_CAMERA = 1;
  23239. /**
  23240. * This is the default FOV mode for perspective cameras.
  23241. * This setting aligns the upper and lower bounds of the viewport to the upper and lower bounds of the camera frustum.
  23242. */
  23243. Camera.FOVMODE_VERTICAL_FIXED = 0;
  23244. /**
  23245. * This setting aligns the left and right bounds of the viewport to the left and right bounds of the camera frustum.
  23246. */
  23247. Camera.FOVMODE_HORIZONTAL_FIXED = 1;
  23248. /**
  23249. * This specifies ther is no need for a camera rig.
  23250. * Basically only one eye is rendered corresponding to the camera.
  23251. */
  23252. Camera.RIG_MODE_NONE = 0;
  23253. /**
  23254. * Simulates a camera Rig with one blue eye and one red eye.
  23255. * This can be use with 3d blue and red glasses.
  23256. */
  23257. Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  23258. /**
  23259. * Defines that both eyes of the camera will be rendered side by side with a parallel target.
  23260. */
  23261. Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  23262. /**
  23263. * Defines that both eyes of the camera will be rendered side by side with a none parallel target.
  23264. */
  23265. Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  23266. /**
  23267. * Defines that both eyes of the camera will be rendered over under each other.
  23268. */
  23269. Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  23270. /**
  23271. * Defines that both eyes of the camera should be renderered in a VR mode (carbox).
  23272. */
  23273. Camera.RIG_MODE_VR = 20;
  23274. /**
  23275. * Defines that both eyes of the camera should be renderered in a VR mode (webVR).
  23276. */
  23277. Camera.RIG_MODE_WEBVR = 21;
  23278. /**
  23279. * Defines if by default attaching controls should prevent the default javascript event to continue.
  23280. */
  23281. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  23282. /**
  23283. * @hidden
  23284. * Might be removed once multiview will be a thing
  23285. */
  23286. Camera.UseAlternateWebVRRendering = false;
  23287. __decorate([
  23288. BABYLON.serializeAsVector3()
  23289. ], Camera.prototype, "position", void 0);
  23290. __decorate([
  23291. BABYLON.serializeAsVector3()
  23292. ], Camera.prototype, "upVector", void 0);
  23293. __decorate([
  23294. BABYLON.serialize()
  23295. ], Camera.prototype, "orthoLeft", void 0);
  23296. __decorate([
  23297. BABYLON.serialize()
  23298. ], Camera.prototype, "orthoRight", void 0);
  23299. __decorate([
  23300. BABYLON.serialize()
  23301. ], Camera.prototype, "orthoBottom", void 0);
  23302. __decorate([
  23303. BABYLON.serialize()
  23304. ], Camera.prototype, "orthoTop", void 0);
  23305. __decorate([
  23306. BABYLON.serialize()
  23307. ], Camera.prototype, "fov", void 0);
  23308. __decorate([
  23309. BABYLON.serialize()
  23310. ], Camera.prototype, "minZ", void 0);
  23311. __decorate([
  23312. BABYLON.serialize()
  23313. ], Camera.prototype, "maxZ", void 0);
  23314. __decorate([
  23315. BABYLON.serialize()
  23316. ], Camera.prototype, "inertia", void 0);
  23317. __decorate([
  23318. BABYLON.serialize()
  23319. ], Camera.prototype, "mode", void 0);
  23320. __decorate([
  23321. BABYLON.serialize()
  23322. ], Camera.prototype, "layerMask", void 0);
  23323. __decorate([
  23324. BABYLON.serialize()
  23325. ], Camera.prototype, "fovMode", void 0);
  23326. __decorate([
  23327. BABYLON.serialize()
  23328. ], Camera.prototype, "cameraRigMode", void 0);
  23329. __decorate([
  23330. BABYLON.serialize()
  23331. ], Camera.prototype, "interaxialDistance", void 0);
  23332. __decorate([
  23333. BABYLON.serialize()
  23334. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  23335. return Camera;
  23336. }(BABYLON.Node));
  23337. BABYLON.Camera = Camera;
  23338. })(BABYLON || (BABYLON = {}));
  23339. //# sourceMappingURL=babylon.camera.js.map
  23340. var BABYLON;
  23341. (function (BABYLON) {
  23342. var RenderingManager = /** @class */ (function () {
  23343. function RenderingManager(scene) {
  23344. /**
  23345. * @hidden
  23346. */
  23347. this._useSceneAutoClearSetup = false;
  23348. this._renderingGroups = new Array();
  23349. this._autoClearDepthStencil = {};
  23350. this._customOpaqueSortCompareFn = {};
  23351. this._customAlphaTestSortCompareFn = {};
  23352. this._customTransparentSortCompareFn = {};
  23353. this._renderingGroupInfo = new BABYLON.RenderingGroupInfo();
  23354. this._scene = scene;
  23355. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  23356. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  23357. }
  23358. }
  23359. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  23360. if (depth === void 0) { depth = true; }
  23361. if (stencil === void 0) { stencil = true; }
  23362. if (this._depthStencilBufferAlreadyCleaned) {
  23363. return;
  23364. }
  23365. this._scene.getEngine().clear(null, false, depth, stencil);
  23366. this._depthStencilBufferAlreadyCleaned = true;
  23367. };
  23368. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  23369. // Update the observable context (not null as it only goes away on dispose)
  23370. var info = this._renderingGroupInfo;
  23371. info.scene = this._scene;
  23372. info.camera = this._scene.activeCamera;
  23373. // Dispatch sprites
  23374. if (this._scene.spriteManagers && renderSprites) {
  23375. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  23376. var manager = this._scene.spriteManagers[index];
  23377. this.dispatchSprites(manager);
  23378. }
  23379. }
  23380. // Render
  23381. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  23382. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  23383. var renderingGroup = this._renderingGroups[index];
  23384. if (!renderingGroup)
  23385. continue;
  23386. var renderingGroupMask = Math.pow(2, index);
  23387. info.renderingGroupId = index;
  23388. // Before Observable
  23389. this._scene.onBeforeRenderingGroupObservable.notifyObservers(info, renderingGroupMask);
  23390. // Clear depth/stencil if needed
  23391. if (RenderingManager.AUTOCLEAR) {
  23392. var autoClear = this._useSceneAutoClearSetup ?
  23393. this._scene.getAutoClearDepthStencilSetup(index) :
  23394. this._autoClearDepthStencil[index];
  23395. if (autoClear && autoClear.autoClear) {
  23396. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  23397. }
  23398. }
  23399. // Render
  23400. for (var _i = 0, _a = this._scene._beforeRenderingGroupDrawStage; _i < _a.length; _i++) {
  23401. var step = _a[_i];
  23402. step.action(index);
  23403. }
  23404. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  23405. for (var _b = 0, _c = this._scene._afterRenderingGroupDrawStage; _b < _c.length; _b++) {
  23406. var step = _c[_b];
  23407. step.action(index);
  23408. }
  23409. // After Observable
  23410. this._scene.onAfterRenderingGroupObservable.notifyObservers(info, renderingGroupMask);
  23411. }
  23412. };
  23413. RenderingManager.prototype.reset = function () {
  23414. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  23415. var renderingGroup = this._renderingGroups[index];
  23416. if (renderingGroup) {
  23417. renderingGroup.prepare();
  23418. }
  23419. }
  23420. };
  23421. RenderingManager.prototype.dispose = function () {
  23422. this.freeRenderingGroups();
  23423. this._renderingGroups.length = 0;
  23424. this._renderingGroupInfo = null;
  23425. };
  23426. /**
  23427. * Clear the info related to rendering groups preventing retention points during dispose.
  23428. */
  23429. RenderingManager.prototype.freeRenderingGroups = function () {
  23430. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  23431. var renderingGroup = this._renderingGroups[index];
  23432. if (renderingGroup) {
  23433. renderingGroup.dispose();
  23434. }
  23435. }
  23436. };
  23437. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  23438. if (this._renderingGroups[renderingGroupId] === undefined) {
  23439. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  23440. }
  23441. };
  23442. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  23443. var renderingGroupId = spriteManager.renderingGroupId || 0;
  23444. this._prepareRenderingGroup(renderingGroupId);
  23445. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  23446. };
  23447. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  23448. var renderingGroupId = particleSystem.renderingGroupId || 0;
  23449. this._prepareRenderingGroup(renderingGroupId);
  23450. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  23451. };
  23452. /**
  23453. * @param subMesh The submesh to dispatch
  23454. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  23455. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  23456. */
  23457. RenderingManager.prototype.dispatch = function (subMesh, mesh, material) {
  23458. if (mesh === undefined) {
  23459. mesh = subMesh.getMesh();
  23460. }
  23461. var renderingGroupId = mesh.renderingGroupId || 0;
  23462. this._prepareRenderingGroup(renderingGroupId);
  23463. this._renderingGroups[renderingGroupId].dispatch(subMesh, mesh, material);
  23464. };
  23465. /**
  23466. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  23467. * This allowed control for front to back rendering or reversly depending of the special needs.
  23468. *
  23469. * @param renderingGroupId The rendering group id corresponding to its index
  23470. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  23471. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  23472. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  23473. */
  23474. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  23475. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  23476. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  23477. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  23478. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  23479. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  23480. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  23481. if (this._renderingGroups[renderingGroupId]) {
  23482. var group = this._renderingGroups[renderingGroupId];
  23483. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  23484. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  23485. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  23486. }
  23487. };
  23488. /**
  23489. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  23490. *
  23491. * @param renderingGroupId The rendering group id corresponding to its index
  23492. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  23493. * @param depth Automatically clears depth between groups if true and autoClear is true.
  23494. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  23495. */
  23496. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  23497. if (depth === void 0) { depth = true; }
  23498. if (stencil === void 0) { stencil = true; }
  23499. this._autoClearDepthStencil[renderingGroupId] = {
  23500. autoClear: autoClearDepthStencil,
  23501. depth: depth,
  23502. stencil: stencil
  23503. };
  23504. };
  23505. /**
  23506. * Gets the current auto clear configuration for one rendering group of the rendering
  23507. * manager.
  23508. * @param index the rendering group index to get the information for
  23509. * @returns The auto clear setup for the requested rendering group
  23510. */
  23511. RenderingManager.prototype.getAutoClearDepthStencilSetup = function (index) {
  23512. return this._autoClearDepthStencil[index];
  23513. };
  23514. /**
  23515. * The max id used for rendering groups (not included)
  23516. */
  23517. RenderingManager.MAX_RENDERINGGROUPS = 4;
  23518. /**
  23519. * The min id used for rendering groups (included)
  23520. */
  23521. RenderingManager.MIN_RENDERINGGROUPS = 0;
  23522. /**
  23523. * Used to globally prevent autoclearing scenes.
  23524. */
  23525. RenderingManager.AUTOCLEAR = true;
  23526. return RenderingManager;
  23527. }());
  23528. BABYLON.RenderingManager = RenderingManager;
  23529. })(BABYLON || (BABYLON = {}));
  23530. //# sourceMappingURL=babylon.renderingManager.js.map
  23531. var BABYLON;
  23532. (function (BABYLON) {
  23533. var RenderingGroup = /** @class */ (function () {
  23534. /**
  23535. * Creates a new rendering group.
  23536. * @param index The rendering group index
  23537. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  23538. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  23539. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  23540. */
  23541. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  23542. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  23543. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  23544. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  23545. this.index = index;
  23546. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  23547. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  23548. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  23549. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  23550. this._particleSystems = new BABYLON.SmartArray(256);
  23551. this._spriteManagers = new BABYLON.SmartArray(256);
  23552. this._edgesRenderers = new BABYLON.SmartArray(16);
  23553. this._scene = scene;
  23554. this.opaqueSortCompareFn = opaqueSortCompareFn;
  23555. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  23556. this.transparentSortCompareFn = transparentSortCompareFn;
  23557. }
  23558. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  23559. /**
  23560. * Set the opaque sort comparison function.
  23561. * If null the sub meshes will be render in the order they were created
  23562. */
  23563. set: function (value) {
  23564. this._opaqueSortCompareFn = value;
  23565. if (value) {
  23566. this._renderOpaque = this.renderOpaqueSorted;
  23567. }
  23568. else {
  23569. this._renderOpaque = RenderingGroup.renderUnsorted;
  23570. }
  23571. },
  23572. enumerable: true,
  23573. configurable: true
  23574. });
  23575. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  23576. /**
  23577. * Set the alpha test sort comparison function.
  23578. * If null the sub meshes will be render in the order they were created
  23579. */
  23580. set: function (value) {
  23581. this._alphaTestSortCompareFn = value;
  23582. if (value) {
  23583. this._renderAlphaTest = this.renderAlphaTestSorted;
  23584. }
  23585. else {
  23586. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  23587. }
  23588. },
  23589. enumerable: true,
  23590. configurable: true
  23591. });
  23592. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  23593. /**
  23594. * Set the transparent sort comparison function.
  23595. * If null the sub meshes will be render in the order they were created
  23596. */
  23597. set: function (value) {
  23598. if (value) {
  23599. this._transparentSortCompareFn = value;
  23600. }
  23601. else {
  23602. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  23603. }
  23604. this._renderTransparent = this.renderTransparentSorted;
  23605. },
  23606. enumerable: true,
  23607. configurable: true
  23608. });
  23609. /**
  23610. * Render all the sub meshes contained in the group.
  23611. * @param customRenderFunction Used to override the default render behaviour of the group.
  23612. * @returns true if rendered some submeshes.
  23613. */
  23614. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  23615. if (customRenderFunction) {
  23616. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  23617. return;
  23618. }
  23619. var engine = this._scene.getEngine();
  23620. // Depth only
  23621. if (this._depthOnlySubMeshes.length !== 0) {
  23622. engine.setColorWrite(false);
  23623. this._renderAlphaTest(this._depthOnlySubMeshes);
  23624. engine.setColorWrite(true);
  23625. }
  23626. // Opaque
  23627. if (this._opaqueSubMeshes.length !== 0) {
  23628. this._renderOpaque(this._opaqueSubMeshes);
  23629. }
  23630. // Alpha test
  23631. if (this._alphaTestSubMeshes.length !== 0) {
  23632. this._renderAlphaTest(this._alphaTestSubMeshes);
  23633. }
  23634. var stencilState = engine.getStencilBuffer();
  23635. engine.setStencilBuffer(false);
  23636. // Sprites
  23637. if (renderSprites) {
  23638. this._renderSprites();
  23639. }
  23640. // Particles
  23641. if (renderParticles) {
  23642. this._renderParticles(activeMeshes);
  23643. }
  23644. if (this.onBeforeTransparentRendering) {
  23645. this.onBeforeTransparentRendering();
  23646. }
  23647. // Transparent
  23648. if (this._transparentSubMeshes.length !== 0) {
  23649. this._renderTransparent(this._transparentSubMeshes);
  23650. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23651. }
  23652. // Set back stencil to false in case it changes before the edge renderer.
  23653. engine.setStencilBuffer(false);
  23654. // Edges
  23655. if (this._edgesRenderers.length) {
  23656. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  23657. this._edgesRenderers.data[edgesRendererIndex].render();
  23658. }
  23659. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23660. }
  23661. // Restore Stencil state.
  23662. engine.setStencilBuffer(stencilState);
  23663. };
  23664. /**
  23665. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  23666. * @param subMeshes The submeshes to render
  23667. */
  23668. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  23669. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
  23670. };
  23671. /**
  23672. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  23673. * @param subMeshes The submeshes to render
  23674. */
  23675. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  23676. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
  23677. };
  23678. /**
  23679. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  23680. * @param subMeshes The submeshes to render
  23681. */
  23682. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  23683. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);
  23684. };
  23685. /**
  23686. * Renders the submeshes in a specified order.
  23687. * @param subMeshes The submeshes to sort before render
  23688. * @param sortCompareFn The comparison function use to sort
  23689. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  23690. * @param transparent Specifies to activate blending if true
  23691. */
  23692. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) {
  23693. var subIndex = 0;
  23694. var subMesh;
  23695. var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero();
  23696. for (; subIndex < subMeshes.length; subIndex++) {
  23697. subMesh = subMeshes.data[subIndex];
  23698. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  23699. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  23700. }
  23701. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  23702. if (sortCompareFn) {
  23703. sortedArray.sort(sortCompareFn);
  23704. }
  23705. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  23706. subMesh = sortedArray[subIndex];
  23707. if (transparent) {
  23708. var material = subMesh.getMaterial();
  23709. if (material && material.needDepthPrePass) {
  23710. var engine = material.getScene().getEngine();
  23711. engine.setColorWrite(false);
  23712. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23713. subMesh.render(false);
  23714. engine.setColorWrite(true);
  23715. }
  23716. }
  23717. subMesh.render(transparent);
  23718. }
  23719. };
  23720. /**
  23721. * Renders the submeshes in the order they were dispatched (no sort applied).
  23722. * @param subMeshes The submeshes to render
  23723. */
  23724. RenderingGroup.renderUnsorted = function (subMeshes) {
  23725. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  23726. var submesh = subMeshes.data[subIndex];
  23727. submesh.render(false);
  23728. }
  23729. };
  23730. /**
  23731. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23732. * are rendered back to front if in the same alpha index.
  23733. *
  23734. * @param a The first submesh
  23735. * @param b The second submesh
  23736. * @returns The result of the comparison
  23737. */
  23738. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  23739. // Alpha index first
  23740. if (a._alphaIndex > b._alphaIndex) {
  23741. return 1;
  23742. }
  23743. if (a._alphaIndex < b._alphaIndex) {
  23744. return -1;
  23745. }
  23746. // Then distance to camera
  23747. return RenderingGroup.backToFrontSortCompare(a, b);
  23748. };
  23749. /**
  23750. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23751. * are rendered back to front.
  23752. *
  23753. * @param a The first submesh
  23754. * @param b The second submesh
  23755. * @returns The result of the comparison
  23756. */
  23757. RenderingGroup.backToFrontSortCompare = function (a, b) {
  23758. // Then distance to camera
  23759. if (a._distanceToCamera < b._distanceToCamera) {
  23760. return 1;
  23761. }
  23762. if (a._distanceToCamera > b._distanceToCamera) {
  23763. return -1;
  23764. }
  23765. return 0;
  23766. };
  23767. /**
  23768. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23769. * are rendered front to back (prevent overdraw).
  23770. *
  23771. * @param a The first submesh
  23772. * @param b The second submesh
  23773. * @returns The result of the comparison
  23774. */
  23775. RenderingGroup.frontToBackSortCompare = function (a, b) {
  23776. // Then distance to camera
  23777. if (a._distanceToCamera < b._distanceToCamera) {
  23778. return -1;
  23779. }
  23780. if (a._distanceToCamera > b._distanceToCamera) {
  23781. return 1;
  23782. }
  23783. return 0;
  23784. };
  23785. /**
  23786. * Resets the different lists of submeshes to prepare a new frame.
  23787. */
  23788. RenderingGroup.prototype.prepare = function () {
  23789. this._opaqueSubMeshes.reset();
  23790. this._transparentSubMeshes.reset();
  23791. this._alphaTestSubMeshes.reset();
  23792. this._depthOnlySubMeshes.reset();
  23793. this._particleSystems.reset();
  23794. this._spriteManagers.reset();
  23795. this._edgesRenderers.reset();
  23796. };
  23797. RenderingGroup.prototype.dispose = function () {
  23798. this._opaqueSubMeshes.dispose();
  23799. this._transparentSubMeshes.dispose();
  23800. this._alphaTestSubMeshes.dispose();
  23801. this._depthOnlySubMeshes.dispose();
  23802. this._particleSystems.dispose();
  23803. this._spriteManagers.dispose();
  23804. this._edgesRenderers.dispose();
  23805. };
  23806. /**
  23807. * Inserts the submesh in its correct queue depending on its material.
  23808. * @param subMesh The submesh to dispatch
  23809. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  23810. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  23811. */
  23812. RenderingGroup.prototype.dispatch = function (subMesh, mesh, material) {
  23813. // Get mesh and materials if not provided
  23814. if (mesh === undefined) {
  23815. mesh = subMesh.getMesh();
  23816. }
  23817. if (material === undefined) {
  23818. material = subMesh.getMaterial();
  23819. }
  23820. if (material === null || material === undefined) {
  23821. return;
  23822. }
  23823. if (material.needAlphaBlendingForMesh(mesh)) { // Transparent
  23824. this._transparentSubMeshes.push(subMesh);
  23825. }
  23826. else if (material.needAlphaTesting()) { // Alpha test
  23827. if (material.needDepthPrePass) {
  23828. this._depthOnlySubMeshes.push(subMesh);
  23829. }
  23830. this._alphaTestSubMeshes.push(subMesh);
  23831. }
  23832. else {
  23833. if (material.needDepthPrePass) {
  23834. this._depthOnlySubMeshes.push(subMesh);
  23835. }
  23836. this._opaqueSubMeshes.push(subMesh); // Opaque
  23837. }
  23838. if (mesh._edgesRenderer && mesh._edgesRenderer.isEnabled) {
  23839. this._edgesRenderers.push(mesh._edgesRenderer);
  23840. }
  23841. };
  23842. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  23843. this._spriteManagers.push(spriteManager);
  23844. };
  23845. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  23846. this._particleSystems.push(particleSystem);
  23847. };
  23848. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  23849. if (this._particleSystems.length === 0) {
  23850. return;
  23851. }
  23852. // Particles
  23853. var activeCamera = this._scene.activeCamera;
  23854. this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);
  23855. for (var particleIndex = 0; particleIndex < this._particleSystems.length; particleIndex++) {
  23856. var particleSystem = this._particleSystems.data[particleIndex];
  23857. if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
  23858. continue;
  23859. }
  23860. var emitter = particleSystem.emitter;
  23861. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  23862. this._scene._activeParticles.addCount(particleSystem.render(), false);
  23863. }
  23864. }
  23865. this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);
  23866. };
  23867. RenderingGroup.prototype._renderSprites = function () {
  23868. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  23869. return;
  23870. }
  23871. // Sprites
  23872. var activeCamera = this._scene.activeCamera;
  23873. this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);
  23874. for (var id = 0; id < this._spriteManagers.length; id++) {
  23875. var spriteManager = this._spriteManagers.data[id];
  23876. if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  23877. spriteManager.render();
  23878. }
  23879. }
  23880. this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene);
  23881. };
  23882. return RenderingGroup;
  23883. }());
  23884. BABYLON.RenderingGroup = RenderingGroup;
  23885. })(BABYLON || (BABYLON = {}));
  23886. //# sourceMappingURL=babylon.renderingGroup.js.map
  23887. var BABYLON;
  23888. (function (BABYLON) {
  23889. /**
  23890. * Groups all the scene component constants in one place to ease maintenance.
  23891. * @hidden
  23892. */
  23893. var SceneComponentConstants = /** @class */ (function () {
  23894. function SceneComponentConstants() {
  23895. }
  23896. SceneComponentConstants.NAME_EFFECTLAYER = "EffectLayer";
  23897. SceneComponentConstants.NAME_LAYER = "Layer";
  23898. SceneComponentConstants.NAME_LENSFLARESYSTEM = "LensFlareSystem";
  23899. SceneComponentConstants.NAME_BOUNDINGBOXRENDERER = "BoundingBoxRenderer";
  23900. SceneComponentConstants.NAME_PARTICLESYSTEM = "ParticleSystem";
  23901. SceneComponentConstants.NAME_GAMEPAD = "Gamepad";
  23902. SceneComponentConstants.NAME_SIMPLIFICATIONQUEUE = "SimplificationQueue";
  23903. SceneComponentConstants.NAME_GEOMETRYBUFFERRENDERER = "GeometryBufferRenderer";
  23904. SceneComponentConstants.NAME_DEPTHRENDERER = "DepthRenderer";
  23905. SceneComponentConstants.NAME_POSTPROCESSRENDERPIPELINEMANAGER = "PostProcessRenderPipelineManager";
  23906. SceneComponentConstants.NAME_SPRITE = "Sprite";
  23907. SceneComponentConstants.NAME_OUTLINERENDERER = "Outline";
  23908. SceneComponentConstants.NAME_PROCEDURALTEXTURE = "ProceduralTexture";
  23909. SceneComponentConstants.NAME_SHADOWGENERATOR = "ShadowGenerator";
  23910. SceneComponentConstants.NAME_OCTREE = "Octree";
  23911. SceneComponentConstants.NAME_PHYSICSENGINE = "PhysicsEngine";
  23912. SceneComponentConstants.NAME_AUDIO = "Audio";
  23913. SceneComponentConstants.STEP_ISREADYFORMESH_EFFECTLAYER = 0;
  23914. SceneComponentConstants.STEP_BEFOREEVALUATEACTIVEMESH_BOUNDINGBOXRENDERER = 0;
  23915. SceneComponentConstants.STEP_EVALUATESUBMESH_BOUNDINGBOXRENDERER = 0;
  23916. SceneComponentConstants.STEP_ACTIVEMESH_BOUNDINGBOXRENDERER = 0;
  23917. SceneComponentConstants.STEP_CAMERADRAWRENDERTARGET_EFFECTLAYER = 1;
  23918. SceneComponentConstants.STEP_BEFORECAMERADRAW_EFFECTLAYER = 0;
  23919. SceneComponentConstants.STEP_BEFORECAMERADRAW_LAYER = 1;
  23920. SceneComponentConstants.STEP_BEFORERENDERINGMESH_OUTLINE = 0;
  23921. SceneComponentConstants.STEP_AFTERRENDERINGMESH_OUTLINE = 0;
  23922. SceneComponentConstants.STEP_AFTERRENDERINGGROUPDRAW_EFFECTLAYER_DRAW = 0;
  23923. SceneComponentConstants.STEP_AFTERRENDERINGGROUPDRAW_BOUNDINGBOXRENDERER = 1;
  23924. SceneComponentConstants.STEP_BEFORECAMERAUPDATE_SIMPLIFICATIONQUEUE = 0;
  23925. SceneComponentConstants.STEP_BEFORECAMERAUPDATE_GAMEPAD = 1;
  23926. SceneComponentConstants.STEP_BEFORECLEAR_PROCEDURALTEXTURE = 0;
  23927. SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER = 0;
  23928. SceneComponentConstants.STEP_AFTERCAMERADRAW_LENSFLARESYSTEM = 1;
  23929. SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER_DRAW = 2;
  23930. SceneComponentConstants.STEP_AFTERCAMERADRAW_LAYER = 3;
  23931. SceneComponentConstants.STEP_AFTERRENDER_AUDIO = 0;
  23932. SceneComponentConstants.STEP_GATHERRENDERTARGETS_SHADOWGENERATOR = 0;
  23933. SceneComponentConstants.STEP_GATHERRENDERTARGETS_GEOMETRYBUFFERRENDERER = 1;
  23934. SceneComponentConstants.STEP_GATHERRENDERTARGETS_DEPTHRENDERER = 2;
  23935. SceneComponentConstants.STEP_GATHERRENDERTARGETS_POSTPROCESSRENDERPIPELINEMANAGER = 3;
  23936. SceneComponentConstants.STEP_GATHERACTIVECAMERARENDERTARGETS_DEPTHRENDERER = 0;
  23937. SceneComponentConstants.STEP_POINTERMOVE_SPRITE = 0;
  23938. SceneComponentConstants.STEP_POINTERDOWN_SPRITE = 0;
  23939. SceneComponentConstants.STEP_POINTERUP_SPRITE = 0;
  23940. return SceneComponentConstants;
  23941. }());
  23942. BABYLON.SceneComponentConstants = SceneComponentConstants;
  23943. /**
  23944. * Repressentation of a stage in the scene (Basically a list of ordered steps)
  23945. * @hidden
  23946. */
  23947. var Stage = /** @class */ (function (_super) {
  23948. __extends(Stage, _super);
  23949. /**
  23950. * Hide ctor from the rest of the world.
  23951. * @param items The items to add.
  23952. */
  23953. function Stage(items) {
  23954. return _super.apply(this, items) || this;
  23955. }
  23956. /**
  23957. * Creates a new Stage.
  23958. * @returns A new instance of a Stage
  23959. */
  23960. Stage.Create = function () {
  23961. return Object.create(Stage.prototype);
  23962. };
  23963. /**
  23964. * Registers a step in an ordered way in the targeted stage.
  23965. * @param index Defines the position to register the step in
  23966. * @param component Defines the component attached to the step
  23967. * @param action Defines the action to launch during the step
  23968. */
  23969. Stage.prototype.registerStep = function (index, component, action) {
  23970. var i = 0;
  23971. var maxIndex = Number.MAX_VALUE;
  23972. for (; i < this.length && i < maxIndex; i++) {
  23973. var step = this[i];
  23974. maxIndex = step.index;
  23975. }
  23976. this.splice(i, 0, { index: index, component: component, action: action.bind(component) });
  23977. };
  23978. /**
  23979. * Clears all the steps from the stage.
  23980. */
  23981. Stage.prototype.clear = function () {
  23982. this.length = 0;
  23983. };
  23984. return Stage;
  23985. }(Array));
  23986. BABYLON.Stage = Stage;
  23987. })(BABYLON || (BABYLON = {}));
  23988. //# sourceMappingURL=babylon.sceneComponent.js.map
  23989. var BABYLON;
  23990. (function (BABYLON) {
  23991. /**
  23992. * Base class of the scene acting as a container for the different elements composing a scene.
  23993. * This class is dynamically extended by the different components of the scene increasing
  23994. * flexibility and reducing coupling
  23995. */
  23996. var AbstractScene = /** @class */ (function () {
  23997. function AbstractScene() {
  23998. /**
  23999. * Gets the list of root nodes (ie. nodes with no parent)
  24000. */
  24001. this.rootNodes = new Array();
  24002. /** All of the cameras added to this scene
  24003. * @see http://doc.babylonjs.com/babylon101/cameras
  24004. */
  24005. this.cameras = new Array();
  24006. /**
  24007. * All of the lights added to this scene
  24008. * @see http://doc.babylonjs.com/babylon101/lights
  24009. */
  24010. this.lights = new Array();
  24011. /**
  24012. * All of the (abstract) meshes added to this scene
  24013. */
  24014. this.meshes = new Array();
  24015. /**
  24016. * The list of skeletons added to the scene
  24017. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  24018. */
  24019. this.skeletons = new Array();
  24020. /**
  24021. * All of the particle systems added to this scene
  24022. * @see http://doc.babylonjs.com/babylon101/particles
  24023. */
  24024. this.particleSystems = new Array();
  24025. /**
  24026. * Gets a list of Animations associated with the scene
  24027. */
  24028. this.animations = [];
  24029. /**
  24030. * All of the animation groups added to this scene
  24031. * @see http://doc.babylonjs.com/how_to/group
  24032. */
  24033. this.animationGroups = new Array();
  24034. /**
  24035. * All of the multi-materials added to this scene
  24036. * @see http://doc.babylonjs.com/how_to/multi_materials
  24037. */
  24038. this.multiMaterials = new Array();
  24039. /**
  24040. * All of the materials added to this scene
  24041. * @see http://doc.babylonjs.com/babylon101/materials
  24042. */
  24043. this.materials = new Array();
  24044. /**
  24045. * The list of morph target managers added to the scene
  24046. * @see http://doc.babylonjs.com/how_to/how_to_dynamically_morph_a_mesh
  24047. */
  24048. this.morphTargetManagers = new Array();
  24049. /**
  24050. * The list of geometries used in the scene.
  24051. */
  24052. this.geometries = new Array();
  24053. /**
  24054. * All of the tranform nodes added to this scene
  24055. * @see http://doc.babylonjs.com/how_to/transformnode
  24056. */
  24057. this.transformNodes = new Array();
  24058. /**
  24059. * ActionManagers available on the scene.
  24060. */
  24061. this.actionManagers = new Array();
  24062. /**
  24063. * Textures to keep.
  24064. */
  24065. this.textures = new Array();
  24066. }
  24067. /**
  24068. * Adds a parser in the list of available ones
  24069. * @param name Defines the name of the parser
  24070. * @param parser Defines the parser to add
  24071. */
  24072. AbstractScene.AddParser = function (name, parser) {
  24073. this._BabylonFileParsers[name] = parser;
  24074. };
  24075. /**
  24076. * Gets a general parser from the list of avaialble ones
  24077. * @param name Defines the name of the parser
  24078. * @returns the requested parser or null
  24079. */
  24080. AbstractScene.GetParser = function (name) {
  24081. if (this._BabylonFileParsers[name]) {
  24082. return this._BabylonFileParsers[name];
  24083. }
  24084. return null;
  24085. };
  24086. /**
  24087. * Adds n individual parser in the list of available ones
  24088. * @param name Defines the name of the parser
  24089. * @param parser Defines the parser to add
  24090. */
  24091. AbstractScene.AddIndividualParser = function (name, parser) {
  24092. this._IndividualBabylonFileParsers[name] = parser;
  24093. };
  24094. /**
  24095. * Gets an individual parser from the list of avaialble ones
  24096. * @param name Defines the name of the parser
  24097. * @returns the requested parser or null
  24098. */
  24099. AbstractScene.GetIndividualParser = function (name) {
  24100. if (this._IndividualBabylonFileParsers[name]) {
  24101. return this._IndividualBabylonFileParsers[name];
  24102. }
  24103. return null;
  24104. };
  24105. /**
  24106. * Parser json data and populate both a scene and its associated container object
  24107. * @param jsonData Defines the data to parse
  24108. * @param scene Defines the scene to parse the data for
  24109. * @param container Defines the container attached to the parsing sequence
  24110. * @param rootUrl Defines the root url of the data
  24111. */
  24112. AbstractScene.Parse = function (jsonData, scene, container, rootUrl) {
  24113. for (var parserName in this._BabylonFileParsers) {
  24114. if (this._BabylonFileParsers.hasOwnProperty(parserName)) {
  24115. this._BabylonFileParsers[parserName](jsonData, scene, container, rootUrl);
  24116. }
  24117. }
  24118. };
  24119. /**
  24120. * Stores the list of available parsers in the application.
  24121. */
  24122. AbstractScene._BabylonFileParsers = {};
  24123. /**
  24124. * Stores the list of available individual parsers in the application.
  24125. */
  24126. AbstractScene._IndividualBabylonFileParsers = {};
  24127. return AbstractScene;
  24128. }());
  24129. BABYLON.AbstractScene = AbstractScene;
  24130. })(BABYLON || (BABYLON = {}));
  24131. //# sourceMappingURL=babylon.abstractScene.js.map
  24132. var BABYLON;
  24133. (function (BABYLON) {
  24134. /** @hidden */
  24135. var ClickInfo = /** @class */ (function () {
  24136. function ClickInfo() {
  24137. this._singleClick = false;
  24138. this._doubleClick = false;
  24139. this._hasSwiped = false;
  24140. this._ignore = false;
  24141. }
  24142. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  24143. get: function () {
  24144. return this._singleClick;
  24145. },
  24146. set: function (b) {
  24147. this._singleClick = b;
  24148. },
  24149. enumerable: true,
  24150. configurable: true
  24151. });
  24152. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  24153. get: function () {
  24154. return this._doubleClick;
  24155. },
  24156. set: function (b) {
  24157. this._doubleClick = b;
  24158. },
  24159. enumerable: true,
  24160. configurable: true
  24161. });
  24162. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  24163. get: function () {
  24164. return this._hasSwiped;
  24165. },
  24166. set: function (b) {
  24167. this._hasSwiped = b;
  24168. },
  24169. enumerable: true,
  24170. configurable: true
  24171. });
  24172. Object.defineProperty(ClickInfo.prototype, "ignore", {
  24173. get: function () {
  24174. return this._ignore;
  24175. },
  24176. set: function (b) {
  24177. this._ignore = b;
  24178. },
  24179. enumerable: true,
  24180. configurable: true
  24181. });
  24182. return ClickInfo;
  24183. }());
  24184. /**
  24185. * This class is used by the onRenderingGroupObservable
  24186. */
  24187. var RenderingGroupInfo = /** @class */ (function () {
  24188. function RenderingGroupInfo() {
  24189. }
  24190. return RenderingGroupInfo;
  24191. }());
  24192. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  24193. /**
  24194. * Represents a scene to be rendered by the engine.
  24195. * @see http://doc.babylonjs.com/features/scene
  24196. */
  24197. var Scene = /** @class */ (function (_super) {
  24198. __extends(Scene, _super);
  24199. /**
  24200. * Creates a new Scene
  24201. * @param engine defines the engine to use to render this scene
  24202. */
  24203. function Scene(engine) {
  24204. var _this = _super.call(this) || this;
  24205. // Members
  24206. /**
  24207. * Gets or sets a boolean that indicates if the scene must clear the render buffer before rendering a frame
  24208. */
  24209. _this.autoClear = true;
  24210. /**
  24211. * Gets or sets a boolean that indicates if the scene must clear the depth and stencil buffers before rendering a frame
  24212. */
  24213. _this.autoClearDepthAndStencil = true;
  24214. /**
  24215. * Defines the color used to clear the render buffer (Default is (0.2, 0.2, 0.3, 1.0))
  24216. */
  24217. _this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  24218. /**
  24219. * Defines the color used to simulate the ambient color (Default is (0, 0, 0))
  24220. */
  24221. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  24222. _this._forceWireframe = false;
  24223. _this._forcePointsCloud = false;
  24224. /**
  24225. * Gets or sets a boolean indicating if animations are enabled
  24226. */
  24227. _this.animationsEnabled = true;
  24228. _this._animationPropertiesOverride = null;
  24229. /**
  24230. * Gets or sets a boolean indicating if a constant deltatime has to be used
  24231. * This is mostly useful for testing purposes when you do not want the animations to scale with the framerate
  24232. */
  24233. _this.useConstantAnimationDeltaTime = false;
  24234. /**
  24235. * Gets or sets a boolean indicating if the scene must keep the meshUnderPointer property updated
  24236. * Please note that it requires to run a ray cast through the scene on every frame
  24237. */
  24238. _this.constantlyUpdateMeshUnderPointer = false;
  24239. /**
  24240. * Defines the HTML cursor to use when hovering over interactive elements
  24241. */
  24242. _this.hoverCursor = "pointer";
  24243. /**
  24244. * Defines the HTML default cursor to use (empty by default)
  24245. */
  24246. _this.defaultCursor = "";
  24247. /**
  24248. * This is used to call preventDefault() on pointer down
  24249. * in order to block unwanted artifacts like system double clicks
  24250. */
  24251. _this.preventDefaultOnPointerDown = true;
  24252. // Metadata
  24253. /**
  24254. * Gets or sets user defined metadata
  24255. */
  24256. _this.metadata = null;
  24257. /**
  24258. * Use this array to add regular expressions used to disable offline support for specific urls
  24259. */
  24260. _this.disableOfflineSupportExceptionRules = new Array();
  24261. /**
  24262. * An event triggered when the scene is disposed.
  24263. */
  24264. _this.onDisposeObservable = new BABYLON.Observable();
  24265. _this._onDisposeObserver = null;
  24266. /**
  24267. * An event triggered before rendering the scene (right after animations and physics)
  24268. */
  24269. _this.onBeforeRenderObservable = new BABYLON.Observable();
  24270. _this._onBeforeRenderObserver = null;
  24271. /**
  24272. * An event triggered after rendering the scene
  24273. */
  24274. _this.onAfterRenderObservable = new BABYLON.Observable();
  24275. _this._onAfterRenderObserver = null;
  24276. /**
  24277. * An event triggered before animating the scene
  24278. */
  24279. _this.onBeforeAnimationsObservable = new BABYLON.Observable();
  24280. /**
  24281. * An event triggered after animations processing
  24282. */
  24283. _this.onAfterAnimationsObservable = new BABYLON.Observable();
  24284. /**
  24285. * An event triggered before draw calls are ready to be sent
  24286. */
  24287. _this.onBeforeDrawPhaseObservable = new BABYLON.Observable();
  24288. /**
  24289. * An event triggered after draw calls have been sent
  24290. */
  24291. _this.onAfterDrawPhaseObservable = new BABYLON.Observable();
  24292. /**
  24293. * An event triggered when the scene is ready
  24294. */
  24295. _this.onReadyObservable = new BABYLON.Observable();
  24296. /**
  24297. * An event triggered before rendering a camera
  24298. */
  24299. _this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  24300. _this._onBeforeCameraRenderObserver = null;
  24301. /**
  24302. * An event triggered after rendering a camera
  24303. */
  24304. _this.onAfterCameraRenderObservable = new BABYLON.Observable();
  24305. _this._onAfterCameraRenderObserver = null;
  24306. /**
  24307. * An event triggered when active meshes evaluation is about to start
  24308. */
  24309. _this.onBeforeActiveMeshesEvaluationObservable = new BABYLON.Observable();
  24310. /**
  24311. * An event triggered when active meshes evaluation is done
  24312. */
  24313. _this.onAfterActiveMeshesEvaluationObservable = new BABYLON.Observable();
  24314. /**
  24315. * An event triggered when particles rendering is about to start
  24316. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  24317. */
  24318. _this.onBeforeParticlesRenderingObservable = new BABYLON.Observable();
  24319. /**
  24320. * An event triggered when particles rendering is done
  24321. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  24322. */
  24323. _this.onAfterParticlesRenderingObservable = new BABYLON.Observable();
  24324. /**
  24325. * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed
  24326. */
  24327. _this.onDataLoadedObservable = new BABYLON.Observable();
  24328. /**
  24329. * An event triggered when a camera is created
  24330. */
  24331. _this.onNewCameraAddedObservable = new BABYLON.Observable();
  24332. /**
  24333. * An event triggered when a camera is removed
  24334. */
  24335. _this.onCameraRemovedObservable = new BABYLON.Observable();
  24336. /**
  24337. * An event triggered when a light is created
  24338. */
  24339. _this.onNewLightAddedObservable = new BABYLON.Observable();
  24340. /**
  24341. * An event triggered when a light is removed
  24342. */
  24343. _this.onLightRemovedObservable = new BABYLON.Observable();
  24344. /**
  24345. * An event triggered when a geometry is created
  24346. */
  24347. _this.onNewGeometryAddedObservable = new BABYLON.Observable();
  24348. /**
  24349. * An event triggered when a geometry is removed
  24350. */
  24351. _this.onGeometryRemovedObservable = new BABYLON.Observable();
  24352. /**
  24353. * An event triggered when a transform node is created
  24354. */
  24355. _this.onNewTransformNodeAddedObservable = new BABYLON.Observable();
  24356. /**
  24357. * An event triggered when a transform node is removed
  24358. */
  24359. _this.onTransformNodeRemovedObservable = new BABYLON.Observable();
  24360. /**
  24361. * An event triggered when a mesh is created
  24362. */
  24363. _this.onNewMeshAddedObservable = new BABYLON.Observable();
  24364. /**
  24365. * An event triggered when a mesh is removed
  24366. */
  24367. _this.onMeshRemovedObservable = new BABYLON.Observable();
  24368. /**
  24369. * An event triggered when render targets are about to be rendered
  24370. * Can happen multiple times per frame.
  24371. */
  24372. _this.onBeforeRenderTargetsRenderObservable = new BABYLON.Observable();
  24373. /**
  24374. * An event triggered when render targets were rendered.
  24375. * Can happen multiple times per frame.
  24376. */
  24377. _this.onAfterRenderTargetsRenderObservable = new BABYLON.Observable();
  24378. /**
  24379. * An event triggered before calculating deterministic simulation step
  24380. */
  24381. _this.onBeforeStepObservable = new BABYLON.Observable();
  24382. /**
  24383. * An event triggered after calculating deterministic simulation step
  24384. */
  24385. _this.onAfterStepObservable = new BABYLON.Observable();
  24386. /**
  24387. * This Observable will be triggered before rendering each renderingGroup of each rendered camera.
  24388. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  24389. * 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)
  24390. */
  24391. _this.onBeforeRenderingGroupObservable = new BABYLON.Observable();
  24392. /**
  24393. * This Observable will be triggered after rendering each renderingGroup of each rendered camera.
  24394. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  24395. * 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)
  24396. */
  24397. _this.onAfterRenderingGroupObservable = new BABYLON.Observable();
  24398. /**
  24399. * This Observable will when a mesh has been imported into the scene.
  24400. */
  24401. _this.onMeshImportedObservable = new BABYLON.Observable();
  24402. // Animations
  24403. _this._registeredForLateAnimationBindings = new BABYLON.SmartArrayNoDuplicate(256);
  24404. /**
  24405. * 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).
  24406. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  24407. */
  24408. _this.onPrePointerObservable = new BABYLON.Observable();
  24409. /**
  24410. * Observable event triggered each time an input event is received from the rendering canvas
  24411. */
  24412. _this.onPointerObservable = new BABYLON.Observable();
  24413. _this._meshPickProceed = false;
  24414. _this._currentPickResult = null;
  24415. _this._previousPickResult = null;
  24416. _this._totalPointersPressed = 0;
  24417. _this._doubleClickOccured = false;
  24418. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  24419. _this.cameraToUseForPointers = null;
  24420. _this._pointerX = 0;
  24421. _this._pointerY = 0;
  24422. _this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  24423. _this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  24424. _this._startingPointerTime = 0;
  24425. _this._previousStartingPointerTime = 0;
  24426. _this._pointerCaptures = {};
  24427. // Deterministic lockstep
  24428. _this._timeAccumulator = 0;
  24429. _this._currentStepId = 0;
  24430. _this._currentInternalStep = 0;
  24431. // Keyboard
  24432. /**
  24433. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  24434. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  24435. */
  24436. _this.onPreKeyboardObservable = new BABYLON.Observable();
  24437. /**
  24438. * Observable event triggered each time an keyboard event is received from the hosting window
  24439. */
  24440. _this.onKeyboardObservable = new BABYLON.Observable();
  24441. // Coordinates system
  24442. _this._useRightHandedSystem = false;
  24443. // Fog
  24444. _this._fogEnabled = true;
  24445. _this._fogMode = Scene.FOGMODE_NONE;
  24446. /**
  24447. * Gets or sets the fog color to use
  24448. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24449. */
  24450. _this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  24451. /**
  24452. * Gets or sets the fog density to use
  24453. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24454. */
  24455. _this.fogDensity = 0.1;
  24456. /**
  24457. * Gets or sets the fog start distance to use
  24458. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24459. */
  24460. _this.fogStart = 0;
  24461. /**
  24462. * Gets or sets the fog end distance to use
  24463. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24464. */
  24465. _this.fogEnd = 1000.0;
  24466. // Lights
  24467. _this._shadowsEnabled = true;
  24468. _this._lightsEnabled = true;
  24469. /** All of the active cameras added to this scene. */
  24470. _this.activeCameras = new Array();
  24471. // Textures
  24472. _this._texturesEnabled = true;
  24473. // Particles
  24474. /**
  24475. * Gets or sets a boolean indicating if particles are enabled on this scene
  24476. */
  24477. _this.particlesEnabled = true;
  24478. // Sprites
  24479. /**
  24480. * Gets or sets a boolean indicating if sprites are enabled on this scene
  24481. */
  24482. _this.spritesEnabled = true;
  24483. // Skeletons
  24484. _this._skeletonsEnabled = true;
  24485. // Lens flares
  24486. /**
  24487. * Gets or sets a boolean indicating if lens flares are enabled on this scene
  24488. */
  24489. _this.lensFlaresEnabled = true;
  24490. // Collisions
  24491. /**
  24492. * Gets or sets a boolean indicating if collisions are enabled on this scene
  24493. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  24494. */
  24495. _this.collisionsEnabled = true;
  24496. /**
  24497. * Defines the gravity applied to this scene (used only for collisions)
  24498. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  24499. */
  24500. _this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  24501. // Postprocesses
  24502. /**
  24503. * Gets or sets a boolean indicating if postprocesses are enabled on this scene
  24504. */
  24505. _this.postProcessesEnabled = true;
  24506. /**
  24507. * The list of postprocesses added to the scene
  24508. */
  24509. _this.postProcesses = new Array();
  24510. // Customs render targets
  24511. /**
  24512. * Gets or sets a boolean indicating if render targets are enabled on this scene
  24513. */
  24514. _this.renderTargetsEnabled = true;
  24515. /**
  24516. * Gets or sets a boolean indicating if next render targets must be dumped as image for debugging purposes
  24517. * We recommend not using it and instead rely on Spector.js: http://spector.babylonjs.com
  24518. */
  24519. _this.dumpNextRenderTargets = false;
  24520. /**
  24521. * The list of user defined render targets added to the scene
  24522. */
  24523. _this.customRenderTargets = new Array();
  24524. /**
  24525. * Gets the list of meshes imported to the scene through SceneLoader
  24526. */
  24527. _this.importedMeshesFiles = new Array();
  24528. // Probes
  24529. /**
  24530. * Gets or sets a boolean indicating if probes are enabled on this scene
  24531. */
  24532. _this.probesEnabled = true;
  24533. _this._meshesForIntersections = new BABYLON.SmartArrayNoDuplicate(256);
  24534. // Procedural textures
  24535. /**
  24536. * Gets or sets a boolean indicating if procedural textures are enabled on this scene
  24537. */
  24538. _this.proceduralTexturesEnabled = true;
  24539. // Performance counters
  24540. _this._totalVertices = new BABYLON.PerfCounter();
  24541. /** @hidden */
  24542. _this._activeIndices = new BABYLON.PerfCounter();
  24543. /** @hidden */
  24544. _this._activeParticles = new BABYLON.PerfCounter();
  24545. /** @hidden */
  24546. _this._activeBones = new BABYLON.PerfCounter();
  24547. _this._animationTime = 0;
  24548. /**
  24549. * Gets or sets a general scale for animation speed
  24550. * @see https://www.babylonjs-playground.com/#IBU2W7#3
  24551. */
  24552. _this.animationTimeScale = 1;
  24553. _this._renderId = 0;
  24554. _this._frameId = 0;
  24555. _this._executeWhenReadyTimeoutId = -1;
  24556. _this._intermediateRendering = false;
  24557. _this._viewUpdateFlag = -1;
  24558. _this._projectionUpdateFlag = -1;
  24559. _this._alternateViewUpdateFlag = -1;
  24560. _this._alternateProjectionUpdateFlag = -1;
  24561. /** @hidden */
  24562. _this._toBeDisposed = new Array(256);
  24563. _this._activeRequests = new Array();
  24564. _this._pendingData = new Array();
  24565. _this._isDisposed = false;
  24566. /**
  24567. * Gets or sets a boolean indicating that all submeshes of active meshes must be rendered
  24568. * Use this boolean to avoid computing frustum clipping on submeshes (This could help when you are CPU bound)
  24569. */
  24570. _this.dispatchAllSubMeshesOfActiveMeshes = false;
  24571. _this._activeMeshes = new BABYLON.SmartArray(256);
  24572. _this._processedMaterials = new BABYLON.SmartArray(256);
  24573. _this._renderTargets = new BABYLON.SmartArrayNoDuplicate(256);
  24574. /** @hidden */
  24575. _this._activeParticleSystems = new BABYLON.SmartArray(256);
  24576. _this._activeSkeletons = new BABYLON.SmartArrayNoDuplicate(32);
  24577. _this._softwareSkinnedMeshes = new BABYLON.SmartArrayNoDuplicate(32);
  24578. /** @hidden */
  24579. _this._activeAnimatables = new Array();
  24580. _this._transformMatrix = BABYLON.Matrix.Zero();
  24581. _this._useAlternateCameraConfiguration = false;
  24582. _this._alternateRendering = false;
  24583. /**
  24584. * Gets or sets a boolean indicating if lights must be sorted by priority (off by default)
  24585. * This is useful if there are more lights that the maximum simulteanous authorized
  24586. */
  24587. _this.requireLightSorting = false;
  24588. /**
  24589. * @hidden
  24590. * Backing store of defined scene components.
  24591. */
  24592. _this._components = [];
  24593. /**
  24594. * @hidden
  24595. * Backing store of defined scene components.
  24596. */
  24597. _this._serializableComponents = [];
  24598. /**
  24599. * List of components to register on the next registration step.
  24600. */
  24601. _this._transientComponents = [];
  24602. /**
  24603. * @hidden
  24604. * Defines the actions happening before camera updates.
  24605. */
  24606. _this._beforeCameraUpdateStage = BABYLON.Stage.Create();
  24607. /**
  24608. * @hidden
  24609. * Defines the actions happening before clear the canvas.
  24610. */
  24611. _this._beforeClearStage = BABYLON.Stage.Create();
  24612. /**
  24613. * @hidden
  24614. * Defines the actions when collecting render targets for the frame.
  24615. */
  24616. _this._gatherRenderTargetsStage = BABYLON.Stage.Create();
  24617. /**
  24618. * @hidden
  24619. * Defines the actions happening for one camera in the frame.
  24620. */
  24621. _this._gatherActiveCameraRenderTargetsStage = BABYLON.Stage.Create();
  24622. /**
  24623. * @hidden
  24624. * Defines the actions happening during the per mesh ready checks.
  24625. */
  24626. _this._isReadyForMeshStage = BABYLON.Stage.Create();
  24627. /**
  24628. * @hidden
  24629. * Defines the actions happening before evaluate active mesh checks.
  24630. */
  24631. _this._beforeEvaluateActiveMeshStage = BABYLON.Stage.Create();
  24632. /**
  24633. * @hidden
  24634. * Defines the actions happening during the evaluate sub mesh checks.
  24635. */
  24636. _this._evaluateSubMeshStage = BABYLON.Stage.Create();
  24637. /**
  24638. * @hidden
  24639. * Defines the actions happening during the active mesh stage.
  24640. */
  24641. _this._activeMeshStage = BABYLON.Stage.Create();
  24642. /**
  24643. * @hidden
  24644. * Defines the actions happening during the per camera render target step.
  24645. */
  24646. _this._cameraDrawRenderTargetStage = BABYLON.Stage.Create();
  24647. /**
  24648. * @hidden
  24649. * Defines the actions happening just before the active camera is drawing.
  24650. */
  24651. _this._beforeCameraDrawStage = BABYLON.Stage.Create();
  24652. /**
  24653. * @hidden
  24654. * Defines the actions happening just before a rendering group is drawing.
  24655. */
  24656. _this._beforeRenderingGroupDrawStage = BABYLON.Stage.Create();
  24657. /**
  24658. * @hidden
  24659. * Defines the actions happening just before a mesh is drawing.
  24660. */
  24661. _this._beforeRenderingMeshStage = BABYLON.Stage.Create();
  24662. /**
  24663. * @hidden
  24664. * Defines the actions happening just after a mesh has been drawn.
  24665. */
  24666. _this._afterRenderingMeshStage = BABYLON.Stage.Create();
  24667. /**
  24668. * @hidden
  24669. * Defines the actions happening just after a rendering group has been drawn.
  24670. */
  24671. _this._afterRenderingGroupDrawStage = BABYLON.Stage.Create();
  24672. /**
  24673. * @hidden
  24674. * Defines the actions happening just after the active camera has been drawn.
  24675. */
  24676. _this._afterCameraDrawStage = BABYLON.Stage.Create();
  24677. /**
  24678. * @hidden
  24679. * Defines the actions happening just after rendering all cameras and computing intersections.
  24680. */
  24681. _this._afterRenderStage = BABYLON.Stage.Create();
  24682. /**
  24683. * @hidden
  24684. * Defines the actions happening when a pointer move event happens.
  24685. */
  24686. _this._pointerMoveStage = BABYLON.Stage.Create();
  24687. /**
  24688. * @hidden
  24689. * Defines the actions happening when a pointer down event happens.
  24690. */
  24691. _this._pointerDownStage = BABYLON.Stage.Create();
  24692. /**
  24693. * @hidden
  24694. * Defines the actions happening when a pointer up event happens.
  24695. */
  24696. _this._pointerUpStage = BABYLON.Stage.Create();
  24697. _this._defaultMeshCandidates = {
  24698. data: [],
  24699. length: 0
  24700. };
  24701. _this._defaultSubMeshCandidates = {
  24702. data: [],
  24703. length: 0
  24704. };
  24705. _this._activeMeshesFrozen = false;
  24706. /** @hidden */
  24707. _this._allowPostProcessClearColor = true;
  24708. /**
  24709. * User updatable function that will return a deterministic frame time when engine is in deterministic lock step mode
  24710. */
  24711. _this.getDeterministicFrameTime = function () {
  24712. return 1000.0 / 60.0; // frame time in ms
  24713. };
  24714. _this._tempPickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  24715. _this._blockMaterialDirtyMechanism = false;
  24716. _this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  24717. _this._engine.scenes.push(_this);
  24718. _this._uid = null;
  24719. _this._renderingManager = new BABYLON.RenderingManager(_this);
  24720. if (BABYLON.PostProcessManager) {
  24721. _this.postProcessManager = new BABYLON.PostProcessManager(_this);
  24722. }
  24723. if (BABYLON.Tools.IsWindowObjectExist()) {
  24724. _this.attachControl();
  24725. }
  24726. //collision coordinator initialization. For now legacy per default.
  24727. _this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  24728. // Uniform Buffer
  24729. _this._createUbo();
  24730. // Default Image processing definition
  24731. if (BABYLON.ImageProcessingConfiguration) {
  24732. _this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  24733. }
  24734. _this.setDefaultCandidateProviders();
  24735. return _this;
  24736. }
  24737. Object.defineProperty(Scene.prototype, "environmentTexture", {
  24738. /**
  24739. * Texture used in all pbr material as the reflection texture.
  24740. * As in the majority of the scene they are the same (exception for multi room and so on),
  24741. * this is easier to reference from here than from all the materials.
  24742. */
  24743. get: function () {
  24744. return this._environmentTexture;
  24745. },
  24746. /**
  24747. * Texture used in all pbr material as the reflection texture.
  24748. * As in the majority of the scene they are the same (exception for multi room and so on),
  24749. * this is easier to set here than in all the materials.
  24750. */
  24751. set: function (value) {
  24752. if (this._environmentTexture === value) {
  24753. return;
  24754. }
  24755. this._environmentTexture = value;
  24756. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  24757. },
  24758. enumerable: true,
  24759. configurable: true
  24760. });
  24761. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  24762. /**
  24763. * Default image processing configuration used either in the rendering
  24764. * Forward main pass or through the imageProcessingPostProcess if present.
  24765. * As in the majority of the scene they are the same (exception for multi camera),
  24766. * this is easier to reference from here than from all the materials and post process.
  24767. *
  24768. * No setter as we it is a shared configuration, you can set the values instead.
  24769. */
  24770. get: function () {
  24771. return this._imageProcessingConfiguration;
  24772. },
  24773. enumerable: true,
  24774. configurable: true
  24775. });
  24776. Object.defineProperty(Scene.prototype, "forceWireframe", {
  24777. get: function () {
  24778. return this._forceWireframe;
  24779. },
  24780. /**
  24781. * Gets or sets a boolean indicating if all rendering must be done in wireframe
  24782. */
  24783. set: function (value) {
  24784. if (this._forceWireframe === value) {
  24785. return;
  24786. }
  24787. this._forceWireframe = value;
  24788. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24789. },
  24790. enumerable: true,
  24791. configurable: true
  24792. });
  24793. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  24794. get: function () {
  24795. return this._forcePointsCloud;
  24796. },
  24797. /**
  24798. * Gets or sets a boolean indicating if all rendering must be done in point cloud
  24799. */
  24800. set: function (value) {
  24801. if (this._forcePointsCloud === value) {
  24802. return;
  24803. }
  24804. this._forcePointsCloud = value;
  24805. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24806. },
  24807. enumerable: true,
  24808. configurable: true
  24809. });
  24810. Object.defineProperty(Scene.prototype, "animationPropertiesOverride", {
  24811. /**
  24812. * Gets or sets the animation properties override
  24813. */
  24814. get: function () {
  24815. return this._animationPropertiesOverride;
  24816. },
  24817. set: function (value) {
  24818. this._animationPropertiesOverride = value;
  24819. },
  24820. enumerable: true,
  24821. configurable: true
  24822. });
  24823. Object.defineProperty(Scene.prototype, "onDispose", {
  24824. /** Sets a function to be executed when this scene is disposed. */
  24825. set: function (callback) {
  24826. if (this._onDisposeObserver) {
  24827. this.onDisposeObservable.remove(this._onDisposeObserver);
  24828. }
  24829. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  24830. },
  24831. enumerable: true,
  24832. configurable: true
  24833. });
  24834. Object.defineProperty(Scene.prototype, "beforeRender", {
  24835. /** Sets a function to be executed before rendering this scene */
  24836. set: function (callback) {
  24837. if (this._onBeforeRenderObserver) {
  24838. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  24839. }
  24840. if (callback) {
  24841. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  24842. }
  24843. },
  24844. enumerable: true,
  24845. configurable: true
  24846. });
  24847. Object.defineProperty(Scene.prototype, "afterRender", {
  24848. /** Sets a function to be executed after rendering this scene */
  24849. set: function (callback) {
  24850. if (this._onAfterRenderObserver) {
  24851. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  24852. }
  24853. if (callback) {
  24854. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  24855. }
  24856. },
  24857. enumerable: true,
  24858. configurable: true
  24859. });
  24860. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  24861. /** Sets a function to be executed before rendering a camera*/
  24862. set: function (callback) {
  24863. if (this._onBeforeCameraRenderObserver) {
  24864. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  24865. }
  24866. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  24867. },
  24868. enumerable: true,
  24869. configurable: true
  24870. });
  24871. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  24872. /** Sets a function to be executed after rendering a camera*/
  24873. set: function (callback) {
  24874. if (this._onAfterCameraRenderObserver) {
  24875. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  24876. }
  24877. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  24878. },
  24879. enumerable: true,
  24880. configurable: true
  24881. });
  24882. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  24883. /**
  24884. * Gets the pointer coordinates without any translation (ie. straight out of the pointer event)
  24885. */
  24886. get: function () {
  24887. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  24888. },
  24889. enumerable: true,
  24890. configurable: true
  24891. });
  24892. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  24893. get: function () {
  24894. return this._useRightHandedSystem;
  24895. },
  24896. /**
  24897. * Gets or sets a boolean indicating if the scene must use right-handed coordinates system
  24898. */
  24899. set: function (value) {
  24900. if (this._useRightHandedSystem === value) {
  24901. return;
  24902. }
  24903. this._useRightHandedSystem = value;
  24904. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24905. },
  24906. enumerable: true,
  24907. configurable: true
  24908. });
  24909. /**
  24910. * Sets the step Id used by deterministic lock step
  24911. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24912. * @param newStepId defines the step Id
  24913. */
  24914. Scene.prototype.setStepId = function (newStepId) {
  24915. this._currentStepId = newStepId;
  24916. };
  24917. ;
  24918. /**
  24919. * Gets the step Id used by deterministic lock step
  24920. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24921. * @returns the step Id
  24922. */
  24923. Scene.prototype.getStepId = function () {
  24924. return this._currentStepId;
  24925. };
  24926. ;
  24927. /**
  24928. * Gets the internal step used by deterministic lock step
  24929. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24930. * @returns the internal step
  24931. */
  24932. Scene.prototype.getInternalStep = function () {
  24933. return this._currentInternalStep;
  24934. };
  24935. ;
  24936. Object.defineProperty(Scene.prototype, "fogEnabled", {
  24937. get: function () {
  24938. return this._fogEnabled;
  24939. },
  24940. /**
  24941. * Gets or sets a boolean indicating if fog is enabled on this scene
  24942. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24943. */
  24944. set: function (value) {
  24945. if (this._fogEnabled === value) {
  24946. return;
  24947. }
  24948. this._fogEnabled = value;
  24949. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24950. },
  24951. enumerable: true,
  24952. configurable: true
  24953. });
  24954. Object.defineProperty(Scene.prototype, "fogMode", {
  24955. get: function () {
  24956. return this._fogMode;
  24957. },
  24958. /**
  24959. * Gets or sets the fog mode to use
  24960. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24961. */
  24962. set: function (value) {
  24963. if (this._fogMode === value) {
  24964. return;
  24965. }
  24966. this._fogMode = value;
  24967. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24968. },
  24969. enumerable: true,
  24970. configurable: true
  24971. });
  24972. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  24973. get: function () {
  24974. return this._shadowsEnabled;
  24975. },
  24976. /**
  24977. * Gets or sets a boolean indicating if shadows are enabled on this scene
  24978. */
  24979. set: function (value) {
  24980. if (this._shadowsEnabled === value) {
  24981. return;
  24982. }
  24983. this._shadowsEnabled = value;
  24984. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  24985. },
  24986. enumerable: true,
  24987. configurable: true
  24988. });
  24989. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  24990. get: function () {
  24991. return this._lightsEnabled;
  24992. },
  24993. /**
  24994. * Gets or sets a boolean indicating if lights are enabled on this scene
  24995. */
  24996. set: function (value) {
  24997. if (this._lightsEnabled === value) {
  24998. return;
  24999. }
  25000. this._lightsEnabled = value;
  25001. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  25002. },
  25003. enumerable: true,
  25004. configurable: true
  25005. });
  25006. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  25007. /** The default material used on meshes when no material is affected */
  25008. get: function () {
  25009. if (!this._defaultMaterial) {
  25010. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  25011. }
  25012. return this._defaultMaterial;
  25013. },
  25014. /** The default material used on meshes when no material is affected */
  25015. set: function (value) {
  25016. this._defaultMaterial = value;
  25017. },
  25018. enumerable: true,
  25019. configurable: true
  25020. });
  25021. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  25022. get: function () {
  25023. return this._texturesEnabled;
  25024. },
  25025. /**
  25026. * Gets or sets a boolean indicating if textures are enabled on this scene
  25027. */
  25028. set: function (value) {
  25029. if (this._texturesEnabled === value) {
  25030. return;
  25031. }
  25032. this._texturesEnabled = value;
  25033. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  25034. },
  25035. enumerable: true,
  25036. configurable: true
  25037. });
  25038. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  25039. get: function () {
  25040. return this._skeletonsEnabled;
  25041. },
  25042. /**
  25043. * Gets or sets a boolean indicating if skeletons are enabled on this scene
  25044. */
  25045. set: function (value) {
  25046. if (this._skeletonsEnabled === value) {
  25047. return;
  25048. }
  25049. this._skeletonsEnabled = value;
  25050. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  25051. },
  25052. enumerable: true,
  25053. configurable: true
  25054. });
  25055. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  25056. /** @hidden */
  25057. get: function () {
  25058. return this._alternateRendering;
  25059. },
  25060. enumerable: true,
  25061. configurable: true
  25062. });
  25063. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  25064. /**
  25065. * Gets the list of frustum planes (built from the active camera)
  25066. */
  25067. get: function () {
  25068. return this._frustumPlanes;
  25069. },
  25070. enumerable: true,
  25071. configurable: true
  25072. });
  25073. /**
  25074. * Registers the transient components if needed.
  25075. */
  25076. Scene.prototype._registerTransientComponents = function () {
  25077. // Register components that have been associated lately to the scene.
  25078. if (this._transientComponents.length > 0) {
  25079. for (var _i = 0, _a = this._transientComponents; _i < _a.length; _i++) {
  25080. var component = _a[_i];
  25081. component.register();
  25082. }
  25083. this._transientComponents = [];
  25084. }
  25085. };
  25086. /**
  25087. * @hidden
  25088. * Add a component to the scene.
  25089. * Note that the ccomponent could be registered on th next frame if this is called after
  25090. * the register component stage.
  25091. * @param component Defines the component to add to the scene
  25092. */
  25093. Scene.prototype._addComponent = function (component) {
  25094. this._components.push(component);
  25095. this._transientComponents.push(component);
  25096. var serializableComponent = component;
  25097. if (serializableComponent.addFromContainer) {
  25098. this._serializableComponents.push(serializableComponent);
  25099. }
  25100. };
  25101. /**
  25102. * @hidden
  25103. * Gets a component from the scene.
  25104. * @param name defines the name of the component to retrieve
  25105. * @returns the component or null if not present
  25106. */
  25107. Scene.prototype._getComponent = function (name) {
  25108. for (var _i = 0, _a = this._components; _i < _a.length; _i++) {
  25109. var component = _a[_i];
  25110. if (component.name === name) {
  25111. return component;
  25112. }
  25113. }
  25114. return null;
  25115. };
  25116. /**
  25117. * @hidden
  25118. */
  25119. Scene.prototype._getDefaultMeshCandidates = function () {
  25120. this._defaultMeshCandidates.data = this.meshes;
  25121. this._defaultMeshCandidates.length = this.meshes.length;
  25122. return this._defaultMeshCandidates;
  25123. };
  25124. /**
  25125. * @hidden
  25126. */
  25127. Scene.prototype._getDefaultSubMeshCandidates = function (mesh) {
  25128. this._defaultSubMeshCandidates.data = mesh.subMeshes;
  25129. this._defaultSubMeshCandidates.length = mesh.subMeshes.length;
  25130. return this._defaultSubMeshCandidates;
  25131. };
  25132. /**
  25133. * Sets the default candidate providers for the scene.
  25134. * This sets the getActiveMeshCandidates, getActiveSubMeshCandidates, getIntersectingSubMeshCandidates
  25135. * and getCollidingSubMeshCandidates to their default function
  25136. */
  25137. Scene.prototype.setDefaultCandidateProviders = function () {
  25138. this.getActiveMeshCandidates = this._getDefaultMeshCandidates.bind(this);
  25139. this.getActiveSubMeshCandidates = this._getDefaultSubMeshCandidates.bind(this);
  25140. this.getIntersectingSubMeshCandidates = this._getDefaultSubMeshCandidates.bind(this);
  25141. this.getCollidingSubMeshCandidates = this._getDefaultSubMeshCandidates.bind(this);
  25142. };
  25143. Object.defineProperty(Scene.prototype, "workerCollisions", {
  25144. /**
  25145. * Gets a boolean indicating if collisions are processed on a web worker
  25146. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#web-worker-based-collision-system-since-21
  25147. */
  25148. get: function () {
  25149. return this._workerCollisions;
  25150. },
  25151. set: function (enabled) {
  25152. if (!BABYLON.CollisionCoordinatorLegacy) {
  25153. return;
  25154. }
  25155. enabled = (enabled && !!Worker && !!BABYLON.CollisionWorker);
  25156. this._workerCollisions = enabled;
  25157. if (this.collisionCoordinator) {
  25158. this.collisionCoordinator.destroy();
  25159. }
  25160. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  25161. this.collisionCoordinator.init(this);
  25162. },
  25163. enumerable: true,
  25164. configurable: true
  25165. });
  25166. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  25167. /**
  25168. * Gets the mesh that is currently under the pointer
  25169. */
  25170. get: function () {
  25171. return this._pointerOverMesh;
  25172. },
  25173. enumerable: true,
  25174. configurable: true
  25175. });
  25176. Object.defineProperty(Scene.prototype, "pointerX", {
  25177. /**
  25178. * Gets the current on-screen X position of the pointer
  25179. */
  25180. get: function () {
  25181. return this._pointerX;
  25182. },
  25183. enumerable: true,
  25184. configurable: true
  25185. });
  25186. Object.defineProperty(Scene.prototype, "pointerY", {
  25187. /**
  25188. * Gets the current on-screen Y position of the pointer
  25189. */
  25190. get: function () {
  25191. return this._pointerY;
  25192. },
  25193. enumerable: true,
  25194. configurable: true
  25195. });
  25196. /**
  25197. * Gets the cached material (ie. the latest rendered one)
  25198. * @returns the cached material
  25199. */
  25200. Scene.prototype.getCachedMaterial = function () {
  25201. return this._cachedMaterial;
  25202. };
  25203. /**
  25204. * Gets the cached effect (ie. the latest rendered one)
  25205. * @returns the cached effect
  25206. */
  25207. Scene.prototype.getCachedEffect = function () {
  25208. return this._cachedEffect;
  25209. };
  25210. /**
  25211. * Gets the cached visibility state (ie. the latest rendered one)
  25212. * @returns the cached visibility state
  25213. */
  25214. Scene.prototype.getCachedVisibility = function () {
  25215. return this._cachedVisibility;
  25216. };
  25217. /**
  25218. * Gets a boolean indicating if the current material / effect / visibility must be bind again
  25219. * @param material defines the current material
  25220. * @param effect defines the current effect
  25221. * @param visibility defines the current visibility state
  25222. * @returns true if one parameter is not cached
  25223. */
  25224. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  25225. if (visibility === void 0) { visibility = 1; }
  25226. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  25227. };
  25228. /**
  25229. * Gets the engine associated with the scene
  25230. * @returns an Engine
  25231. */
  25232. Scene.prototype.getEngine = function () {
  25233. return this._engine;
  25234. };
  25235. /**
  25236. * Gets the total number of vertices rendered per frame
  25237. * @returns the total number of vertices rendered per frame
  25238. */
  25239. Scene.prototype.getTotalVertices = function () {
  25240. return this._totalVertices.current;
  25241. };
  25242. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  25243. /**
  25244. * Gets the performance counter for total vertices
  25245. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  25246. */
  25247. get: function () {
  25248. return this._totalVertices;
  25249. },
  25250. enumerable: true,
  25251. configurable: true
  25252. });
  25253. /**
  25254. * Gets the total number of active indices rendered per frame (You can deduce the number of rendered triangles by dividing this number by 3)
  25255. * @returns the total number of active indices rendered per frame
  25256. */
  25257. Scene.prototype.getActiveIndices = function () {
  25258. return this._activeIndices.current;
  25259. };
  25260. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  25261. /**
  25262. * Gets the performance counter for active indices
  25263. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  25264. */
  25265. get: function () {
  25266. return this._activeIndices;
  25267. },
  25268. enumerable: true,
  25269. configurable: true
  25270. });
  25271. /**
  25272. * Gets the total number of active particles rendered per frame
  25273. * @returns the total number of active particles rendered per frame
  25274. */
  25275. Scene.prototype.getActiveParticles = function () {
  25276. return this._activeParticles.current;
  25277. };
  25278. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  25279. /**
  25280. * Gets the performance counter for active particles
  25281. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  25282. */
  25283. get: function () {
  25284. return this._activeParticles;
  25285. },
  25286. enumerable: true,
  25287. configurable: true
  25288. });
  25289. /**
  25290. * Gets the total number of active bones rendered per frame
  25291. * @returns the total number of active bones rendered per frame
  25292. */
  25293. Scene.prototype.getActiveBones = function () {
  25294. return this._activeBones.current;
  25295. };
  25296. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  25297. /**
  25298. * Gets the performance counter for active bones
  25299. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  25300. */
  25301. get: function () {
  25302. return this._activeBones;
  25303. },
  25304. enumerable: true,
  25305. configurable: true
  25306. });
  25307. /** @hidden */
  25308. Scene.prototype.getInterFramePerfCounter = function () {
  25309. BABYLON.Tools.Warn("getInterFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  25310. return 0;
  25311. };
  25312. Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
  25313. /** @hidden */
  25314. get: function () {
  25315. BABYLON.Tools.Warn("interFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  25316. return null;
  25317. },
  25318. enumerable: true,
  25319. configurable: true
  25320. });
  25321. /** @hidden */
  25322. Scene.prototype.getLastFrameDuration = function () {
  25323. BABYLON.Tools.Warn("getLastFrameDuration is deprecated. Please use SceneInstrumentation class");
  25324. return 0;
  25325. };
  25326. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  25327. /** @hidden */
  25328. get: function () {
  25329. BABYLON.Tools.Warn("lastFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  25330. return null;
  25331. },
  25332. enumerable: true,
  25333. configurable: true
  25334. });
  25335. /** @hidden */
  25336. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  25337. BABYLON.Tools.Warn("getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class");
  25338. return 0;
  25339. };
  25340. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  25341. /** @hidden */
  25342. get: function () {
  25343. BABYLON.Tools.Warn("evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  25344. return null;
  25345. },
  25346. enumerable: true,
  25347. configurable: true
  25348. });
  25349. /**
  25350. * Gets the array of active meshes
  25351. * @returns an array of AbstractMesh
  25352. */
  25353. Scene.prototype.getActiveMeshes = function () {
  25354. return this._activeMeshes;
  25355. };
  25356. /** @hidden */
  25357. Scene.prototype.getRenderTargetsDuration = function () {
  25358. BABYLON.Tools.Warn("getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class");
  25359. return 0;
  25360. };
  25361. /** @hidden */
  25362. Scene.prototype.getRenderDuration = function () {
  25363. BABYLON.Tools.Warn("getRenderDuration is deprecated. Please use SceneInstrumentation class");
  25364. return 0;
  25365. };
  25366. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  25367. /** @hidden */
  25368. get: function () {
  25369. BABYLON.Tools.Warn("renderDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  25370. return null;
  25371. },
  25372. enumerable: true,
  25373. configurable: true
  25374. });
  25375. /** @hidden */
  25376. Scene.prototype.getParticlesDuration = function () {
  25377. BABYLON.Tools.Warn("getParticlesDuration is deprecated. Please use SceneInstrumentation class");
  25378. return 0;
  25379. };
  25380. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  25381. /** @hidden */
  25382. get: function () {
  25383. BABYLON.Tools.Warn("particlesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  25384. return null;
  25385. },
  25386. enumerable: true,
  25387. configurable: true
  25388. });
  25389. /** @hidden */
  25390. Scene.prototype.getSpritesDuration = function () {
  25391. BABYLON.Tools.Warn("getSpritesDuration is deprecated. Please use SceneInstrumentation class");
  25392. return 0;
  25393. };
  25394. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  25395. /** @hidden */
  25396. get: function () {
  25397. BABYLON.Tools.Warn("spriteDuractionPerfCounter is deprecated. Please use SceneInstrumentation class");
  25398. return null;
  25399. },
  25400. enumerable: true,
  25401. configurable: true
  25402. });
  25403. /**
  25404. * Gets the animation ratio (which is 1.0 is the scene renders at 60fps and 2 if the scene renders at 30fps, etc.)
  25405. * @returns a number
  25406. */
  25407. Scene.prototype.getAnimationRatio = function () {
  25408. return this._animationRatio !== undefined ? this._animationRatio : 1;
  25409. };
  25410. /**
  25411. * Gets an unique Id for the current render phase
  25412. * @returns a number
  25413. */
  25414. Scene.prototype.getRenderId = function () {
  25415. return this._renderId;
  25416. };
  25417. /**
  25418. * Gets an unique Id for the current frame
  25419. * @returns a number
  25420. */
  25421. Scene.prototype.getFrameId = function () {
  25422. return this._frameId;
  25423. };
  25424. /** Call this function if you want to manually increment the render Id*/
  25425. Scene.prototype.incrementRenderId = function () {
  25426. this._renderId++;
  25427. };
  25428. Scene.prototype._updatePointerPosition = function (evt) {
  25429. var canvasRect = this._engine.getRenderingCanvasClientRect();
  25430. if (!canvasRect) {
  25431. return;
  25432. }
  25433. this._pointerX = evt.clientX - canvasRect.left;
  25434. this._pointerY = evt.clientY - canvasRect.top;
  25435. this._unTranslatedPointerX = this._pointerX;
  25436. this._unTranslatedPointerY = this._pointerY;
  25437. };
  25438. Scene.prototype._createUbo = function () {
  25439. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  25440. this._sceneUbo.addUniform("viewProjection", 16);
  25441. this._sceneUbo.addUniform("view", 16);
  25442. };
  25443. Scene.prototype._createAlternateUbo = function () {
  25444. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  25445. this._alternateSceneUbo.addUniform("viewProjection", 16);
  25446. this._alternateSceneUbo.addUniform("view", 16);
  25447. };
  25448. // Pointers handling
  25449. Scene.prototype._setRayOnPointerInfo = function (pointerInfo) {
  25450. if (pointerInfo.pickInfo) {
  25451. if (!pointerInfo.pickInfo.ray) {
  25452. pointerInfo.pickInfo.ray = this.createPickingRay(pointerInfo.event.offsetX, pointerInfo.event.offsetY, BABYLON.Matrix.Identity(), this.activeCamera);
  25453. }
  25454. }
  25455. };
  25456. /**
  25457. * Use this method to simulate a pointer move on a mesh
  25458. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  25459. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  25460. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  25461. * @returns the current scene
  25462. */
  25463. Scene.prototype.simulatePointerMove = function (pickResult, pointerEventInit) {
  25464. var evt = new PointerEvent("pointermove", pointerEventInit);
  25465. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERMOVE)) {
  25466. return this;
  25467. }
  25468. return this._processPointerMove(pickResult, evt);
  25469. };
  25470. Scene.prototype._processPointerMove = function (pickResult, evt) {
  25471. var canvas = this._engine.getRenderingCanvas();
  25472. if (!canvas) {
  25473. return this;
  25474. }
  25475. // Restore pointer
  25476. canvas.style.cursor = this.defaultCursor;
  25477. var isMeshPicked = (pickResult && pickResult.hit && pickResult.pickedMesh) ? true : false;
  25478. if (isMeshPicked) {
  25479. this.setPointerOverMesh(pickResult.pickedMesh);
  25480. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  25481. if (this._pointerOverMesh.actionManager.hoverCursor) {
  25482. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  25483. }
  25484. else {
  25485. canvas.style.cursor = this.hoverCursor;
  25486. }
  25487. }
  25488. }
  25489. else {
  25490. this.setPointerOverMesh(null);
  25491. }
  25492. for (var _i = 0, _a = this._pointerMoveStage; _i < _a.length; _i++) {
  25493. var step = _a[_i];
  25494. pickResult = step.action(this._unTranslatedPointerX, this._unTranslatedPointerY, pickResult, isMeshPicked, canvas);
  25495. }
  25496. if (pickResult) {
  25497. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  25498. if (this.onPointerMove) {
  25499. this.onPointerMove(evt, pickResult, type);
  25500. }
  25501. if (this.onPointerObservable.hasObservers()) {
  25502. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  25503. this._setRayOnPointerInfo(pi);
  25504. this.onPointerObservable.notifyObservers(pi, type);
  25505. }
  25506. }
  25507. return this;
  25508. };
  25509. Scene.prototype._checkPrePointerObservable = function (pickResult, evt, type) {
  25510. var pi = new BABYLON.PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  25511. if (pickResult) {
  25512. pi.ray = pickResult.ray;
  25513. }
  25514. this.onPrePointerObservable.notifyObservers(pi, type);
  25515. if (pi.skipOnPointerObservable) {
  25516. return true;
  25517. }
  25518. else {
  25519. return false;
  25520. }
  25521. };
  25522. /**
  25523. * Use this method to simulate a pointer down on a mesh
  25524. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  25525. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  25526. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  25527. * @returns the current scene
  25528. */
  25529. Scene.prototype.simulatePointerDown = function (pickResult, pointerEventInit) {
  25530. var evt = new PointerEvent("pointerdown", pointerEventInit);
  25531. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERDOWN)) {
  25532. return this;
  25533. }
  25534. return this._processPointerDown(pickResult, evt);
  25535. };
  25536. Scene.prototype._processPointerDown = function (pickResult, evt) {
  25537. var _this = this;
  25538. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  25539. this._pickedDownMesh = pickResult.pickedMesh;
  25540. var actionManager = pickResult.pickedMesh.actionManager;
  25541. if (actionManager) {
  25542. if (actionManager.hasPickTriggers) {
  25543. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25544. switch (evt.button) {
  25545. case 0:
  25546. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25547. break;
  25548. case 1:
  25549. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25550. break;
  25551. case 2:
  25552. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25553. break;
  25554. }
  25555. }
  25556. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  25557. window.setTimeout(function () {
  25558. 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);
  25559. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  25560. if (_this._totalPointersPressed !== 0 &&
  25561. ((Date.now() - _this._startingPointerTime) > Scene.LongPressDelay) &&
  25562. !_this._isPointerSwiping()) {
  25563. _this._startingPointerTime = 0;
  25564. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25565. }
  25566. }
  25567. }, Scene.LongPressDelay);
  25568. }
  25569. }
  25570. }
  25571. else {
  25572. for (var _i = 0, _a = this._pointerDownStage; _i < _a.length; _i++) {
  25573. var step = _a[_i];
  25574. pickResult = step.action(this._unTranslatedPointerX, this._unTranslatedPointerY, pickResult, evt);
  25575. }
  25576. }
  25577. if (pickResult) {
  25578. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  25579. if (this.onPointerDown) {
  25580. this.onPointerDown(evt, pickResult, type);
  25581. }
  25582. if (this.onPointerObservable.hasObservers()) {
  25583. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  25584. this._setRayOnPointerInfo(pi);
  25585. this.onPointerObservable.notifyObservers(pi, type);
  25586. }
  25587. }
  25588. return this;
  25589. };
  25590. /**
  25591. * Use this method to simulate a pointer up on a mesh
  25592. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  25593. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  25594. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  25595. * @returns the current scene
  25596. */
  25597. Scene.prototype.simulatePointerUp = function (pickResult, pointerEventInit) {
  25598. var evt = new PointerEvent("pointerup", pointerEventInit);
  25599. var clickInfo = new ClickInfo();
  25600. clickInfo.singleClick = true;
  25601. clickInfo.ignore = true;
  25602. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERUP)) {
  25603. return this;
  25604. }
  25605. return this._processPointerUp(pickResult, evt, clickInfo);
  25606. };
  25607. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  25608. if (pickResult && pickResult && pickResult.pickedMesh) {
  25609. this._pickedUpMesh = pickResult.pickedMesh;
  25610. if (this._pickedDownMesh === this._pickedUpMesh) {
  25611. if (this.onPointerPick) {
  25612. this.onPointerPick(evt, pickResult);
  25613. }
  25614. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  25615. var type_1 = BABYLON.PointerEventTypes.POINTERPICK;
  25616. var pi = new BABYLON.PointerInfo(type_1, evt, pickResult);
  25617. this._setRayOnPointerInfo(pi);
  25618. this.onPointerObservable.notifyObservers(pi, type_1);
  25619. }
  25620. }
  25621. if (pickResult.pickedMesh.actionManager) {
  25622. if (clickInfo.ignore) {
  25623. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25624. }
  25625. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  25626. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25627. }
  25628. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25629. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25630. }
  25631. }
  25632. }
  25633. else {
  25634. if (!clickInfo.ignore) {
  25635. for (var _i = 0, _a = this._pointerUpStage; _i < _a.length; _i++) {
  25636. var step = _a[_i];
  25637. pickResult = step.action(this._unTranslatedPointerX, this._unTranslatedPointerY, pickResult, evt);
  25638. }
  25639. }
  25640. }
  25641. if (this._pickedDownMesh &&
  25642. this._pickedDownMesh.actionManager &&
  25643. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  25644. this._pickedDownMesh !== this._pickedUpMesh) {
  25645. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  25646. }
  25647. var type = BABYLON.PointerEventTypes.POINTERUP;
  25648. if (this.onPointerObservable.hasObservers()) {
  25649. if (!clickInfo.ignore) {
  25650. if (!clickInfo.hasSwiped) {
  25651. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  25652. var type_2 = BABYLON.PointerEventTypes.POINTERTAP;
  25653. var pi = new BABYLON.PointerInfo(type_2, evt, pickResult);
  25654. this._setRayOnPointerInfo(pi);
  25655. this.onPointerObservable.notifyObservers(pi, type_2);
  25656. }
  25657. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25658. var type_3 = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  25659. var pi = new BABYLON.PointerInfo(type_3, evt, pickResult);
  25660. this._setRayOnPointerInfo(pi);
  25661. this.onPointerObservable.notifyObservers(pi, type_3);
  25662. }
  25663. }
  25664. }
  25665. else {
  25666. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  25667. this._setRayOnPointerInfo(pi);
  25668. this.onPointerObservable.notifyObservers(pi, type);
  25669. }
  25670. }
  25671. if (this.onPointerUp) {
  25672. this.onPointerUp(evt, pickResult, type);
  25673. }
  25674. return this;
  25675. };
  25676. /**
  25677. * Gets a boolean indicating if the current pointer event is captured (meaning that the scene has already handled the pointer down)
  25678. * @param pointerId defines the pointer id to use in a multi-touch scenario (0 by default)
  25679. * @returns true if the pointer was captured
  25680. */
  25681. Scene.prototype.isPointerCaptured = function (pointerId) {
  25682. if (pointerId === void 0) { pointerId = 0; }
  25683. return this._pointerCaptures[pointerId];
  25684. };
  25685. /** @hidden */
  25686. Scene.prototype._isPointerSwiping = function () {
  25687. return Math.abs(this._startingPointerPosition.x - this._pointerX) > Scene.DragMovementThreshold ||
  25688. Math.abs(this._startingPointerPosition.y - this._pointerY) > Scene.DragMovementThreshold;
  25689. };
  25690. /**
  25691. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  25692. * @param attachUp defines if you want to attach events to pointerup
  25693. * @param attachDown defines if you want to attach events to pointerdown
  25694. * @param attachMove defines if you want to attach events to pointermove
  25695. */
  25696. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  25697. var _this = this;
  25698. if (attachUp === void 0) { attachUp = true; }
  25699. if (attachDown === void 0) { attachDown = true; }
  25700. if (attachMove === void 0) { attachMove = true; }
  25701. this._initActionManager = function (act, clickInfo) {
  25702. if (!_this._meshPickProceed) {
  25703. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  25704. _this._currentPickResult = pickResult;
  25705. if (pickResult) {
  25706. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  25707. }
  25708. _this._meshPickProceed = true;
  25709. }
  25710. return act;
  25711. };
  25712. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  25713. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  25714. if ((Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  25715. btn !== _this._previousButtonPressed) {
  25716. _this._doubleClickOccured = false;
  25717. clickInfo.singleClick = true;
  25718. clickInfo.ignore = false;
  25719. cb(clickInfo, _this._currentPickResult);
  25720. }
  25721. };
  25722. this._initClickEvent = function (obs1, obs2, evt, cb) {
  25723. var clickInfo = new ClickInfo();
  25724. _this._currentPickResult = null;
  25725. var act = null;
  25726. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  25727. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  25728. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25729. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  25730. act = _this._initActionManager(act, clickInfo);
  25731. if (act)
  25732. checkPicking = act.hasPickTriggers;
  25733. }
  25734. if (checkPicking) {
  25735. var btn = evt.button;
  25736. clickInfo.hasSwiped = _this._isPointerSwiping();
  25737. if (!clickInfo.hasSwiped) {
  25738. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  25739. if (!checkSingleClickImmediately) {
  25740. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  25741. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25742. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25743. act = _this._initActionManager(act, clickInfo);
  25744. if (act)
  25745. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  25746. }
  25747. }
  25748. if (checkSingleClickImmediately) {
  25749. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  25750. if (Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  25751. btn !== _this._previousButtonPressed) {
  25752. clickInfo.singleClick = true;
  25753. cb(clickInfo, _this._currentPickResult);
  25754. }
  25755. }
  25756. // at least one double click is required to be check and exclusive double click is enabled
  25757. else {
  25758. // wait that no double click has been raised during the double click delay
  25759. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25760. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  25761. }
  25762. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  25763. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25764. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25765. act = _this._initActionManager(act, clickInfo);
  25766. if (act)
  25767. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  25768. }
  25769. if (checkDoubleClick) {
  25770. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  25771. if (btn === _this._previousButtonPressed &&
  25772. Date.now() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  25773. !_this._doubleClickOccured) {
  25774. // pointer has not moved for 2 clicks, it's a double click
  25775. if (!clickInfo.hasSwiped &&
  25776. !_this._isPointerSwiping()) {
  25777. _this._previousStartingPointerTime = 0;
  25778. _this._doubleClickOccured = true;
  25779. clickInfo.doubleClick = true;
  25780. clickInfo.ignore = false;
  25781. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
  25782. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  25783. }
  25784. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25785. cb(clickInfo, _this._currentPickResult);
  25786. }
  25787. // if the two successive clicks are too far, it's just two simple clicks
  25788. else {
  25789. _this._doubleClickOccured = false;
  25790. _this._previousStartingPointerTime = _this._startingPointerTime;
  25791. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  25792. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  25793. _this._previousButtonPressed = btn;
  25794. if (Scene.ExclusiveDoubleClickMode) {
  25795. if (_this._previousDelayedSimpleClickTimeout) {
  25796. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  25797. }
  25798. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25799. cb(clickInfo, _this._previousPickResult);
  25800. }
  25801. else {
  25802. cb(clickInfo, _this._currentPickResult);
  25803. }
  25804. }
  25805. }
  25806. // just the first click of the double has been raised
  25807. else {
  25808. _this._doubleClickOccured = false;
  25809. _this._previousStartingPointerTime = _this._startingPointerTime;
  25810. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  25811. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  25812. _this._previousButtonPressed = btn;
  25813. }
  25814. }
  25815. }
  25816. }
  25817. clickInfo.ignore = true;
  25818. cb(clickInfo, _this._currentPickResult);
  25819. };
  25820. this._onPointerMove = function (evt) {
  25821. _this._updatePointerPosition(evt);
  25822. // PreObservable support
  25823. if (_this._checkPrePointerObservable(null, evt, evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE)) {
  25824. return;
  25825. }
  25826. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25827. return;
  25828. }
  25829. if (!_this.pointerMovePredicate) {
  25830. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  25831. }
  25832. // Meshes
  25833. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  25834. _this._processPointerMove(pickResult, evt);
  25835. };
  25836. this._onPointerDown = function (evt) {
  25837. _this._totalPointersPressed++;
  25838. _this._pickedDownMesh = null;
  25839. _this._meshPickProceed = false;
  25840. _this._updatePointerPosition(evt);
  25841. if (_this.preventDefaultOnPointerDown && canvas) {
  25842. evt.preventDefault();
  25843. canvas.focus();
  25844. }
  25845. // PreObservable support
  25846. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERDOWN)) {
  25847. return;
  25848. }
  25849. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25850. return;
  25851. }
  25852. _this._pointerCaptures[evt.pointerId] = true;
  25853. _this._startingPointerPosition.x = _this._pointerX;
  25854. _this._startingPointerPosition.y = _this._pointerY;
  25855. _this._startingPointerTime = Date.now();
  25856. if (!_this.pointerDownPredicate) {
  25857. _this.pointerDownPredicate = function (mesh) {
  25858. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  25859. };
  25860. }
  25861. // Meshes
  25862. _this._pickedDownMesh = null;
  25863. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  25864. _this._processPointerDown(pickResult, evt);
  25865. };
  25866. this._onPointerUp = function (evt) {
  25867. if (_this._totalPointersPressed === 0) { // We are attaching the pointer up to windows because of a bug in FF
  25868. return; // So we need to test it the pointer down was pressed before.
  25869. }
  25870. _this._totalPointersPressed--;
  25871. _this._pickedUpMesh = null;
  25872. _this._meshPickProceed = false;
  25873. _this._updatePointerPosition(evt);
  25874. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {
  25875. // PreObservable support
  25876. if (_this.onPrePointerObservable.hasObservers()) {
  25877. if (!clickInfo.ignore) {
  25878. if (!clickInfo.hasSwiped) {
  25879. if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  25880. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERTAP)) {
  25881. return;
  25882. }
  25883. }
  25884. if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25885. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25886. return;
  25887. }
  25888. }
  25889. }
  25890. }
  25891. else {
  25892. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERUP)) {
  25893. return;
  25894. }
  25895. }
  25896. }
  25897. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25898. return;
  25899. }
  25900. _this._pointerCaptures[evt.pointerId] = false;
  25901. if (!_this.pointerUpPredicate) {
  25902. _this.pointerUpPredicate = function (mesh) {
  25903. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  25904. };
  25905. }
  25906. // Meshes
  25907. if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {
  25908. _this._initActionManager(null, clickInfo);
  25909. }
  25910. if (!pickResult) {
  25911. pickResult = _this._currentPickResult;
  25912. }
  25913. _this._processPointerUp(pickResult, evt, clickInfo);
  25914. _this._previousPickResult = _this._currentPickResult;
  25915. });
  25916. };
  25917. this._onKeyDown = function (evt) {
  25918. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  25919. if (_this.onPreKeyboardObservable.hasObservers()) {
  25920. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  25921. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  25922. if (pi.skipOnPointerObservable) {
  25923. return;
  25924. }
  25925. }
  25926. if (_this.onKeyboardObservable.hasObservers()) {
  25927. var pi = new BABYLON.KeyboardInfo(type, evt);
  25928. _this.onKeyboardObservable.notifyObservers(pi, type);
  25929. }
  25930. if (_this.actionManager) {
  25931. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  25932. }
  25933. };
  25934. this._onKeyUp = function (evt) {
  25935. var type = BABYLON.KeyboardEventTypes.KEYUP;
  25936. if (_this.onPreKeyboardObservable.hasObservers()) {
  25937. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  25938. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  25939. if (pi.skipOnPointerObservable) {
  25940. return;
  25941. }
  25942. }
  25943. if (_this.onKeyboardObservable.hasObservers()) {
  25944. var pi = new BABYLON.KeyboardInfo(type, evt);
  25945. _this.onKeyboardObservable.notifyObservers(pi, type);
  25946. }
  25947. if (_this.actionManager) {
  25948. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  25949. }
  25950. };
  25951. var engine = this.getEngine();
  25952. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  25953. if (!canvas) {
  25954. return;
  25955. }
  25956. canvas.addEventListener("keydown", _this._onKeyDown, false);
  25957. canvas.addEventListener("keyup", _this._onKeyUp, false);
  25958. });
  25959. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  25960. if (!canvas) {
  25961. return;
  25962. }
  25963. canvas.removeEventListener("keydown", _this._onKeyDown);
  25964. canvas.removeEventListener("keyup", _this._onKeyUp);
  25965. });
  25966. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  25967. var canvas = this._engine.getRenderingCanvas();
  25968. if (!canvas) {
  25969. return;
  25970. }
  25971. if (attachMove) {
  25972. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  25973. // Wheel
  25974. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  25975. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  25976. }
  25977. if (attachDown) {
  25978. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  25979. }
  25980. if (attachUp) {
  25981. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  25982. }
  25983. canvas.tabIndex = 1;
  25984. };
  25985. /** Detaches all event handlers*/
  25986. Scene.prototype.detachControl = function () {
  25987. var engine = this.getEngine();
  25988. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  25989. var canvas = engine.getRenderingCanvas();
  25990. if (!canvas) {
  25991. return;
  25992. }
  25993. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  25994. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  25995. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  25996. if (this._onCanvasBlurObserver) {
  25997. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  25998. }
  25999. if (this._onCanvasFocusObserver) {
  26000. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  26001. }
  26002. // Wheel
  26003. canvas.removeEventListener('mousewheel', this._onPointerMove);
  26004. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  26005. // Keyboard
  26006. canvas.removeEventListener("keydown", this._onKeyDown);
  26007. canvas.removeEventListener("keyup", this._onKeyUp);
  26008. // Observables
  26009. this.onKeyboardObservable.clear();
  26010. this.onPreKeyboardObservable.clear();
  26011. this.onPointerObservable.clear();
  26012. this.onPrePointerObservable.clear();
  26013. };
  26014. /**
  26015. * This function will check if the scene can be rendered (textures are loaded, shaders are compiled)
  26016. * Delay loaded resources are not taking in account
  26017. * @return true if all required resources are ready
  26018. */
  26019. Scene.prototype.isReady = function () {
  26020. if (this._isDisposed) {
  26021. return false;
  26022. }
  26023. if (this._pendingData.length > 0) {
  26024. return false;
  26025. }
  26026. var index;
  26027. var engine = this.getEngine();
  26028. // Geometries
  26029. for (index = 0; index < this.geometries.length; index++) {
  26030. var geometry = this.geometries[index];
  26031. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  26032. return false;
  26033. }
  26034. }
  26035. // Meshes
  26036. for (index = 0; index < this.meshes.length; index++) {
  26037. var mesh = this.meshes[index];
  26038. if (!mesh.isEnabled()) {
  26039. continue;
  26040. }
  26041. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  26042. continue;
  26043. }
  26044. if (!mesh.isReady(true)) {
  26045. return false;
  26046. }
  26047. var hardwareInstancedRendering = mesh.getClassName() === "InstancedMesh" || engine.getCaps().instancedArrays && mesh.instances.length > 0;
  26048. // Is Ready For Mesh
  26049. for (var _i = 0, _a = this._isReadyForMeshStage; _i < _a.length; _i++) {
  26050. var step = _a[_i];
  26051. if (!step.action(mesh, hardwareInstancedRendering)) {
  26052. return false;
  26053. }
  26054. }
  26055. }
  26056. // Post-processes
  26057. if (this.activeCameras && this.activeCameras.length > 0) {
  26058. for (var _b = 0, _c = this.activeCameras; _b < _c.length; _b++) {
  26059. var camera = _c[_b];
  26060. if (!camera.isReady(true)) {
  26061. return false;
  26062. }
  26063. }
  26064. }
  26065. else if (this.activeCamera) {
  26066. if (!this.activeCamera.isReady(true)) {
  26067. return false;
  26068. }
  26069. }
  26070. // Particles
  26071. for (var _d = 0, _e = this.particleSystems; _d < _e.length; _d++) {
  26072. var particleSystem = _e[_d];
  26073. if (!particleSystem.isReady()) {
  26074. return false;
  26075. }
  26076. }
  26077. return true;
  26078. };
  26079. /** Resets all cached information relative to material (including effect and visibility) */
  26080. Scene.prototype.resetCachedMaterial = function () {
  26081. this._cachedMaterial = null;
  26082. this._cachedEffect = null;
  26083. this._cachedVisibility = null;
  26084. };
  26085. /**
  26086. * Registers a function to be called before every frame render
  26087. * @param func defines the function to register
  26088. */
  26089. Scene.prototype.registerBeforeRender = function (func) {
  26090. this.onBeforeRenderObservable.add(func);
  26091. };
  26092. /**
  26093. * Unregisters a function called before every frame render
  26094. * @param func defines the function to unregister
  26095. */
  26096. Scene.prototype.unregisterBeforeRender = function (func) {
  26097. this.onBeforeRenderObservable.removeCallback(func);
  26098. };
  26099. /**
  26100. * Registers a function to be called after every frame render
  26101. * @param func defines the function to register
  26102. */
  26103. Scene.prototype.registerAfterRender = function (func) {
  26104. this.onAfterRenderObservable.add(func);
  26105. };
  26106. /**
  26107. * Unregisters a function called after every frame render
  26108. * @param func defines the function to unregister
  26109. */
  26110. Scene.prototype.unregisterAfterRender = function (func) {
  26111. this.onAfterRenderObservable.removeCallback(func);
  26112. };
  26113. Scene.prototype._executeOnceBeforeRender = function (func) {
  26114. var _this = this;
  26115. var execFunc = function () {
  26116. func();
  26117. setTimeout(function () {
  26118. _this.unregisterBeforeRender(execFunc);
  26119. });
  26120. };
  26121. this.registerBeforeRender(execFunc);
  26122. };
  26123. /**
  26124. * The provided function will run before render once and will be disposed afterwards.
  26125. * A timeout delay can be provided so that the function will be executed in N ms.
  26126. * The timeout is using the browser's native setTimeout so time percision cannot be guaranteed.
  26127. * @param func The function to be executed.
  26128. * @param timeout optional delay in ms
  26129. */
  26130. Scene.prototype.executeOnceBeforeRender = function (func, timeout) {
  26131. var _this = this;
  26132. if (timeout !== undefined) {
  26133. setTimeout(function () {
  26134. _this._executeOnceBeforeRender(func);
  26135. }, timeout);
  26136. }
  26137. else {
  26138. this._executeOnceBeforeRender(func);
  26139. }
  26140. };
  26141. /** @hidden */
  26142. Scene.prototype._addPendingData = function (data) {
  26143. this._pendingData.push(data);
  26144. };
  26145. /** @hidden */
  26146. Scene.prototype._removePendingData = function (data) {
  26147. var wasLoading = this.isLoading;
  26148. var index = this._pendingData.indexOf(data);
  26149. if (index !== -1) {
  26150. this._pendingData.splice(index, 1);
  26151. }
  26152. if (wasLoading && !this.isLoading) {
  26153. this.onDataLoadedObservable.notifyObservers(this);
  26154. }
  26155. };
  26156. /**
  26157. * Returns the number of items waiting to be loaded
  26158. * @returns the number of items waiting to be loaded
  26159. */
  26160. Scene.prototype.getWaitingItemsCount = function () {
  26161. return this._pendingData.length;
  26162. };
  26163. Object.defineProperty(Scene.prototype, "isLoading", {
  26164. /**
  26165. * Returns a boolean indicating if the scene is still loading data
  26166. */
  26167. get: function () {
  26168. return this._pendingData.length > 0;
  26169. },
  26170. enumerable: true,
  26171. configurable: true
  26172. });
  26173. /**
  26174. * Registers a function to be executed when the scene is ready
  26175. * @param {Function} func - the function to be executed
  26176. */
  26177. Scene.prototype.executeWhenReady = function (func) {
  26178. var _this = this;
  26179. this.onReadyObservable.add(func);
  26180. if (this._executeWhenReadyTimeoutId !== -1) {
  26181. return;
  26182. }
  26183. this._executeWhenReadyTimeoutId = setTimeout(function () {
  26184. _this._checkIsReady();
  26185. }, 150);
  26186. };
  26187. /**
  26188. * Returns a promise that resolves when the scene is ready
  26189. * @returns A promise that resolves when the scene is ready
  26190. */
  26191. Scene.prototype.whenReadyAsync = function () {
  26192. var _this = this;
  26193. return new Promise(function (resolve) {
  26194. _this.executeWhenReady(function () {
  26195. resolve();
  26196. });
  26197. });
  26198. };
  26199. /** @hidden */
  26200. Scene.prototype._checkIsReady = function () {
  26201. var _this = this;
  26202. this._registerTransientComponents();
  26203. if (this.isReady()) {
  26204. this.onReadyObservable.notifyObservers(this);
  26205. this.onReadyObservable.clear();
  26206. this._executeWhenReadyTimeoutId = -1;
  26207. return;
  26208. }
  26209. this._executeWhenReadyTimeoutId = setTimeout(function () {
  26210. _this._checkIsReady();
  26211. }, 150);
  26212. };
  26213. // Animations
  26214. /**
  26215. * Will start the animation sequence of a given target
  26216. * @param target defines the target
  26217. * @param from defines from which frame should animation start
  26218. * @param to defines until which frame should animation run.
  26219. * @param weight defines the weight to apply to the animation (1.0 by default)
  26220. * @param loop defines if the animation loops
  26221. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  26222. * @param onAnimationEnd defines the function to be executed when the animation ends
  26223. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  26224. * @param targetMask defines if the target should be animated if animations are present (this is called recursively on descendant animatables regardless of return value)
  26225. * @returns the animatable object created for this animation
  26226. */
  26227. Scene.prototype.beginWeightedAnimation = function (target, from, to, weight, loop, speedRatio, onAnimationEnd, animatable, targetMask) {
  26228. if (weight === void 0) { weight = 1.0; }
  26229. if (speedRatio === void 0) { speedRatio = 1.0; }
  26230. var returnedAnimatable = this.beginAnimation(target, from, to, loop, speedRatio, onAnimationEnd, animatable, false, targetMask);
  26231. returnedAnimatable.weight = weight;
  26232. return returnedAnimatable;
  26233. };
  26234. /**
  26235. * Will start the animation sequence of a given target
  26236. * @param target defines the target
  26237. * @param from defines from which frame should animation start
  26238. * @param to defines until which frame should animation run.
  26239. * @param loop defines if the animation loops
  26240. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  26241. * @param onAnimationEnd defines the function to be executed when the animation ends
  26242. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  26243. * @param stopCurrent defines if the current animations must be stopped first (true by default)
  26244. * @param targetMask defines if the target should be animated if animations are present (this is called recursively on descendant animatables regardless of return value)
  26245. * @returns the animatable object created for this animation
  26246. */
  26247. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent, targetMask) {
  26248. if (speedRatio === void 0) { speedRatio = 1.0; }
  26249. if (stopCurrent === void 0) { stopCurrent = true; }
  26250. if (from > to && speedRatio > 0) {
  26251. speedRatio *= -1;
  26252. }
  26253. if (stopCurrent) {
  26254. this.stopAnimation(target, undefined, targetMask);
  26255. }
  26256. if (!animatable) {
  26257. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  26258. }
  26259. var shouldRunTargetAnimations = targetMask ? targetMask(target) : true;
  26260. // Local animations
  26261. if (target.animations && shouldRunTargetAnimations) {
  26262. animatable.appendAnimations(target, target.animations);
  26263. }
  26264. // Children animations
  26265. if (target.getAnimatables) {
  26266. var animatables = target.getAnimatables();
  26267. for (var index = 0; index < animatables.length; index++) {
  26268. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent, targetMask);
  26269. }
  26270. }
  26271. animatable.reset();
  26272. return animatable;
  26273. };
  26274. /**
  26275. * Begin a new animation on a given node
  26276. * @param target defines the target where the animation will take place
  26277. * @param animations defines the list of animations to start
  26278. * @param from defines the initial value
  26279. * @param to defines the final value
  26280. * @param loop defines if you want animation to loop (off by default)
  26281. * @param speedRatio defines the speed ratio to apply to all animations
  26282. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  26283. * @returns the list of created animatables
  26284. */
  26285. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  26286. if (speedRatio === undefined) {
  26287. speedRatio = 1.0;
  26288. }
  26289. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  26290. return animatable;
  26291. };
  26292. /**
  26293. * Begin a new animation on a given node and its hierarchy
  26294. * @param target defines the root node where the animation will take place
  26295. * @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.
  26296. * @param animations defines the list of animations to start
  26297. * @param from defines the initial value
  26298. * @param to defines the final value
  26299. * @param loop defines if you want animation to loop (off by default)
  26300. * @param speedRatio defines the speed ratio to apply to all animations
  26301. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  26302. * @returns the list of animatables created for all nodes
  26303. */
  26304. Scene.prototype.beginDirectHierarchyAnimation = function (target, directDescendantsOnly, animations, from, to, loop, speedRatio, onAnimationEnd) {
  26305. var children = target.getDescendants(directDescendantsOnly);
  26306. var result = [];
  26307. result.push(this.beginDirectAnimation(target, animations, from, to, loop, speedRatio, onAnimationEnd));
  26308. for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
  26309. var child = children_1[_i];
  26310. result.push(this.beginDirectAnimation(child, animations, from, to, loop, speedRatio, onAnimationEnd));
  26311. }
  26312. return result;
  26313. };
  26314. /**
  26315. * Gets the animatable associated with a specific target
  26316. * @param target defines the target of the animatable
  26317. * @returns the required animatable if found
  26318. */
  26319. Scene.prototype.getAnimatableByTarget = function (target) {
  26320. for (var index = 0; index < this._activeAnimatables.length; index++) {
  26321. if (this._activeAnimatables[index].target === target) {
  26322. return this._activeAnimatables[index];
  26323. }
  26324. }
  26325. return null;
  26326. };
  26327. /**
  26328. * Gets all animatables associated with a given target
  26329. * @param target defines the target to look animatables for
  26330. * @returns an array of Animatables
  26331. */
  26332. Scene.prototype.getAllAnimatablesByTarget = function (target) {
  26333. var result = [];
  26334. for (var index = 0; index < this._activeAnimatables.length; index++) {
  26335. if (this._activeAnimatables[index].target === target) {
  26336. result.push(this._activeAnimatables[index]);
  26337. }
  26338. }
  26339. return result;
  26340. };
  26341. Object.defineProperty(Scene.prototype, "animatables", {
  26342. /**
  26343. * Gets all animatable attached to the scene
  26344. */
  26345. get: function () {
  26346. return this._activeAnimatables;
  26347. },
  26348. enumerable: true,
  26349. configurable: true
  26350. });
  26351. /**
  26352. * Will stop the animation of the given target
  26353. * @param target - the target
  26354. * @param animationName - the name of the animation to stop (all animations will be stopped if both this and targetMask are empty)
  26355. * @param targetMask - a function that determines if the animation should be stopped based on its target (all animations will be stopped if both this and animationName are empty)
  26356. */
  26357. Scene.prototype.stopAnimation = function (target, animationName, targetMask) {
  26358. var animatables = this.getAllAnimatablesByTarget(target);
  26359. for (var _i = 0, animatables_1 = animatables; _i < animatables_1.length; _i++) {
  26360. var animatable = animatables_1[_i];
  26361. animatable.stop(animationName, targetMask);
  26362. }
  26363. };
  26364. /**
  26365. * Stops and removes all animations that have been applied to the scene
  26366. */
  26367. Scene.prototype.stopAllAnimations = function () {
  26368. if (this._activeAnimatables) {
  26369. for (var i = 0; i < this._activeAnimatables.length; i++) {
  26370. this._activeAnimatables[i].stop();
  26371. }
  26372. this._activeAnimatables = [];
  26373. }
  26374. for (var _i = 0, _a = this.animationGroups; _i < _a.length; _i++) {
  26375. var group = _a[_i];
  26376. group.stop();
  26377. }
  26378. };
  26379. Scene.prototype._animate = function () {
  26380. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  26381. return;
  26382. }
  26383. // Getting time
  26384. var now = BABYLON.Tools.Now;
  26385. if (!this._animationTimeLast) {
  26386. if (this._pendingData.length > 0) {
  26387. return;
  26388. }
  26389. this._animationTimeLast = now;
  26390. }
  26391. var deltaTime = this.useConstantAnimationDeltaTime ? 16.0 : (now - this._animationTimeLast) * this.animationTimeScale;
  26392. this._animationTime += deltaTime;
  26393. this._animationTimeLast = now;
  26394. for (var index = 0; index < this._activeAnimatables.length; index++) {
  26395. this._activeAnimatables[index]._animate(this._animationTime);
  26396. }
  26397. // Late animation bindings
  26398. this._processLateAnimationBindings();
  26399. };
  26400. /** @hidden */
  26401. Scene.prototype._registerTargetForLateAnimationBinding = function (runtimeAnimation, originalValue) {
  26402. var target = runtimeAnimation.target;
  26403. this._registeredForLateAnimationBindings.pushNoDuplicate(target);
  26404. if (!target._lateAnimationHolders) {
  26405. target._lateAnimationHolders = {};
  26406. }
  26407. if (!target._lateAnimationHolders[runtimeAnimation.targetPath]) {
  26408. target._lateAnimationHolders[runtimeAnimation.targetPath] = {
  26409. totalWeight: 0,
  26410. animations: [],
  26411. originalValue: originalValue
  26412. };
  26413. }
  26414. target._lateAnimationHolders[runtimeAnimation.targetPath].animations.push(runtimeAnimation);
  26415. target._lateAnimationHolders[runtimeAnimation.targetPath].totalWeight += runtimeAnimation.weight;
  26416. };
  26417. Scene.prototype._processLateAnimationBindingsForMatrices = function (holder) {
  26418. var normalizer = 1.0;
  26419. var finalPosition = BABYLON.Tmp.Vector3[0];
  26420. var finalScaling = BABYLON.Tmp.Vector3[1];
  26421. var finalQuaternion = BABYLON.Tmp.Quaternion[0];
  26422. var startIndex = 0;
  26423. var originalAnimation = holder.animations[0];
  26424. var originalValue = holder.originalValue;
  26425. var scale = 1;
  26426. if (holder.totalWeight < 1.0) {
  26427. // We need to mix the original value in
  26428. originalValue.decompose(finalScaling, finalQuaternion, finalPosition);
  26429. scale = 1.0 - holder.totalWeight;
  26430. }
  26431. else {
  26432. startIndex = 1;
  26433. // We need to normalize the weights
  26434. normalizer = holder.totalWeight;
  26435. originalAnimation.currentValue.decompose(finalScaling, finalQuaternion, finalPosition);
  26436. scale = originalAnimation.weight / normalizer;
  26437. if (scale == 1) {
  26438. return originalAnimation.currentValue;
  26439. }
  26440. }
  26441. finalScaling.scaleInPlace(scale);
  26442. finalPosition.scaleInPlace(scale);
  26443. finalQuaternion.scaleInPlace(scale);
  26444. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  26445. var runtimeAnimation = holder.animations[animIndex];
  26446. var scale = runtimeAnimation.weight / normalizer;
  26447. var currentPosition = BABYLON.Tmp.Vector3[2];
  26448. var currentScaling = BABYLON.Tmp.Vector3[3];
  26449. var currentQuaternion = BABYLON.Tmp.Quaternion[1];
  26450. runtimeAnimation.currentValue.decompose(currentScaling, currentQuaternion, currentPosition);
  26451. currentScaling.scaleAndAddToRef(scale, finalScaling);
  26452. currentQuaternion.scaleAndAddToRef(scale, finalQuaternion);
  26453. currentPosition.scaleAndAddToRef(scale, finalPosition);
  26454. }
  26455. BABYLON.Matrix.ComposeToRef(finalScaling, finalQuaternion, finalPosition, originalAnimation._workValue);
  26456. return originalAnimation._workValue;
  26457. };
  26458. Scene.prototype._processLateAnimationBindingsForQuaternions = function (holder, refQuaternion) {
  26459. var originalAnimation = holder.animations[0];
  26460. var originalValue = holder.originalValue;
  26461. if (holder.animations.length === 1) {
  26462. BABYLON.Quaternion.SlerpToRef(originalValue, originalAnimation.currentValue, Math.min(1.0, holder.totalWeight), refQuaternion);
  26463. return refQuaternion;
  26464. }
  26465. var normalizer = 1.0;
  26466. var quaternions;
  26467. var weights;
  26468. if (holder.totalWeight < 1.0) {
  26469. var scale = 1.0 - holder.totalWeight;
  26470. quaternions = [];
  26471. weights = [];
  26472. quaternions.push(originalValue);
  26473. weights.push(scale);
  26474. }
  26475. else {
  26476. if (holder.animations.length === 2) { // Slerp as soon as we can
  26477. BABYLON.Quaternion.SlerpToRef(holder.animations[0].currentValue, holder.animations[1].currentValue, holder.animations[1].weight / holder.totalWeight, refQuaternion);
  26478. return refQuaternion;
  26479. }
  26480. quaternions = [];
  26481. weights = [];
  26482. normalizer = holder.totalWeight;
  26483. }
  26484. for (var animIndex = 0; animIndex < holder.animations.length; animIndex++) {
  26485. var runtimeAnimation = holder.animations[animIndex];
  26486. quaternions.push(runtimeAnimation.currentValue);
  26487. weights.push(runtimeAnimation.weight / normalizer);
  26488. }
  26489. // https://gamedev.stackexchange.com/questions/62354/method-for-interpolation-between-3-quaternions
  26490. var cumulativeAmount = 0;
  26491. var cumulativeQuaternion = null;
  26492. for (var index = 0; index < quaternions.length;) {
  26493. if (!cumulativeQuaternion) {
  26494. BABYLON.Quaternion.SlerpToRef(quaternions[index], quaternions[index + 1], weights[index + 1] / (weights[index] + weights[index + 1]), refQuaternion);
  26495. cumulativeQuaternion = refQuaternion;
  26496. cumulativeAmount = weights[index] + weights[index + 1];
  26497. index += 2;
  26498. continue;
  26499. }
  26500. cumulativeAmount += weights[index];
  26501. BABYLON.Quaternion.SlerpToRef(cumulativeQuaternion, quaternions[index], weights[index] / cumulativeAmount, cumulativeQuaternion);
  26502. index++;
  26503. }
  26504. return cumulativeQuaternion;
  26505. };
  26506. Scene.prototype._processLateAnimationBindings = function () {
  26507. if (!this._registeredForLateAnimationBindings.length) {
  26508. return;
  26509. }
  26510. for (var index = 0; index < this._registeredForLateAnimationBindings.length; index++) {
  26511. var target = this._registeredForLateAnimationBindings.data[index];
  26512. for (var path in target._lateAnimationHolders) {
  26513. var holder = target._lateAnimationHolders[path];
  26514. var originalAnimation = holder.animations[0];
  26515. var originalValue = holder.originalValue;
  26516. var matrixDecomposeMode = BABYLON.Animation.AllowMatrixDecomposeForInterpolation && originalValue.m; // ie. data is matrix
  26517. var finalValue = target[path];
  26518. if (matrixDecomposeMode) {
  26519. finalValue = this._processLateAnimationBindingsForMatrices(holder);
  26520. }
  26521. else {
  26522. var quaternionMode = originalValue.w !== undefined;
  26523. if (quaternionMode) {
  26524. finalValue = this._processLateAnimationBindingsForQuaternions(holder, finalValue || BABYLON.Quaternion.Identity());
  26525. }
  26526. else {
  26527. var startIndex = 0;
  26528. var normalizer = 1.0;
  26529. if (holder.totalWeight < 1.0) {
  26530. // We need to mix the original value in
  26531. if (originalValue.scale) {
  26532. finalValue = originalValue.scale(1.0 - holder.totalWeight);
  26533. }
  26534. else {
  26535. finalValue = originalValue * (1.0 - holder.totalWeight);
  26536. }
  26537. }
  26538. else {
  26539. // We need to normalize the weights
  26540. normalizer = holder.totalWeight;
  26541. var scale_1 = originalAnimation.weight / normalizer;
  26542. if (scale_1 !== 1) {
  26543. if (originalAnimation.currentValue.scale) {
  26544. finalValue = originalAnimation.currentValue.scale(scale_1);
  26545. }
  26546. else {
  26547. finalValue = originalAnimation.currentValue * scale_1;
  26548. }
  26549. }
  26550. else {
  26551. finalValue = originalAnimation.currentValue;
  26552. }
  26553. startIndex = 1;
  26554. }
  26555. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  26556. var runtimeAnimation = holder.animations[animIndex];
  26557. var scale = runtimeAnimation.weight / normalizer;
  26558. if (runtimeAnimation.currentValue.scaleAndAddToRef) {
  26559. runtimeAnimation.currentValue.scaleAndAddToRef(scale, finalValue);
  26560. }
  26561. else {
  26562. finalValue += runtimeAnimation.currentValue * scale;
  26563. }
  26564. }
  26565. }
  26566. }
  26567. target[path] = finalValue;
  26568. }
  26569. target._lateAnimationHolders = {};
  26570. }
  26571. this._registeredForLateAnimationBindings.reset();
  26572. };
  26573. // Matrix
  26574. /** @hidden */
  26575. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  26576. this._useAlternateCameraConfiguration = active;
  26577. };
  26578. /**
  26579. * Gets the current view matrix
  26580. * @returns a Matrix
  26581. */
  26582. Scene.prototype.getViewMatrix = function () {
  26583. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  26584. };
  26585. /**
  26586. * Gets the current projection matrix
  26587. * @returns a Matrix
  26588. */
  26589. Scene.prototype.getProjectionMatrix = function () {
  26590. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  26591. };
  26592. /**
  26593. * Gets the current transform matrix
  26594. * @returns a Matrix made of View * Projection
  26595. */
  26596. Scene.prototype.getTransformMatrix = function () {
  26597. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  26598. };
  26599. /**
  26600. * Sets the current transform matrix
  26601. * @param view defines the View matrix to use
  26602. * @param projection defines the Projection matrix to use
  26603. */
  26604. Scene.prototype.setTransformMatrix = function (view, projection) {
  26605. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  26606. return;
  26607. }
  26608. this._viewUpdateFlag = view.updateFlag;
  26609. this._projectionUpdateFlag = projection.updateFlag;
  26610. this._viewMatrix = view;
  26611. this._projectionMatrix = projection;
  26612. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  26613. // Update frustum
  26614. if (!this._frustumPlanes) {
  26615. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  26616. }
  26617. else {
  26618. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  26619. }
  26620. if (this.activeCamera && this.activeCamera._alternateCamera) {
  26621. var otherCamera = this.activeCamera._alternateCamera;
  26622. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
  26623. BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  26624. }
  26625. if (this._sceneUbo.useUbo) {
  26626. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  26627. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  26628. this._sceneUbo.update();
  26629. }
  26630. };
  26631. /** @hidden */
  26632. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  26633. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  26634. return;
  26635. }
  26636. this._alternateViewUpdateFlag = view.updateFlag;
  26637. this._alternateProjectionUpdateFlag = projection.updateFlag;
  26638. this._alternateViewMatrix = view;
  26639. this._alternateProjectionMatrix = projection;
  26640. if (!this._alternateTransformMatrix) {
  26641. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  26642. }
  26643. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  26644. if (!this._alternateSceneUbo) {
  26645. this._createAlternateUbo();
  26646. }
  26647. if (this._alternateSceneUbo.useUbo) {
  26648. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  26649. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  26650. this._alternateSceneUbo.update();
  26651. }
  26652. };
  26653. /**
  26654. * Gets the uniform buffer used to store scene data
  26655. * @returns a UniformBuffer
  26656. */
  26657. Scene.prototype.getSceneUniformBuffer = function () {
  26658. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  26659. };
  26660. /**
  26661. * Gets an unique (relatively to the current scene) Id
  26662. * @returns an unique number for the scene
  26663. */
  26664. Scene.prototype.getUniqueId = function () {
  26665. var result = Scene._uniqueIdCounter;
  26666. Scene._uniqueIdCounter++;
  26667. return result;
  26668. };
  26669. /**
  26670. * Add a mesh to the list of scene's meshes
  26671. * @param newMesh defines the mesh to add
  26672. * @param recursive if all child meshes should also be added to the scene
  26673. */
  26674. Scene.prototype.addMesh = function (newMesh, recursive) {
  26675. var _this = this;
  26676. if (recursive === void 0) { recursive = false; }
  26677. this.meshes.push(newMesh);
  26678. //notify the collision coordinator
  26679. if (this.collisionCoordinator) {
  26680. this.collisionCoordinator.onMeshAdded(newMesh);
  26681. }
  26682. newMesh._resyncLightSources();
  26683. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  26684. if (recursive) {
  26685. newMesh.getChildMeshes().forEach(function (m) {
  26686. _this.addMesh(m);
  26687. });
  26688. }
  26689. };
  26690. /**
  26691. * Remove a mesh for the list of scene's meshes
  26692. * @param toRemove defines the mesh to remove
  26693. * @param recursive if all child meshes should also be removed from the scene
  26694. * @returns the index where the mesh was in the mesh list
  26695. */
  26696. Scene.prototype.removeMesh = function (toRemove, recursive) {
  26697. var _this = this;
  26698. if (recursive === void 0) { recursive = false; }
  26699. var index = this.meshes.indexOf(toRemove);
  26700. if (index !== -1) {
  26701. // Remove from the scene if mesh found
  26702. this.meshes.splice(index, 1);
  26703. }
  26704. this.onMeshRemovedObservable.notifyObservers(toRemove);
  26705. if (recursive) {
  26706. toRemove.getChildMeshes().forEach(function (m) {
  26707. _this.removeMesh(m);
  26708. });
  26709. }
  26710. return index;
  26711. };
  26712. /**
  26713. * Add a transform node to the list of scene's transform nodes
  26714. * @param newTransformNode defines the transform node to add
  26715. */
  26716. Scene.prototype.addTransformNode = function (newTransformNode) {
  26717. this.transformNodes.push(newTransformNode);
  26718. this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode);
  26719. };
  26720. /**
  26721. * Remove a transform node for the list of scene's transform nodes
  26722. * @param toRemove defines the transform node to remove
  26723. * @returns the index where the transform node was in the transform node list
  26724. */
  26725. Scene.prototype.removeTransformNode = function (toRemove) {
  26726. var index = this.transformNodes.indexOf(toRemove);
  26727. if (index !== -1) {
  26728. // Remove from the scene if found
  26729. this.transformNodes.splice(index, 1);
  26730. }
  26731. this.onTransformNodeRemovedObservable.notifyObservers(toRemove);
  26732. return index;
  26733. };
  26734. /**
  26735. * Remove a skeleton for the list of scene's skeletons
  26736. * @param toRemove defines the skeleton to remove
  26737. * @returns the index where the skeleton was in the skeleton list
  26738. */
  26739. Scene.prototype.removeSkeleton = function (toRemove) {
  26740. var index = this.skeletons.indexOf(toRemove);
  26741. if (index !== -1) {
  26742. // Remove from the scene if found
  26743. this.skeletons.splice(index, 1);
  26744. }
  26745. return index;
  26746. };
  26747. /**
  26748. * Remove a morph target for the list of scene's morph targets
  26749. * @param toRemove defines the morph target to remove
  26750. * @returns the index where the morph target was in the morph target list
  26751. */
  26752. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  26753. var index = this.morphTargetManagers.indexOf(toRemove);
  26754. if (index !== -1) {
  26755. // Remove from the scene if found
  26756. this.morphTargetManagers.splice(index, 1);
  26757. }
  26758. return index;
  26759. };
  26760. /**
  26761. * Remove a light for the list of scene's lights
  26762. * @param toRemove defines the light to remove
  26763. * @returns the index where the light was in the light list
  26764. */
  26765. Scene.prototype.removeLight = function (toRemove) {
  26766. var index = this.lights.indexOf(toRemove);
  26767. if (index !== -1) {
  26768. // Remove from meshes
  26769. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  26770. var mesh = _a[_i];
  26771. mesh._removeLightSource(toRemove);
  26772. }
  26773. // Remove from the scene if mesh found
  26774. this.lights.splice(index, 1);
  26775. this.sortLightsByPriority();
  26776. }
  26777. this.onLightRemovedObservable.notifyObservers(toRemove);
  26778. return index;
  26779. };
  26780. /**
  26781. * Remove a camera for the list of scene's cameras
  26782. * @param toRemove defines the camera to remove
  26783. * @returns the index where the camera was in the camera list
  26784. */
  26785. Scene.prototype.removeCamera = function (toRemove) {
  26786. var index = this.cameras.indexOf(toRemove);
  26787. if (index !== -1) {
  26788. // Remove from the scene if mesh found
  26789. this.cameras.splice(index, 1);
  26790. }
  26791. // Remove from activeCameras
  26792. var index2 = this.activeCameras.indexOf(toRemove);
  26793. if (index2 !== -1) {
  26794. // Remove from the scene if mesh found
  26795. this.activeCameras.splice(index2, 1);
  26796. }
  26797. // Reset the activeCamera
  26798. if (this.activeCamera === toRemove) {
  26799. if (this.cameras.length > 0) {
  26800. this.activeCamera = this.cameras[0];
  26801. }
  26802. else {
  26803. this.activeCamera = null;
  26804. }
  26805. }
  26806. this.onCameraRemovedObservable.notifyObservers(toRemove);
  26807. return index;
  26808. };
  26809. /**
  26810. * Remove a particle system for the list of scene's particle systems
  26811. * @param toRemove defines the particle system to remove
  26812. * @returns the index where the particle system was in the particle system list
  26813. */
  26814. Scene.prototype.removeParticleSystem = function (toRemove) {
  26815. var index = this.particleSystems.indexOf(toRemove);
  26816. if (index !== -1) {
  26817. this.particleSystems.splice(index, 1);
  26818. }
  26819. return index;
  26820. };
  26821. /**
  26822. * Remove a animation for the list of scene's animations
  26823. * @param toRemove defines the animation to remove
  26824. * @returns the index where the animation was in the animation list
  26825. */
  26826. Scene.prototype.removeAnimation = function (toRemove) {
  26827. var index = this.animations.indexOf(toRemove);
  26828. if (index !== -1) {
  26829. this.animations.splice(index, 1);
  26830. }
  26831. return index;
  26832. };
  26833. /**
  26834. * Removes the given animation group from this scene.
  26835. * @param toRemove The animation group to remove
  26836. * @returns The index of the removed animation group
  26837. */
  26838. Scene.prototype.removeAnimationGroup = function (toRemove) {
  26839. var index = this.animationGroups.indexOf(toRemove);
  26840. if (index !== -1) {
  26841. this.animationGroups.splice(index, 1);
  26842. }
  26843. return index;
  26844. };
  26845. /**
  26846. * Removes the given multi-material from this scene.
  26847. * @param toRemove The multi-material to remove
  26848. * @returns The index of the removed multi-material
  26849. */
  26850. Scene.prototype.removeMultiMaterial = function (toRemove) {
  26851. var index = this.multiMaterials.indexOf(toRemove);
  26852. if (index !== -1) {
  26853. this.multiMaterials.splice(index, 1);
  26854. }
  26855. return index;
  26856. };
  26857. /**
  26858. * Removes the given material from this scene.
  26859. * @param toRemove The material to remove
  26860. * @returns The index of the removed material
  26861. */
  26862. Scene.prototype.removeMaterial = function (toRemove) {
  26863. var index = this.materials.indexOf(toRemove);
  26864. if (index !== -1) {
  26865. this.materials.splice(index, 1);
  26866. }
  26867. return index;
  26868. };
  26869. /**
  26870. * Removes the given action manager from this scene.
  26871. * @param toRemove The action manager to remove
  26872. * @returns The index of the removed action manager
  26873. */
  26874. Scene.prototype.removeActionManager = function (toRemove) {
  26875. var index = this.actionManagers.indexOf(toRemove);
  26876. if (index !== -1) {
  26877. this.actionManagers.splice(index, 1);
  26878. }
  26879. return index;
  26880. };
  26881. /**
  26882. * Removes the given texture from this scene.
  26883. * @param toRemove The texture to remove
  26884. * @returns The index of the removed texture
  26885. */
  26886. Scene.prototype.removeTexture = function (toRemove) {
  26887. var index = this.textures.indexOf(toRemove);
  26888. if (index !== -1) {
  26889. this.textures.splice(index, 1);
  26890. }
  26891. return index;
  26892. };
  26893. /**
  26894. * Adds the given light to this scene
  26895. * @param newLight The light to add
  26896. */
  26897. Scene.prototype.addLight = function (newLight) {
  26898. this.lights.push(newLight);
  26899. this.sortLightsByPriority();
  26900. // Add light to all meshes (To support if the light is removed and then readded)
  26901. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  26902. var mesh = _a[_i];
  26903. if (mesh._lightSources.indexOf(newLight) === -1) {
  26904. mesh._lightSources.push(newLight);
  26905. mesh._resyncLightSources();
  26906. }
  26907. }
  26908. this.onNewLightAddedObservable.notifyObservers(newLight);
  26909. };
  26910. /**
  26911. * Sorts the list list based on light priorities
  26912. */
  26913. Scene.prototype.sortLightsByPriority = function () {
  26914. if (this.requireLightSorting) {
  26915. this.lights.sort(BABYLON.Light.CompareLightsPriority);
  26916. }
  26917. };
  26918. /**
  26919. * Adds the given camera to this scene
  26920. * @param newCamera The camera to add
  26921. */
  26922. Scene.prototype.addCamera = function (newCamera) {
  26923. this.cameras.push(newCamera);
  26924. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  26925. };
  26926. /**
  26927. * Adds the given skeleton to this scene
  26928. * @param newSkeleton The skeleton to add
  26929. */
  26930. Scene.prototype.addSkeleton = function (newSkeleton) {
  26931. this.skeletons.push(newSkeleton);
  26932. };
  26933. /**
  26934. * Adds the given particle system to this scene
  26935. * @param newParticleSystem The particle system to add
  26936. */
  26937. Scene.prototype.addParticleSystem = function (newParticleSystem) {
  26938. this.particleSystems.push(newParticleSystem);
  26939. };
  26940. /**
  26941. * Adds the given animation to this scene
  26942. * @param newAnimation The animation to add
  26943. */
  26944. Scene.prototype.addAnimation = function (newAnimation) {
  26945. this.animations.push(newAnimation);
  26946. };
  26947. /**
  26948. * Adds the given animation group to this scene.
  26949. * @param newAnimationGroup The animation group to add
  26950. */
  26951. Scene.prototype.addAnimationGroup = function (newAnimationGroup) {
  26952. this.animationGroups.push(newAnimationGroup);
  26953. };
  26954. /**
  26955. * Adds the given multi-material to this scene
  26956. * @param newMultiMaterial The multi-material to add
  26957. */
  26958. Scene.prototype.addMultiMaterial = function (newMultiMaterial) {
  26959. this.multiMaterials.push(newMultiMaterial);
  26960. };
  26961. /**
  26962. * Adds the given material to this scene
  26963. * @param newMaterial The material to add
  26964. */
  26965. Scene.prototype.addMaterial = function (newMaterial) {
  26966. this.materials.push(newMaterial);
  26967. };
  26968. /**
  26969. * Adds the given morph target to this scene
  26970. * @param newMorphTargetManager The morph target to add
  26971. */
  26972. Scene.prototype.addMorphTargetManager = function (newMorphTargetManager) {
  26973. this.morphTargetManagers.push(newMorphTargetManager);
  26974. };
  26975. /**
  26976. * Adds the given geometry to this scene
  26977. * @param newGeometry The geometry to add
  26978. */
  26979. Scene.prototype.addGeometry = function (newGeometry) {
  26980. this.geometries.push(newGeometry);
  26981. };
  26982. /**
  26983. * Adds the given action manager to this scene
  26984. * @param newActionManager The action manager to add
  26985. */
  26986. Scene.prototype.addActionManager = function (newActionManager) {
  26987. this.actionManagers.push(newActionManager);
  26988. };
  26989. /**
  26990. * Adds the given texture to this scene.
  26991. * @param newTexture The texture to add
  26992. */
  26993. Scene.prototype.addTexture = function (newTexture) {
  26994. this.textures.push(newTexture);
  26995. };
  26996. /**
  26997. * Switch active camera
  26998. * @param newCamera defines the new active camera
  26999. * @param attachControl defines if attachControl must be called for the new active camera (default: true)
  27000. */
  27001. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  27002. if (attachControl === void 0) { attachControl = true; }
  27003. var canvas = this._engine.getRenderingCanvas();
  27004. if (!canvas) {
  27005. return;
  27006. }
  27007. if (this.activeCamera) {
  27008. this.activeCamera.detachControl(canvas);
  27009. }
  27010. this.activeCamera = newCamera;
  27011. if (attachControl) {
  27012. newCamera.attachControl(canvas);
  27013. }
  27014. };
  27015. /**
  27016. * sets the active camera of the scene using its ID
  27017. * @param id defines the camera's ID
  27018. * @return the new active camera or null if none found.
  27019. */
  27020. Scene.prototype.setActiveCameraByID = function (id) {
  27021. var camera = this.getCameraByID(id);
  27022. if (camera) {
  27023. this.activeCamera = camera;
  27024. return camera;
  27025. }
  27026. return null;
  27027. };
  27028. /**
  27029. * sets the active camera of the scene using its name
  27030. * @param name defines the camera's name
  27031. * @returns the new active camera or null if none found.
  27032. */
  27033. Scene.prototype.setActiveCameraByName = function (name) {
  27034. var camera = this.getCameraByName(name);
  27035. if (camera) {
  27036. this.activeCamera = camera;
  27037. return camera;
  27038. }
  27039. return null;
  27040. };
  27041. /**
  27042. * get an animation group using its name
  27043. * @param name defines the material's name
  27044. * @return the animation group or null if none found.
  27045. */
  27046. Scene.prototype.getAnimationGroupByName = function (name) {
  27047. for (var index = 0; index < this.animationGroups.length; index++) {
  27048. if (this.animationGroups[index].name === name) {
  27049. return this.animationGroups[index];
  27050. }
  27051. }
  27052. return null;
  27053. };
  27054. /**
  27055. * get a material using its id
  27056. * @param id defines the material's ID
  27057. * @return the material or null if none found.
  27058. */
  27059. Scene.prototype.getMaterialByID = function (id) {
  27060. for (var index = 0; index < this.materials.length; index++) {
  27061. if (this.materials[index].id === id) {
  27062. return this.materials[index];
  27063. }
  27064. }
  27065. return null;
  27066. };
  27067. /**
  27068. * Gets a material using its name
  27069. * @param name defines the material's name
  27070. * @return the material or null if none found.
  27071. */
  27072. Scene.prototype.getMaterialByName = function (name) {
  27073. for (var index = 0; index < this.materials.length; index++) {
  27074. if (this.materials[index].name === name) {
  27075. return this.materials[index];
  27076. }
  27077. }
  27078. return null;
  27079. };
  27080. /**
  27081. * Gets a camera using its id
  27082. * @param id defines the id to look for
  27083. * @returns the camera or null if not found
  27084. */
  27085. Scene.prototype.getCameraByID = function (id) {
  27086. for (var index = 0; index < this.cameras.length; index++) {
  27087. if (this.cameras[index].id === id) {
  27088. return this.cameras[index];
  27089. }
  27090. }
  27091. return null;
  27092. };
  27093. /**
  27094. * Gets a camera using its unique id
  27095. * @param uniqueId defines the unique id to look for
  27096. * @returns the camera or null if not found
  27097. */
  27098. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  27099. for (var index = 0; index < this.cameras.length; index++) {
  27100. if (this.cameras[index].uniqueId === uniqueId) {
  27101. return this.cameras[index];
  27102. }
  27103. }
  27104. return null;
  27105. };
  27106. /**
  27107. * Gets a camera using its name
  27108. * @param name defines the camera's name
  27109. * @return the camera or null if none found.
  27110. */
  27111. Scene.prototype.getCameraByName = function (name) {
  27112. for (var index = 0; index < this.cameras.length; index++) {
  27113. if (this.cameras[index].name === name) {
  27114. return this.cameras[index];
  27115. }
  27116. }
  27117. return null;
  27118. };
  27119. /**
  27120. * Gets a bone using its id
  27121. * @param id defines the bone's id
  27122. * @return the bone or null if not found
  27123. */
  27124. Scene.prototype.getBoneByID = function (id) {
  27125. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  27126. var skeleton = this.skeletons[skeletonIndex];
  27127. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  27128. if (skeleton.bones[boneIndex].id === id) {
  27129. return skeleton.bones[boneIndex];
  27130. }
  27131. }
  27132. }
  27133. return null;
  27134. };
  27135. /**
  27136. * Gets a bone using its id
  27137. * @param name defines the bone's name
  27138. * @return the bone or null if not found
  27139. */
  27140. Scene.prototype.getBoneByName = function (name) {
  27141. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  27142. var skeleton = this.skeletons[skeletonIndex];
  27143. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  27144. if (skeleton.bones[boneIndex].name === name) {
  27145. return skeleton.bones[boneIndex];
  27146. }
  27147. }
  27148. }
  27149. return null;
  27150. };
  27151. /**
  27152. * Gets a light node using its name
  27153. * @param name defines the the light's name
  27154. * @return the light or null if none found.
  27155. */
  27156. Scene.prototype.getLightByName = function (name) {
  27157. for (var index = 0; index < this.lights.length; index++) {
  27158. if (this.lights[index].name === name) {
  27159. return this.lights[index];
  27160. }
  27161. }
  27162. return null;
  27163. };
  27164. /**
  27165. * Gets a light node using its id
  27166. * @param id defines the light's id
  27167. * @return the light or null if none found.
  27168. */
  27169. Scene.prototype.getLightByID = function (id) {
  27170. for (var index = 0; index < this.lights.length; index++) {
  27171. if (this.lights[index].id === id) {
  27172. return this.lights[index];
  27173. }
  27174. }
  27175. return null;
  27176. };
  27177. /**
  27178. * Gets a light node using its scene-generated unique ID
  27179. * @param uniqueId defines the light's unique id
  27180. * @return the light or null if none found.
  27181. */
  27182. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  27183. for (var index = 0; index < this.lights.length; index++) {
  27184. if (this.lights[index].uniqueId === uniqueId) {
  27185. return this.lights[index];
  27186. }
  27187. }
  27188. return null;
  27189. };
  27190. /**
  27191. * Gets a particle system by id
  27192. * @param id defines the particle system id
  27193. * @return the corresponding system or null if none found
  27194. */
  27195. Scene.prototype.getParticleSystemByID = function (id) {
  27196. for (var index = 0; index < this.particleSystems.length; index++) {
  27197. if (this.particleSystems[index].id === id) {
  27198. return this.particleSystems[index];
  27199. }
  27200. }
  27201. return null;
  27202. };
  27203. /**
  27204. * Gets a geometry using its ID
  27205. * @param id defines the geometry's id
  27206. * @return the geometry or null if none found.
  27207. */
  27208. Scene.prototype.getGeometryByID = function (id) {
  27209. for (var index = 0; index < this.geometries.length; index++) {
  27210. if (this.geometries[index].id === id) {
  27211. return this.geometries[index];
  27212. }
  27213. }
  27214. return null;
  27215. };
  27216. /**
  27217. * Add a new geometry to this scene
  27218. * @param geometry defines the geometry to be added to the scene.
  27219. * @param force defines if the geometry must be pushed even if a geometry with this id already exists
  27220. * @return a boolean defining if the geometry was added or not
  27221. */
  27222. Scene.prototype.pushGeometry = function (geometry, force) {
  27223. if (!force && this.getGeometryByID(geometry.id)) {
  27224. return false;
  27225. }
  27226. this.geometries.push(geometry);
  27227. //notify the collision coordinator
  27228. if (this.collisionCoordinator) {
  27229. this.collisionCoordinator.onGeometryAdded(geometry);
  27230. }
  27231. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  27232. return true;
  27233. };
  27234. /**
  27235. * Removes an existing geometry
  27236. * @param geometry defines the geometry to be removed from the scene
  27237. * @return a boolean defining if the geometry was removed or not
  27238. */
  27239. Scene.prototype.removeGeometry = function (geometry) {
  27240. var index = this.geometries.indexOf(geometry);
  27241. if (index > -1) {
  27242. this.geometries.splice(index, 1);
  27243. //notify the collision coordinator
  27244. if (this.collisionCoordinator) {
  27245. this.collisionCoordinator.onGeometryDeleted(geometry);
  27246. }
  27247. this.onGeometryRemovedObservable.notifyObservers(geometry);
  27248. return true;
  27249. }
  27250. return false;
  27251. };
  27252. /**
  27253. * Gets the list of geometries attached to the scene
  27254. * @returns an array of Geometry
  27255. */
  27256. Scene.prototype.getGeometries = function () {
  27257. return this.geometries;
  27258. };
  27259. /**
  27260. * Gets the first added mesh found of a given ID
  27261. * @param id defines the id to search for
  27262. * @return the mesh found or null if not found at all
  27263. */
  27264. Scene.prototype.getMeshByID = function (id) {
  27265. for (var index = 0; index < this.meshes.length; index++) {
  27266. if (this.meshes[index].id === id) {
  27267. return this.meshes[index];
  27268. }
  27269. }
  27270. return null;
  27271. };
  27272. /**
  27273. * Gets a list of meshes using their id
  27274. * @param id defines the id to search for
  27275. * @returns a list of meshes
  27276. */
  27277. Scene.prototype.getMeshesByID = function (id) {
  27278. return this.meshes.filter(function (m) {
  27279. return m.id === id;
  27280. });
  27281. };
  27282. /**
  27283. * Gets the first added transform node found of a given ID
  27284. * @param id defines the id to search for
  27285. * @return the found transform node or null if not found at all.
  27286. */
  27287. Scene.prototype.getTransformNodeByID = function (id) {
  27288. for (var index = 0; index < this.transformNodes.length; index++) {
  27289. if (this.transformNodes[index].id === id) {
  27290. return this.transformNodes[index];
  27291. }
  27292. }
  27293. return null;
  27294. };
  27295. /**
  27296. * Gets a list of transform nodes using their id
  27297. * @param id defines the id to search for
  27298. * @returns a list of transform nodes
  27299. */
  27300. Scene.prototype.getTransformNodesByID = function (id) {
  27301. return this.transformNodes.filter(function (m) {
  27302. return m.id === id;
  27303. });
  27304. };
  27305. /**
  27306. * Gets a mesh with its auto-generated unique id
  27307. * @param uniqueId defines the unique id to search for
  27308. * @return the found mesh or null if not found at all.
  27309. */
  27310. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  27311. for (var index = 0; index < this.meshes.length; index++) {
  27312. if (this.meshes[index].uniqueId === uniqueId) {
  27313. return this.meshes[index];
  27314. }
  27315. }
  27316. return null;
  27317. };
  27318. /**
  27319. * Gets a the last added mesh using a given id
  27320. * @param id defines the id to search for
  27321. * @return the found mesh or null if not found at all.
  27322. */
  27323. Scene.prototype.getLastMeshByID = function (id) {
  27324. for (var index = this.meshes.length - 1; index >= 0; index--) {
  27325. if (this.meshes[index].id === id) {
  27326. return this.meshes[index];
  27327. }
  27328. }
  27329. return null;
  27330. };
  27331. /**
  27332. * Gets a the last added node (Mesh, Camera, Light) using a given id
  27333. * @param id defines the id to search for
  27334. * @return the found node or null if not found at all
  27335. */
  27336. Scene.prototype.getLastEntryByID = function (id) {
  27337. var index;
  27338. for (index = this.meshes.length - 1; index >= 0; index--) {
  27339. if (this.meshes[index].id === id) {
  27340. return this.meshes[index];
  27341. }
  27342. }
  27343. for (index = this.transformNodes.length - 1; index >= 0; index--) {
  27344. if (this.transformNodes[index].id === id) {
  27345. return this.transformNodes[index];
  27346. }
  27347. }
  27348. for (index = this.cameras.length - 1; index >= 0; index--) {
  27349. if (this.cameras[index].id === id) {
  27350. return this.cameras[index];
  27351. }
  27352. }
  27353. for (index = this.lights.length - 1; index >= 0; index--) {
  27354. if (this.lights[index].id === id) {
  27355. return this.lights[index];
  27356. }
  27357. }
  27358. return null;
  27359. };
  27360. /**
  27361. * Gets a node (Mesh, Camera, Light) using a given id
  27362. * @param id defines the id to search for
  27363. * @return the found node or null if not found at all
  27364. */
  27365. Scene.prototype.getNodeByID = function (id) {
  27366. var mesh = this.getMeshByID(id);
  27367. if (mesh) {
  27368. return mesh;
  27369. }
  27370. var light = this.getLightByID(id);
  27371. if (light) {
  27372. return light;
  27373. }
  27374. var camera = this.getCameraByID(id);
  27375. if (camera) {
  27376. return camera;
  27377. }
  27378. var bone = this.getBoneByID(id);
  27379. return bone;
  27380. };
  27381. /**
  27382. * Gets a node (Mesh, Camera, Light) using a given name
  27383. * @param name defines the name to search for
  27384. * @return the found node or null if not found at all.
  27385. */
  27386. Scene.prototype.getNodeByName = function (name) {
  27387. var mesh = this.getMeshByName(name);
  27388. if (mesh) {
  27389. return mesh;
  27390. }
  27391. var light = this.getLightByName(name);
  27392. if (light) {
  27393. return light;
  27394. }
  27395. var camera = this.getCameraByName(name);
  27396. if (camera) {
  27397. return camera;
  27398. }
  27399. var bone = this.getBoneByName(name);
  27400. return bone;
  27401. };
  27402. /**
  27403. * Gets a mesh using a given name
  27404. * @param name defines the name to search for
  27405. * @return the found mesh or null if not found at all.
  27406. */
  27407. Scene.prototype.getMeshByName = function (name) {
  27408. for (var index = 0; index < this.meshes.length; index++) {
  27409. if (this.meshes[index].name === name) {
  27410. return this.meshes[index];
  27411. }
  27412. }
  27413. return null;
  27414. };
  27415. /**
  27416. * Gets a transform node using a given name
  27417. * @param name defines the name to search for
  27418. * @return the found transform node or null if not found at all.
  27419. */
  27420. Scene.prototype.getTransformNodeByName = function (name) {
  27421. for (var index = 0; index < this.transformNodes.length; index++) {
  27422. if (this.transformNodes[index].name === name) {
  27423. return this.transformNodes[index];
  27424. }
  27425. }
  27426. return null;
  27427. };
  27428. /**
  27429. * Gets a skeleton using a given id (if many are found, this function will pick the last one)
  27430. * @param id defines the id to search for
  27431. * @return the found skeleton or null if not found at all.
  27432. */
  27433. Scene.prototype.getLastSkeletonByID = function (id) {
  27434. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  27435. if (this.skeletons[index].id === id) {
  27436. return this.skeletons[index];
  27437. }
  27438. }
  27439. return null;
  27440. };
  27441. /**
  27442. * Gets a skeleton using a given id (if many are found, this function will pick the first one)
  27443. * @param id defines the id to search for
  27444. * @return the found skeleton or null if not found at all.
  27445. */
  27446. Scene.prototype.getSkeletonById = function (id) {
  27447. for (var index = 0; index < this.skeletons.length; index++) {
  27448. if (this.skeletons[index].id === id) {
  27449. return this.skeletons[index];
  27450. }
  27451. }
  27452. return null;
  27453. };
  27454. /**
  27455. * Gets a skeleton using a given name
  27456. * @param name defines the name to search for
  27457. * @return the found skeleton or null if not found at all.
  27458. */
  27459. Scene.prototype.getSkeletonByName = function (name) {
  27460. for (var index = 0; index < this.skeletons.length; index++) {
  27461. if (this.skeletons[index].name === name) {
  27462. return this.skeletons[index];
  27463. }
  27464. }
  27465. return null;
  27466. };
  27467. /**
  27468. * Gets a morph target manager using a given id (if many are found, this function will pick the last one)
  27469. * @param id defines the id to search for
  27470. * @return the found morph target manager or null if not found at all.
  27471. */
  27472. Scene.prototype.getMorphTargetManagerById = function (id) {
  27473. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  27474. if (this.morphTargetManagers[index].uniqueId === id) {
  27475. return this.morphTargetManagers[index];
  27476. }
  27477. }
  27478. return null;
  27479. };
  27480. /**
  27481. * Gets a boolean indicating if the given mesh is active
  27482. * @param mesh defines the mesh to look for
  27483. * @returns true if the mesh is in the active list
  27484. */
  27485. Scene.prototype.isActiveMesh = function (mesh) {
  27486. return (this._activeMeshes.indexOf(mesh) !== -1);
  27487. };
  27488. Object.defineProperty(Scene.prototype, "uid", {
  27489. /**
  27490. * Return a unique id as a string which can serve as an identifier for the scene
  27491. */
  27492. get: function () {
  27493. if (!this._uid) {
  27494. this._uid = BABYLON.Tools.RandomId();
  27495. }
  27496. return this._uid;
  27497. },
  27498. enumerable: true,
  27499. configurable: true
  27500. });
  27501. /**
  27502. * Add an externaly attached data from its key.
  27503. * This method call will fail and return false, if such key already exists.
  27504. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  27505. * @param key the unique key that identifies the data
  27506. * @param data the data object to associate to the key for this Engine instance
  27507. * @return true if no such key were already present and the data was added successfully, false otherwise
  27508. */
  27509. Scene.prototype.addExternalData = function (key, data) {
  27510. if (!this._externalData) {
  27511. this._externalData = new BABYLON.StringDictionary();
  27512. }
  27513. return this._externalData.add(key, data);
  27514. };
  27515. /**
  27516. * Get an externaly attached data from its key
  27517. * @param key the unique key that identifies the data
  27518. * @return the associated data, if present (can be null), or undefined if not present
  27519. */
  27520. Scene.prototype.getExternalData = function (key) {
  27521. if (!this._externalData) {
  27522. return null;
  27523. }
  27524. return this._externalData.get(key);
  27525. };
  27526. /**
  27527. * Get an externaly attached data from its key, create it using a factory if it's not already present
  27528. * @param key the unique key that identifies the data
  27529. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  27530. * @return the associated data, can be null if the factory returned null.
  27531. */
  27532. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  27533. if (!this._externalData) {
  27534. this._externalData = new BABYLON.StringDictionary();
  27535. }
  27536. return this._externalData.getOrAddWithFactory(key, factory);
  27537. };
  27538. /**
  27539. * Remove an externaly attached data from the Engine instance
  27540. * @param key the unique key that identifies the data
  27541. * @return true if the data was successfully removed, false if it doesn't exist
  27542. */
  27543. Scene.prototype.removeExternalData = function (key) {
  27544. return this._externalData.remove(key);
  27545. };
  27546. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  27547. if (this.dispatchAllSubMeshesOfActiveMeshes || mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  27548. for (var _i = 0, _a = this._evaluateSubMeshStage; _i < _a.length; _i++) {
  27549. var step = _a[_i];
  27550. step.action(mesh, subMesh);
  27551. }
  27552. var material = subMesh.getMaterial();
  27553. if (material !== null && material !== undefined) {
  27554. // Render targets
  27555. if (material.hasRenderTargetTextures && material.getRenderTargetTextures !== undefined) {
  27556. if (this._processedMaterials.indexOf(material) === -1) {
  27557. this._processedMaterials.push(material);
  27558. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  27559. }
  27560. }
  27561. // Dispatch
  27562. this._activeIndices.addCount(subMesh.indexCount, false);
  27563. this._renderingManager.dispatch(subMesh, mesh, material);
  27564. }
  27565. }
  27566. };
  27567. /**
  27568. * Clear the processed materials smart array preventing retention point in material dispose.
  27569. */
  27570. Scene.prototype.freeProcessedMaterials = function () {
  27571. this._processedMaterials.dispose();
  27572. };
  27573. /**
  27574. * Clear the active meshes smart array preventing retention point in mesh dispose.
  27575. */
  27576. Scene.prototype.freeActiveMeshes = function () {
  27577. this._activeMeshes.dispose();
  27578. if (this.activeCamera && this.activeCamera._activeMeshes) {
  27579. this.activeCamera._activeMeshes.dispose();
  27580. }
  27581. if (this.activeCameras) {
  27582. for (var i = 0; i < this.activeCameras.length; i++) {
  27583. var activeCamera = this.activeCameras[i];
  27584. if (activeCamera && activeCamera._activeMeshes) {
  27585. activeCamera._activeMeshes.dispose();
  27586. }
  27587. }
  27588. }
  27589. };
  27590. /**
  27591. * Clear the info related to rendering groups preventing retention points during dispose.
  27592. */
  27593. Scene.prototype.freeRenderingGroups = function () {
  27594. if (this._renderingManager) {
  27595. this._renderingManager.freeRenderingGroups();
  27596. }
  27597. if (this.textures) {
  27598. for (var i = 0; i < this.textures.length; i++) {
  27599. var texture = this.textures[i];
  27600. if (texture && texture.renderList) {
  27601. texture.freeRenderingGroups();
  27602. }
  27603. }
  27604. }
  27605. };
  27606. /** @hidden */
  27607. Scene.prototype._isInIntermediateRendering = function () {
  27608. return this._intermediateRendering;
  27609. };
  27610. /**
  27611. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  27612. * @returns the current scene
  27613. */
  27614. Scene.prototype.freezeActiveMeshes = function () {
  27615. if (!this.activeCamera) {
  27616. return this;
  27617. }
  27618. if (!this._frustumPlanes) {
  27619. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  27620. }
  27621. this._evaluateActiveMeshes();
  27622. this._activeMeshesFrozen = true;
  27623. return this;
  27624. };
  27625. /**
  27626. * Use this function to restart evaluating active meshes on every frame
  27627. * @returns the current scene
  27628. */
  27629. Scene.prototype.unfreezeActiveMeshes = function () {
  27630. this._activeMeshesFrozen = false;
  27631. return this;
  27632. };
  27633. Scene.prototype._evaluateActiveMeshes = function () {
  27634. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  27635. return;
  27636. }
  27637. if (!this.activeCamera) {
  27638. return;
  27639. }
  27640. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  27641. this.activeCamera._activeMeshes.reset();
  27642. this._activeMeshes.reset();
  27643. this._renderingManager.reset();
  27644. this._processedMaterials.reset();
  27645. this._activeParticleSystems.reset();
  27646. this._activeSkeletons.reset();
  27647. this._softwareSkinnedMeshes.reset();
  27648. for (var _i = 0, _a = this._beforeEvaluateActiveMeshStage; _i < _a.length; _i++) {
  27649. var step = _a[_i];
  27650. step.action();
  27651. }
  27652. // Determine mesh candidates
  27653. var meshes = this.getActiveMeshCandidates();
  27654. // Check each mesh
  27655. var len = meshes.length;
  27656. for (var i = 0; i < len; i++) {
  27657. var mesh = meshes.data[i];
  27658. if (mesh.isBlocked) {
  27659. continue;
  27660. }
  27661. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  27662. if (!mesh.isReady() || !mesh.isEnabled()) {
  27663. continue;
  27664. }
  27665. mesh.computeWorldMatrix();
  27666. // Intersections
  27667. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers2(BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger)) {
  27668. this._meshesForIntersections.pushNoDuplicate(mesh);
  27669. }
  27670. // Switch to current LOD
  27671. var meshLOD = mesh.getLOD(this.activeCamera);
  27672. if (meshLOD === undefined || meshLOD === null) {
  27673. continue;
  27674. }
  27675. mesh._preActivate();
  27676. if (mesh.isVisible && mesh.visibility > 0 && (mesh.alwaysSelectAsActiveMesh || ((mesh.layerMask & this.activeCamera.layerMask) !== 0 && mesh.isInFrustum(this._frustumPlanes)))) {
  27677. this._activeMeshes.push(mesh);
  27678. this.activeCamera._activeMeshes.push(mesh);
  27679. mesh._activate(this._renderId);
  27680. if (meshLOD !== mesh) {
  27681. meshLOD._activate(this._renderId);
  27682. }
  27683. this._activeMesh(mesh, meshLOD);
  27684. }
  27685. }
  27686. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  27687. // Particle systems
  27688. if (this.particlesEnabled) {
  27689. this.onBeforeParticlesRenderingObservable.notifyObservers(this);
  27690. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  27691. var particleSystem = this.particleSystems[particleIndex];
  27692. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  27693. continue;
  27694. }
  27695. var emitter = particleSystem.emitter;
  27696. if (!emitter.position || emitter.isEnabled()) {
  27697. this._activeParticleSystems.push(particleSystem);
  27698. particleSystem.animate();
  27699. this._renderingManager.dispatchParticles(particleSystem);
  27700. }
  27701. }
  27702. this.onAfterParticlesRenderingObservable.notifyObservers(this);
  27703. }
  27704. };
  27705. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  27706. if (this._skeletonsEnabled && mesh.skeleton !== null && mesh.skeleton !== undefined) {
  27707. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  27708. mesh.skeleton.prepare();
  27709. }
  27710. if (!mesh.computeBonesUsingShaders) {
  27711. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  27712. }
  27713. }
  27714. for (var _i = 0, _a = this._activeMeshStage; _i < _a.length; _i++) {
  27715. var step = _a[_i];
  27716. step.action(sourceMesh, mesh);
  27717. }
  27718. if (mesh !== undefined && mesh !== null
  27719. && mesh.subMeshes !== undefined && mesh.subMeshes !== null && mesh.subMeshes.length > 0) {
  27720. var subMeshes = this.getActiveSubMeshCandidates(mesh);
  27721. var len = subMeshes.length;
  27722. for (var i = 0; i < len; i++) {
  27723. var subMesh = subMeshes.data[i];
  27724. this._evaluateSubMesh(subMesh, mesh);
  27725. }
  27726. }
  27727. };
  27728. /**
  27729. * Update the transform matrix to update from the current active camera
  27730. * @param force defines a boolean used to force the update even if cache is up to date
  27731. */
  27732. Scene.prototype.updateTransformMatrix = function (force) {
  27733. if (!this.activeCamera) {
  27734. return;
  27735. }
  27736. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  27737. };
  27738. /**
  27739. * 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)
  27740. * @param alternateCamera defines the camera to use
  27741. */
  27742. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  27743. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  27744. };
  27745. Scene.prototype._renderForCamera = function (camera, rigParent) {
  27746. if (camera && camera._skipRendering) {
  27747. return;
  27748. }
  27749. var engine = this._engine;
  27750. this.activeCamera = camera;
  27751. if (!this.activeCamera)
  27752. throw new Error("Active camera not set");
  27753. // Viewport
  27754. engine.setViewport(this.activeCamera.viewport);
  27755. // Camera
  27756. this.resetCachedMaterial();
  27757. this._renderId++;
  27758. this.updateTransformMatrix();
  27759. if (camera._alternateCamera) {
  27760. this.updateAlternateTransformMatrix(camera._alternateCamera);
  27761. this._alternateRendering = true;
  27762. }
  27763. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  27764. // Meshes
  27765. this._evaluateActiveMeshes();
  27766. // Software skinning
  27767. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  27768. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  27769. mesh.applySkeleton(mesh.skeleton);
  27770. }
  27771. // Render targets
  27772. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  27773. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  27774. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  27775. }
  27776. if (rigParent && rigParent.customRenderTargets && rigParent.customRenderTargets.length > 0) {
  27777. this._renderTargets.concatWithNoDuplicate(rigParent.customRenderTargets);
  27778. }
  27779. // Collects render targets from external components.
  27780. for (var _i = 0, _a = this._gatherActiveCameraRenderTargetsStage; _i < _a.length; _i++) {
  27781. var step = _a[_i];
  27782. step.action(this._renderTargets);
  27783. }
  27784. if (this.renderTargetsEnabled) {
  27785. this._intermediateRendering = true;
  27786. if (this._renderTargets.length > 0) {
  27787. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  27788. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  27789. var renderTarget = this._renderTargets.data[renderIndex];
  27790. if (renderTarget._shouldRender()) {
  27791. this._renderId++;
  27792. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  27793. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  27794. }
  27795. }
  27796. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  27797. this._renderId++;
  27798. }
  27799. for (var _b = 0, _c = this._cameraDrawRenderTargetStage; _b < _c.length; _b++) {
  27800. var step = _c[_b];
  27801. step.action(this.activeCamera);
  27802. }
  27803. this._intermediateRendering = false;
  27804. engine.restoreDefaultFramebuffer(); // Restore back buffer if needed
  27805. }
  27806. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  27807. // Prepare Frame
  27808. if (this.postProcessManager) {
  27809. this.postProcessManager._prepareFrame();
  27810. }
  27811. // Before Camera Draw
  27812. for (var _d = 0, _e = this._beforeCameraDrawStage; _d < _e.length; _d++) {
  27813. var step = _e[_d];
  27814. step.action(this.activeCamera);
  27815. }
  27816. // Render
  27817. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  27818. this._renderingManager.render(null, null, true, true);
  27819. this.onAfterDrawPhaseObservable.notifyObservers(this);
  27820. // After Camera Draw
  27821. for (var _f = 0, _g = this._afterCameraDrawStage; _f < _g.length; _f++) {
  27822. var step = _g[_f];
  27823. step.action(this.activeCamera);
  27824. }
  27825. // Finalize frame
  27826. if (this.postProcessManager) {
  27827. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  27828. }
  27829. // Reset some special arrays
  27830. this._renderTargets.reset();
  27831. this._alternateRendering = false;
  27832. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  27833. };
  27834. Scene.prototype._processSubCameras = function (camera) {
  27835. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  27836. this._renderForCamera(camera);
  27837. return;
  27838. }
  27839. // rig cameras
  27840. for (var index = 0; index < camera._rigCameras.length; index++) {
  27841. this._renderForCamera(camera._rigCameras[index], camera);
  27842. }
  27843. this.activeCamera = camera;
  27844. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  27845. };
  27846. Scene.prototype._checkIntersections = function () {
  27847. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  27848. var sourceMesh = this._meshesForIntersections.data[index];
  27849. if (!sourceMesh.actionManager) {
  27850. continue;
  27851. }
  27852. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  27853. var action = sourceMesh.actionManager.actions[actionIndex];
  27854. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27855. var parameters = action.getTriggerParameter();
  27856. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  27857. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  27858. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  27859. if (areIntersecting && currentIntersectionInProgress === -1) {
  27860. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  27861. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  27862. sourceMesh._intersectionsInProgress.push(otherMesh);
  27863. }
  27864. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27865. sourceMesh._intersectionsInProgress.push(otherMesh);
  27866. }
  27867. }
  27868. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  27869. //They intersected, and now they don't.
  27870. //is this trigger an exit trigger? execute an event.
  27871. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27872. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  27873. }
  27874. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  27875. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger, function (parameter) {
  27876. var parameterMesh = parameter instanceof BABYLON.AbstractMesh ? parameter : parameter.mesh;
  27877. return otherMesh === parameterMesh;
  27878. }) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27879. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  27880. }
  27881. }
  27882. }
  27883. }
  27884. }
  27885. };
  27886. /** @hidden */
  27887. Scene.prototype._advancePhysicsEngineStep = function (step) {
  27888. // Do nothing. Code will be replaced if physics engine component is referenced
  27889. };
  27890. /**
  27891. * Render the scene
  27892. * @param updateCameras defines a boolean indicating if cameras must update according to their inputs (true by default)
  27893. */
  27894. Scene.prototype.render = function (updateCameras) {
  27895. if (updateCameras === void 0) { updateCameras = true; }
  27896. if (this.isDisposed) {
  27897. return;
  27898. }
  27899. this._frameId++;
  27900. // Register components that have been associated lately to the scene.
  27901. this._registerTransientComponents();
  27902. this._activeParticles.fetchNewFrame();
  27903. this._totalVertices.fetchNewFrame();
  27904. this._activeIndices.fetchNewFrame();
  27905. this._activeBones.fetchNewFrame();
  27906. this._meshesForIntersections.reset();
  27907. this.resetCachedMaterial();
  27908. this.onBeforeAnimationsObservable.notifyObservers(this);
  27909. // Actions
  27910. if (this.actionManager) {
  27911. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);
  27912. }
  27913. if (this._engine.isDeterministicLockStep()) {
  27914. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) + this._timeAccumulator;
  27915. var defaultFPS = (60.0 / 1000.0);
  27916. var defaultFrameTime = this.getDeterministicFrameTime();
  27917. var stepsTaken = 0;
  27918. var maxSubSteps = this._engine.getLockstepMaxSteps();
  27919. var internalSteps = Math.floor(deltaTime / (1000 * defaultFPS));
  27920. internalSteps = Math.min(internalSteps, maxSubSteps);
  27921. do {
  27922. this.onBeforeStepObservable.notifyObservers(this);
  27923. // Animations
  27924. this._animationRatio = defaultFrameTime * defaultFPS;
  27925. this._animate();
  27926. this.onAfterAnimationsObservable.notifyObservers(this);
  27927. // Physics
  27928. this._advancePhysicsEngineStep(defaultFrameTime);
  27929. this.onAfterStepObservable.notifyObservers(this);
  27930. this._currentStepId++;
  27931. stepsTaken++;
  27932. deltaTime -= defaultFrameTime;
  27933. } while (deltaTime > 0 && stepsTaken < internalSteps);
  27934. this._timeAccumulator = deltaTime < 0 ? 0 : deltaTime;
  27935. }
  27936. else {
  27937. // Animations
  27938. var deltaTime = this.useConstantAnimationDeltaTime ? 16 : Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  27939. this._animationRatio = deltaTime * (60.0 / 1000.0);
  27940. this._animate();
  27941. this.onAfterAnimationsObservable.notifyObservers(this);
  27942. // Physics
  27943. this._advancePhysicsEngineStep(deltaTime);
  27944. }
  27945. // Before camera update steps
  27946. for (var _i = 0, _a = this._beforeCameraUpdateStage; _i < _a.length; _i++) {
  27947. var step = _a[_i];
  27948. step.action();
  27949. }
  27950. // Update Cameras
  27951. if (updateCameras) {
  27952. if (this.activeCameras.length > 0) {
  27953. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  27954. var camera = this.activeCameras[cameraIndex];
  27955. camera.update();
  27956. if (camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  27957. // rig cameras
  27958. for (var index = 0; index < camera._rigCameras.length; index++) {
  27959. camera._rigCameras[index].update();
  27960. }
  27961. }
  27962. }
  27963. }
  27964. else if (this.activeCamera) {
  27965. this.activeCamera.update();
  27966. if (this.activeCamera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  27967. // rig cameras
  27968. for (var index = 0; index < this.activeCamera._rigCameras.length; index++) {
  27969. this.activeCamera._rigCameras[index].update();
  27970. }
  27971. }
  27972. }
  27973. }
  27974. // Before render
  27975. this.onBeforeRenderObservable.notifyObservers(this);
  27976. // Customs render targets
  27977. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  27978. var engine = this.getEngine();
  27979. var currentActiveCamera = this.activeCamera;
  27980. if (this.renderTargetsEnabled) {
  27981. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  27982. this._intermediateRendering = true;
  27983. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  27984. var renderTarget = this.customRenderTargets[customIndex];
  27985. if (renderTarget._shouldRender()) {
  27986. this._renderId++;
  27987. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  27988. if (!this.activeCamera)
  27989. throw new Error("Active camera not set");
  27990. // Viewport
  27991. engine.setViewport(this.activeCamera.viewport);
  27992. // Camera
  27993. this.updateTransformMatrix();
  27994. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  27995. }
  27996. }
  27997. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  27998. this._intermediateRendering = false;
  27999. this._renderId++;
  28000. }
  28001. // Restore back buffer
  28002. if (this.customRenderTargets.length > 0) {
  28003. engine.restoreDefaultFramebuffer();
  28004. }
  28005. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  28006. this.activeCamera = currentActiveCamera;
  28007. for (var _b = 0, _c = this._beforeClearStage; _b < _c.length; _b++) {
  28008. var step = _c[_b];
  28009. step.action();
  28010. }
  28011. // Clear
  28012. if (this.autoClearDepthAndStencil || this.autoClear) {
  28013. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  28014. }
  28015. // Collects render targets from external components.
  28016. for (var _d = 0, _e = this._gatherRenderTargetsStage; _d < _e.length; _d++) {
  28017. var step = _e[_d];
  28018. step.action(this._renderTargets);
  28019. }
  28020. // Multi-cameras?
  28021. if (this.activeCameras.length > 0) {
  28022. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  28023. if (cameraIndex > 0) {
  28024. this._engine.clear(null, false, true, true);
  28025. }
  28026. this._processSubCameras(this.activeCameras[cameraIndex]);
  28027. }
  28028. }
  28029. else {
  28030. if (!this.activeCamera) {
  28031. throw new Error("No camera defined");
  28032. }
  28033. this._processSubCameras(this.activeCamera);
  28034. }
  28035. // Intersection checks
  28036. this._checkIntersections();
  28037. // Executes the after render stage actions.
  28038. for (var _f = 0, _g = this._afterRenderStage; _f < _g.length; _f++) {
  28039. var step = _g[_f];
  28040. step.action();
  28041. }
  28042. // After render
  28043. if (this.afterRender) {
  28044. this.afterRender();
  28045. }
  28046. this.onAfterRenderObservable.notifyObservers(this);
  28047. // Cleaning
  28048. if (this._toBeDisposed.length) {
  28049. for (var index = 0; index < this._toBeDisposed.length; index++) {
  28050. var data = this._toBeDisposed[index];
  28051. if (data) {
  28052. data.dispose();
  28053. }
  28054. }
  28055. this._toBeDisposed = [];
  28056. }
  28057. if (this.dumpNextRenderTargets) {
  28058. this.dumpNextRenderTargets = false;
  28059. }
  28060. this._activeBones.addCount(0, true);
  28061. this._activeIndices.addCount(0, true);
  28062. this._activeParticles.addCount(0, true);
  28063. };
  28064. /**
  28065. * Freeze all materials
  28066. * A frozen material will not be updatable but should be faster to render
  28067. */
  28068. Scene.prototype.freezeMaterials = function () {
  28069. for (var i = 0; i < this.materials.length; i++) {
  28070. this.materials[i].freeze();
  28071. }
  28072. };
  28073. /**
  28074. * Unfreeze all materials
  28075. * A frozen material will not be updatable but should be faster to render
  28076. */
  28077. Scene.prototype.unfreezeMaterials = function () {
  28078. for (var i = 0; i < this.materials.length; i++) {
  28079. this.materials[i].unfreeze();
  28080. }
  28081. };
  28082. /**
  28083. * Releases all held ressources
  28084. */
  28085. Scene.prototype.dispose = function () {
  28086. this.beforeRender = null;
  28087. this.afterRender = null;
  28088. this.skeletons = [];
  28089. this.morphTargetManagers = [];
  28090. this._transientComponents = [];
  28091. this._isReadyForMeshStage.clear();
  28092. this._beforeEvaluateActiveMeshStage.clear();
  28093. this._evaluateSubMeshStage.clear();
  28094. this._activeMeshStage.clear();
  28095. this._cameraDrawRenderTargetStage.clear();
  28096. this._beforeCameraDrawStage.clear();
  28097. this._beforeRenderingGroupDrawStage.clear();
  28098. this._beforeRenderingMeshStage.clear();
  28099. this._afterRenderingMeshStage.clear();
  28100. this._afterRenderingGroupDrawStage.clear();
  28101. this._afterCameraDrawStage.clear();
  28102. this._afterRenderStage.clear();
  28103. this._beforeCameraUpdateStage.clear();
  28104. this._beforeClearStage.clear();
  28105. this._gatherRenderTargetsStage.clear();
  28106. this._gatherActiveCameraRenderTargetsStage.clear();
  28107. this._pointerMoveStage.clear();
  28108. this._pointerDownStage.clear();
  28109. this._pointerUpStage.clear();
  28110. for (var _i = 0, _a = this._components; _i < _a.length; _i++) {
  28111. var component = _a[_i];
  28112. component.dispose();
  28113. }
  28114. this.importedMeshesFiles = new Array();
  28115. this.stopAllAnimations();
  28116. this.resetCachedMaterial();
  28117. // Smart arrays
  28118. if (this.activeCamera) {
  28119. this.activeCamera._activeMeshes.dispose();
  28120. this.activeCamera = null;
  28121. }
  28122. this._activeMeshes.dispose();
  28123. this._renderingManager.dispose();
  28124. this._processedMaterials.dispose();
  28125. this._activeParticleSystems.dispose();
  28126. this._activeSkeletons.dispose();
  28127. this._softwareSkinnedMeshes.dispose();
  28128. this._renderTargets.dispose();
  28129. this._registeredForLateAnimationBindings.dispose();
  28130. this._meshesForIntersections.dispose();
  28131. this._toBeDisposed = [];
  28132. // Abort active requests
  28133. for (var _b = 0, _c = this._activeRequests; _b < _c.length; _b++) {
  28134. var request = _c[_b];
  28135. request.abort();
  28136. }
  28137. // Events
  28138. this.onDisposeObservable.notifyObservers(this);
  28139. this.onDisposeObservable.clear();
  28140. this.onBeforeRenderObservable.clear();
  28141. this.onAfterRenderObservable.clear();
  28142. this.onBeforeRenderTargetsRenderObservable.clear();
  28143. this.onAfterRenderTargetsRenderObservable.clear();
  28144. this.onAfterStepObservable.clear();
  28145. this.onBeforeStepObservable.clear();
  28146. this.onBeforeActiveMeshesEvaluationObservable.clear();
  28147. this.onAfterActiveMeshesEvaluationObservable.clear();
  28148. this.onBeforeParticlesRenderingObservable.clear();
  28149. this.onAfterParticlesRenderingObservable.clear();
  28150. this.onBeforeDrawPhaseObservable.clear();
  28151. this.onAfterDrawPhaseObservable.clear();
  28152. this.onBeforeAnimationsObservable.clear();
  28153. this.onAfterAnimationsObservable.clear();
  28154. this.onDataLoadedObservable.clear();
  28155. this.onBeforeRenderingGroupObservable.clear();
  28156. this.onAfterRenderingGroupObservable.clear();
  28157. this.onMeshImportedObservable.clear();
  28158. this.detachControl();
  28159. // Detach cameras
  28160. var canvas = this._engine.getRenderingCanvas();
  28161. if (canvas) {
  28162. var index;
  28163. for (index = 0; index < this.cameras.length; index++) {
  28164. this.cameras[index].detachControl(canvas);
  28165. }
  28166. }
  28167. // Release animation groups
  28168. while (this.animationGroups.length) {
  28169. this.animationGroups[0].dispose();
  28170. }
  28171. // Release lights
  28172. while (this.lights.length) {
  28173. this.lights[0].dispose();
  28174. }
  28175. // Release meshes
  28176. while (this.meshes.length) {
  28177. this.meshes[0].dispose(true);
  28178. }
  28179. while (this.transformNodes.length) {
  28180. this.removeTransformNode(this.transformNodes[0]);
  28181. }
  28182. // Release cameras
  28183. while (this.cameras.length) {
  28184. this.cameras[0].dispose();
  28185. }
  28186. // Release materials
  28187. if (this.defaultMaterial) {
  28188. this.defaultMaterial.dispose();
  28189. }
  28190. while (this.multiMaterials.length) {
  28191. this.multiMaterials[0].dispose();
  28192. }
  28193. while (this.materials.length) {
  28194. this.materials[0].dispose();
  28195. }
  28196. // Release particles
  28197. while (this.particleSystems.length) {
  28198. this.particleSystems[0].dispose();
  28199. }
  28200. // Release postProcesses
  28201. while (this.postProcesses.length) {
  28202. this.postProcesses[0].dispose();
  28203. }
  28204. // Release textures
  28205. while (this.textures.length) {
  28206. this.textures[0].dispose();
  28207. }
  28208. // Release UBO
  28209. this._sceneUbo.dispose();
  28210. if (this._alternateSceneUbo) {
  28211. this._alternateSceneUbo.dispose();
  28212. }
  28213. // Post-processes
  28214. this.postProcessManager.dispose();
  28215. // Remove from engine
  28216. index = this._engine.scenes.indexOf(this);
  28217. if (index > -1) {
  28218. this._engine.scenes.splice(index, 1);
  28219. }
  28220. this._engine.wipeCaches(true);
  28221. this._isDisposed = true;
  28222. };
  28223. Object.defineProperty(Scene.prototype, "isDisposed", {
  28224. /**
  28225. * Gets if the scene is already disposed
  28226. */
  28227. get: function () {
  28228. return this._isDisposed;
  28229. },
  28230. enumerable: true,
  28231. configurable: true
  28232. });
  28233. /**
  28234. * Call this function to reduce memory footprint of the scene.
  28235. * Vertex buffers will not store CPU data anymore (this will prevent picking, collisions or physics to work correctly)
  28236. */
  28237. Scene.prototype.clearCachedVertexData = function () {
  28238. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28239. var mesh = this.meshes[meshIndex];
  28240. var geometry = mesh.geometry;
  28241. if (geometry) {
  28242. geometry._indices = [];
  28243. for (var vbName in geometry._vertexBuffers) {
  28244. if (!geometry._vertexBuffers.hasOwnProperty(vbName)) {
  28245. continue;
  28246. }
  28247. geometry._vertexBuffers[vbName]._buffer._data = null;
  28248. }
  28249. }
  28250. }
  28251. };
  28252. /**
  28253. * This function will remove the local cached buffer data from texture.
  28254. * It will save memory but will prevent the texture from being rebuilt
  28255. */
  28256. Scene.prototype.cleanCachedTextureBuffer = function () {
  28257. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  28258. var baseTexture = _a[_i];
  28259. var buffer = baseTexture._buffer;
  28260. if (buffer) {
  28261. baseTexture._buffer = null;
  28262. }
  28263. }
  28264. };
  28265. /**
  28266. * Get the world extend vectors with an optional filter
  28267. *
  28268. * @param filterPredicate the predicate - which meshes should be included when calculating the world size
  28269. * @returns {{ min: Vector3; max: Vector3 }} min and max vectors
  28270. */
  28271. Scene.prototype.getWorldExtends = function (filterPredicate) {
  28272. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  28273. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  28274. filterPredicate = filterPredicate || (function () { return true; });
  28275. this.meshes.filter(filterPredicate).forEach(function (mesh) {
  28276. mesh.computeWorldMatrix(true);
  28277. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  28278. return;
  28279. }
  28280. var boundingInfo = mesh.getBoundingInfo();
  28281. var minBox = boundingInfo.boundingBox.minimumWorld;
  28282. var maxBox = boundingInfo.boundingBox.maximumWorld;
  28283. BABYLON.Tools.CheckExtends(minBox, min, max);
  28284. BABYLON.Tools.CheckExtends(maxBox, min, max);
  28285. });
  28286. return {
  28287. min: min,
  28288. max: max
  28289. };
  28290. };
  28291. // Picking
  28292. /**
  28293. * Creates a ray that can be used to pick in the scene
  28294. * @param x defines the x coordinate of the origin (on-screen)
  28295. * @param y defines the y coordinate of the origin (on-screen)
  28296. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  28297. * @param camera defines the camera to use for the picking
  28298. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  28299. * @returns a Ray
  28300. */
  28301. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  28302. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  28303. var result = BABYLON.Ray.Zero();
  28304. this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace);
  28305. return result;
  28306. };
  28307. /**
  28308. * Creates a ray that can be used to pick in the scene
  28309. * @param x defines the x coordinate of the origin (on-screen)
  28310. * @param y defines the y coordinate of the origin (on-screen)
  28311. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  28312. * @param result defines the ray where to store the picking ray
  28313. * @param camera defines the camera to use for the picking
  28314. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  28315. * @returns the current scene
  28316. */
  28317. Scene.prototype.createPickingRayToRef = function (x, y, world, result, camera, cameraViewSpace) {
  28318. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  28319. var engine = this._engine;
  28320. if (!camera) {
  28321. if (!this.activeCamera)
  28322. throw new Error("Active camera not set");
  28323. camera = this.activeCamera;
  28324. }
  28325. var cameraViewport = camera.viewport;
  28326. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  28327. // Moving coordinates to local viewport world
  28328. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  28329. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  28330. result.update(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  28331. return this;
  28332. };
  28333. /**
  28334. * Creates a ray that can be used to pick in the scene
  28335. * @param x defines the x coordinate of the origin (on-screen)
  28336. * @param y defines the y coordinate of the origin (on-screen)
  28337. * @param camera defines the camera to use for the picking
  28338. * @returns a Ray
  28339. */
  28340. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  28341. var result = BABYLON.Ray.Zero();
  28342. this.createPickingRayInCameraSpaceToRef(x, y, result, camera);
  28343. return result;
  28344. };
  28345. /**
  28346. * Creates a ray that can be used to pick in the scene
  28347. * @param x defines the x coordinate of the origin (on-screen)
  28348. * @param y defines the y coordinate of the origin (on-screen)
  28349. * @param result defines the ray where to store the picking ray
  28350. * @param camera defines the camera to use for the picking
  28351. * @returns the current scene
  28352. */
  28353. Scene.prototype.createPickingRayInCameraSpaceToRef = function (x, y, result, camera) {
  28354. if (!BABYLON.PickingInfo) {
  28355. return this;
  28356. }
  28357. var engine = this._engine;
  28358. if (!camera) {
  28359. if (!this.activeCamera)
  28360. throw new Error("Active camera not set");
  28361. camera = this.activeCamera;
  28362. }
  28363. var cameraViewport = camera.viewport;
  28364. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  28365. var identity = BABYLON.Matrix.Identity();
  28366. // Moving coordinates to local viewport world
  28367. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  28368. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  28369. result.update(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  28370. return this;
  28371. };
  28372. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  28373. if (!BABYLON.PickingInfo) {
  28374. return null;
  28375. }
  28376. var pickingInfo = null;
  28377. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28378. var mesh = this.meshes[meshIndex];
  28379. if (predicate) {
  28380. if (!predicate(mesh)) {
  28381. continue;
  28382. }
  28383. }
  28384. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  28385. continue;
  28386. }
  28387. var world = mesh.getWorldMatrix();
  28388. var ray = rayFunction(world);
  28389. var result = mesh.intersects(ray, fastCheck);
  28390. if (!result || !result.hit)
  28391. continue;
  28392. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  28393. continue;
  28394. pickingInfo = result;
  28395. if (fastCheck) {
  28396. break;
  28397. }
  28398. }
  28399. return pickingInfo || new BABYLON.PickingInfo();
  28400. };
  28401. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  28402. if (!BABYLON.PickingInfo) {
  28403. return null;
  28404. }
  28405. var pickingInfos = new Array();
  28406. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28407. var mesh = this.meshes[meshIndex];
  28408. if (predicate) {
  28409. if (!predicate(mesh)) {
  28410. continue;
  28411. }
  28412. }
  28413. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  28414. continue;
  28415. }
  28416. var world = mesh.getWorldMatrix();
  28417. var ray = rayFunction(world);
  28418. var result = mesh.intersects(ray, false);
  28419. if (!result || !result.hit)
  28420. continue;
  28421. pickingInfos.push(result);
  28422. }
  28423. return pickingInfos;
  28424. };
  28425. /** Launch a ray to try to pick a mesh in the scene
  28426. * @param x position on screen
  28427. * @param y position on screen
  28428. * @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
  28429. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  28430. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28431. * @returns a PickingInfo
  28432. */
  28433. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  28434. var _this = this;
  28435. if (!BABYLON.PickingInfo) {
  28436. return null;
  28437. }
  28438. var result = this._internalPick(function (world) {
  28439. _this.createPickingRayToRef(x, y, world, _this._tempPickingRay, camera || null);
  28440. return _this._tempPickingRay;
  28441. }, predicate, fastCheck);
  28442. if (result) {
  28443. result.ray = this.createPickingRay(x, y, BABYLON.Matrix.Identity(), camera || null);
  28444. }
  28445. return result;
  28446. };
  28447. /** Use the given ray to pick a mesh in the scene
  28448. * @param ray The ray to use to pick meshes
  28449. * @param predicate Predicate function used to determine eligible meshes. Can be set to null. In this case, a mesh must have isPickable set to true
  28450. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null
  28451. * @returns a PickingInfo
  28452. */
  28453. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  28454. var _this = this;
  28455. var result = this._internalPick(function (world) {
  28456. if (!_this._pickWithRayInverseMatrix) {
  28457. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  28458. }
  28459. world.invertToRef(_this._pickWithRayInverseMatrix);
  28460. if (!_this._cachedRayForTransform) {
  28461. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  28462. }
  28463. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  28464. return _this._cachedRayForTransform;
  28465. }, predicate, fastCheck);
  28466. if (result) {
  28467. result.ray = ray;
  28468. }
  28469. return result;
  28470. };
  28471. /**
  28472. * Launch a ray to try to pick a mesh in the scene
  28473. * @param x X position on screen
  28474. * @param y Y position on screen
  28475. * @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
  28476. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28477. * @returns an array of PickingInfo
  28478. */
  28479. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  28480. var _this = this;
  28481. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);
  28482. };
  28483. /**
  28484. * Launch a ray to try to pick a mesh in the scene
  28485. * @param ray Ray to use
  28486. * @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
  28487. * @returns an array of PickingInfo
  28488. */
  28489. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  28490. var _this = this;
  28491. return this._internalMultiPick(function (world) {
  28492. if (!_this._pickWithRayInverseMatrix) {
  28493. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  28494. }
  28495. world.invertToRef(_this._pickWithRayInverseMatrix);
  28496. if (!_this._cachedRayForTransform) {
  28497. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  28498. }
  28499. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  28500. return _this._cachedRayForTransform;
  28501. }, predicate);
  28502. };
  28503. /**
  28504. * Force the value of meshUnderPointer
  28505. * @param mesh defines the mesh to use
  28506. */
  28507. Scene.prototype.setPointerOverMesh = function (mesh) {
  28508. if (this._pointerOverMesh === mesh) {
  28509. return;
  28510. }
  28511. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  28512. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  28513. }
  28514. this._pointerOverMesh = mesh;
  28515. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  28516. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  28517. }
  28518. };
  28519. /**
  28520. * Gets the mesh under the pointer
  28521. * @returns a Mesh or null if no mesh is under the pointer
  28522. */
  28523. Scene.prototype.getPointerOverMesh = function () {
  28524. return this._pointerOverMesh;
  28525. };
  28526. // Misc.
  28527. /** @hidden */
  28528. Scene.prototype._rebuildGeometries = function () {
  28529. for (var _i = 0, _a = this.geometries; _i < _a.length; _i++) {
  28530. var geometry = _a[_i];
  28531. geometry._rebuild();
  28532. }
  28533. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  28534. var mesh = _c[_b];
  28535. mesh._rebuild();
  28536. }
  28537. if (this.postProcessManager) {
  28538. this.postProcessManager._rebuild();
  28539. }
  28540. for (var _d = 0, _e = this._components; _d < _e.length; _d++) {
  28541. var component = _e[_d];
  28542. component.rebuild();
  28543. }
  28544. for (var _f = 0, _g = this.particleSystems; _f < _g.length; _f++) {
  28545. var system = _g[_f];
  28546. system.rebuild();
  28547. }
  28548. };
  28549. /** @hidden */
  28550. Scene.prototype._rebuildTextures = function () {
  28551. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  28552. var texture = _a[_i];
  28553. texture._rebuild();
  28554. }
  28555. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  28556. };
  28557. // Tags
  28558. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  28559. if (tagsQuery === undefined) {
  28560. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  28561. return list;
  28562. }
  28563. var listByTags = [];
  28564. forEach = forEach || (function (item) { return; });
  28565. for (var i in list) {
  28566. var item = list[i];
  28567. if (BABYLON.Tags && BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  28568. listByTags.push(item);
  28569. forEach(item);
  28570. }
  28571. }
  28572. return listByTags;
  28573. };
  28574. /**
  28575. * Get a list of meshes by tags
  28576. * @param tagsQuery defines the tags query to use
  28577. * @param forEach defines a predicate used to filter results
  28578. * @returns an array of Mesh
  28579. */
  28580. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  28581. return this._getByTags(this.meshes, tagsQuery, forEach);
  28582. };
  28583. /**
  28584. * Get a list of cameras by tags
  28585. * @param tagsQuery defines the tags query to use
  28586. * @param forEach defines a predicate used to filter results
  28587. * @returns an array of Camera
  28588. */
  28589. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  28590. return this._getByTags(this.cameras, tagsQuery, forEach);
  28591. };
  28592. /**
  28593. * Get a list of lights by tags
  28594. * @param tagsQuery defines the tags query to use
  28595. * @param forEach defines a predicate used to filter results
  28596. * @returns an array of Light
  28597. */
  28598. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  28599. return this._getByTags(this.lights, tagsQuery, forEach);
  28600. };
  28601. /**
  28602. * Get a list of materials by tags
  28603. * @param tagsQuery defines the tags query to use
  28604. * @param forEach defines a predicate used to filter results
  28605. * @returns an array of Material
  28606. */
  28607. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  28608. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  28609. };
  28610. /**
  28611. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  28612. * This allowed control for front to back rendering or reversly depending of the special needs.
  28613. *
  28614. * @param renderingGroupId The rendering group id corresponding to its index
  28615. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  28616. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  28617. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  28618. */
  28619. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  28620. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  28621. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  28622. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  28623. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  28624. };
  28625. /**
  28626. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  28627. *
  28628. * @param renderingGroupId The rendering group id corresponding to its index
  28629. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  28630. * @param depth Automatically clears depth between groups if true and autoClear is true.
  28631. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  28632. */
  28633. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  28634. if (depth === void 0) { depth = true; }
  28635. if (stencil === void 0) { stencil = true; }
  28636. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  28637. };
  28638. /**
  28639. * Gets the current auto clear configuration for one rendering group of the rendering
  28640. * manager.
  28641. * @param index the rendering group index to get the information for
  28642. * @returns The auto clear setup for the requested rendering group
  28643. */
  28644. Scene.prototype.getAutoClearDepthStencilSetup = function (index) {
  28645. return this._renderingManager.getAutoClearDepthStencilSetup(index);
  28646. };
  28647. Object.defineProperty(Scene.prototype, "blockMaterialDirtyMechanism", {
  28648. /** Gets or sets a boolean blocking all the calls to markAllMaterialsAsDirty (ie. the materials won't be updated if they are out of sync) */
  28649. get: function () {
  28650. return this._blockMaterialDirtyMechanism;
  28651. },
  28652. set: function (value) {
  28653. if (this._blockMaterialDirtyMechanism === value) {
  28654. return;
  28655. }
  28656. this._blockMaterialDirtyMechanism = value;
  28657. if (!value) { // Do a complete update
  28658. this.markAllMaterialsAsDirty(BABYLON.Material.AllDirtyFlag);
  28659. }
  28660. },
  28661. enumerable: true,
  28662. configurable: true
  28663. });
  28664. /**
  28665. * Will flag all materials as dirty to trigger new shader compilation
  28666. * @param flag defines the flag used to specify which material part must be marked as dirty
  28667. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  28668. */
  28669. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  28670. if (this._blockMaterialDirtyMechanism) {
  28671. return;
  28672. }
  28673. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  28674. var material = _a[_i];
  28675. if (predicate && !predicate(material)) {
  28676. continue;
  28677. }
  28678. material.markAsDirty(flag);
  28679. }
  28680. };
  28681. /** @hidden */
  28682. Scene.prototype._loadFile = function (url, onSuccess, onProgress, useDatabase, useArrayBuffer, onError) {
  28683. var _this = this;
  28684. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, useDatabase ? this.database : undefined, useArrayBuffer, onError);
  28685. this._activeRequests.push(request);
  28686. request.onCompleteObservable.add(function (request) {
  28687. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  28688. });
  28689. return request;
  28690. };
  28691. /** @hidden */
  28692. Scene.prototype._loadFileAsync = function (url, useDatabase, useArrayBuffer) {
  28693. var _this = this;
  28694. return new Promise(function (resolve, reject) {
  28695. _this._loadFile(url, function (data) {
  28696. resolve(data);
  28697. }, undefined, useDatabase, useArrayBuffer, function (request, exception) {
  28698. reject(exception);
  28699. });
  28700. });
  28701. };
  28702. // Statics
  28703. Scene._uniqueIdCounter = 0;
  28704. /** The fog is deactivated */
  28705. Scene.FOGMODE_NONE = 0;
  28706. /** The fog density is following an exponential function */
  28707. Scene.FOGMODE_EXP = 1;
  28708. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  28709. Scene.FOGMODE_EXP2 = 2;
  28710. /** The fog density is following a linear function. */
  28711. Scene.FOGMODE_LINEAR = 3;
  28712. /**
  28713. * Gets or sets the minimum deltatime when deterministic lock step is enabled
  28714. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  28715. */
  28716. Scene.MinDeltaTime = 1.0;
  28717. /**
  28718. * Gets or sets the maximum deltatime when deterministic lock step is enabled
  28719. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  28720. */
  28721. Scene.MaxDeltaTime = 1000.0;
  28722. /** The distance in pixel that you have to move to prevent some events */
  28723. Scene.DragMovementThreshold = 10; // in pixels
  28724. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  28725. Scene.LongPressDelay = 500; // in milliseconds
  28726. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  28727. Scene.DoubleClickDelay = 300; // in milliseconds
  28728. /** If you need to check double click without raising a single click at first click, enable this flag */
  28729. Scene.ExclusiveDoubleClickMode = false;
  28730. return Scene;
  28731. }(BABYLON.AbstractScene));
  28732. BABYLON.Scene = Scene;
  28733. })(BABYLON || (BABYLON = {}));
  28734. //# sourceMappingURL=babylon.scene.js.map
  28735. var BABYLON;
  28736. (function (BABYLON) {
  28737. /**
  28738. * Set of assets to keep when moving a scene into an asset container.
  28739. */
  28740. var KeepAssets = /** @class */ (function (_super) {
  28741. __extends(KeepAssets, _super);
  28742. function KeepAssets() {
  28743. return _super !== null && _super.apply(this, arguments) || this;
  28744. }
  28745. return KeepAssets;
  28746. }(BABYLON.AbstractScene));
  28747. BABYLON.KeepAssets = KeepAssets;
  28748. /**
  28749. * Container with a set of assets that can be added or removed from a scene.
  28750. */
  28751. var AssetContainer = /** @class */ (function (_super) {
  28752. __extends(AssetContainer, _super);
  28753. /**
  28754. * Instantiates an AssetContainer.
  28755. * @param scene The scene the AssetContainer belongs to.
  28756. */
  28757. function AssetContainer(scene) {
  28758. var _this = _super.call(this) || this;
  28759. _this.scene = scene;
  28760. return _this;
  28761. }
  28762. /**
  28763. * Adds all the assets from the container to the scene.
  28764. */
  28765. AssetContainer.prototype.addAllToScene = function () {
  28766. var _this = this;
  28767. this.cameras.forEach(function (o) {
  28768. _this.scene.addCamera(o);
  28769. });
  28770. this.lights.forEach(function (o) {
  28771. _this.scene.addLight(o);
  28772. });
  28773. this.meshes.forEach(function (o) {
  28774. _this.scene.addMesh(o);
  28775. });
  28776. this.skeletons.forEach(function (o) {
  28777. _this.scene.addSkeleton(o);
  28778. });
  28779. this.animations.forEach(function (o) {
  28780. _this.scene.addAnimation(o);
  28781. });
  28782. this.animationGroups.forEach(function (o) {
  28783. _this.scene.addAnimationGroup(o);
  28784. });
  28785. this.multiMaterials.forEach(function (o) {
  28786. _this.scene.addMultiMaterial(o);
  28787. });
  28788. this.materials.forEach(function (o) {
  28789. _this.scene.addMaterial(o);
  28790. });
  28791. this.morphTargetManagers.forEach(function (o) {
  28792. _this.scene.addMorphTargetManager(o);
  28793. });
  28794. this.geometries.forEach(function (o) {
  28795. _this.scene.addGeometry(o);
  28796. });
  28797. this.transformNodes.forEach(function (o) {
  28798. _this.scene.addTransformNode(o);
  28799. });
  28800. this.actionManagers.forEach(function (o) {
  28801. _this.scene.addActionManager(o);
  28802. });
  28803. this.textures.forEach(function (o) {
  28804. _this.scene.addTexture(o);
  28805. });
  28806. for (var _i = 0, _a = this.scene._serializableComponents; _i < _a.length; _i++) {
  28807. var component = _a[_i];
  28808. component.addFromContainer(this.scene);
  28809. }
  28810. };
  28811. /**
  28812. * Removes all the assets in the container from the scene
  28813. */
  28814. AssetContainer.prototype.removeAllFromScene = function () {
  28815. var _this = this;
  28816. this.cameras.forEach(function (o) {
  28817. _this.scene.removeCamera(o);
  28818. });
  28819. this.lights.forEach(function (o) {
  28820. _this.scene.removeLight(o);
  28821. });
  28822. this.meshes.forEach(function (o) {
  28823. _this.scene.removeMesh(o);
  28824. });
  28825. this.skeletons.forEach(function (o) {
  28826. _this.scene.removeSkeleton(o);
  28827. });
  28828. this.animations.forEach(function (o) {
  28829. _this.scene.removeAnimation(o);
  28830. });
  28831. this.animationGroups.forEach(function (o) {
  28832. _this.scene.removeAnimationGroup(o);
  28833. });
  28834. this.multiMaterials.forEach(function (o) {
  28835. _this.scene.removeMultiMaterial(o);
  28836. });
  28837. this.materials.forEach(function (o) {
  28838. _this.scene.removeMaterial(o);
  28839. });
  28840. this.morphTargetManagers.forEach(function (o) {
  28841. _this.scene.removeMorphTargetManager(o);
  28842. });
  28843. this.geometries.forEach(function (o) {
  28844. _this.scene.removeGeometry(o);
  28845. });
  28846. this.transformNodes.forEach(function (o) {
  28847. _this.scene.removeTransformNode(o);
  28848. });
  28849. this.actionManagers.forEach(function (o) {
  28850. _this.scene.removeActionManager(o);
  28851. });
  28852. this.textures.forEach(function (o) {
  28853. _this.scene.removeTexture(o);
  28854. });
  28855. for (var _i = 0, _a = this.scene._serializableComponents; _i < _a.length; _i++) {
  28856. var component = _a[_i];
  28857. component.removeFromContainer(this.scene);
  28858. }
  28859. };
  28860. AssetContainer.prototype._moveAssets = function (sourceAssets, targetAssets, keepAssets) {
  28861. if (!sourceAssets) {
  28862. return;
  28863. }
  28864. for (var _i = 0, sourceAssets_1 = sourceAssets; _i < sourceAssets_1.length; _i++) {
  28865. var asset = sourceAssets_1[_i];
  28866. var move = true;
  28867. if (keepAssets) {
  28868. for (var _a = 0, keepAssets_1 = keepAssets; _a < keepAssets_1.length; _a++) {
  28869. var keepAsset = keepAssets_1[_a];
  28870. if (asset === keepAsset) {
  28871. move = false;
  28872. break;
  28873. }
  28874. }
  28875. }
  28876. if (move) {
  28877. targetAssets.push(asset);
  28878. }
  28879. }
  28880. };
  28881. /**
  28882. * Removes all the assets contained in the scene and adds them to the container.
  28883. * @param keepAssets Set of assets to keep in the scene. (default: empty)
  28884. */
  28885. AssetContainer.prototype.moveAllFromScene = function (keepAssets) {
  28886. if (keepAssets === undefined) {
  28887. keepAssets = new KeepAssets();
  28888. }
  28889. for (var key in this) {
  28890. if (this.hasOwnProperty(key)) {
  28891. this[key] = this[key] || [];
  28892. this._moveAssets(this.scene[key], this[key], keepAssets[key]);
  28893. }
  28894. }
  28895. this.removeAllFromScene();
  28896. };
  28897. /**
  28898. * 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.
  28899. * @returns the root mesh
  28900. */
  28901. AssetContainer.prototype.createRootMesh = function () {
  28902. var rootMesh = new BABYLON.Mesh("assetContainerRootMesh", this.scene);
  28903. this.meshes.forEach(function (m) {
  28904. if (!m.parent) {
  28905. rootMesh.addChild(m);
  28906. }
  28907. });
  28908. this.meshes.unshift(rootMesh);
  28909. return rootMesh;
  28910. };
  28911. return AssetContainer;
  28912. }(BABYLON.AbstractScene));
  28913. BABYLON.AssetContainer = AssetContainer;
  28914. })(BABYLON || (BABYLON = {}));
  28915. //# sourceMappingURL=babylon.assetContainer.js.map
  28916. var BABYLON;
  28917. (function (BABYLON) {
  28918. var Buffer = /** @class */ (function () {
  28919. /**
  28920. * Constructor
  28921. * @param engine the engine
  28922. * @param data the data to use for this buffer
  28923. * @param updatable whether the data is updatable
  28924. * @param stride the stride (optional)
  28925. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  28926. * @param instanced whether the buffer is instanced (optional)
  28927. * @param useBytes set to true if the stride in in bytes (optional)
  28928. */
  28929. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes) {
  28930. if (stride === void 0) { stride = 0; }
  28931. if (postponeInternalCreation === void 0) { postponeInternalCreation = false; }
  28932. if (instanced === void 0) { instanced = false; }
  28933. if (useBytes === void 0) { useBytes = false; }
  28934. if (engine instanceof BABYLON.Mesh) { // old versions of BABYLON.VertexBuffer accepted 'mesh' instead of 'engine'
  28935. this._engine = engine.getScene().getEngine();
  28936. }
  28937. else {
  28938. this._engine = engine;
  28939. }
  28940. this._updatable = updatable;
  28941. this._instanced = instanced;
  28942. this._data = data;
  28943. this.byteStride = useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT;
  28944. if (!postponeInternalCreation) { // by default
  28945. this.create();
  28946. }
  28947. }
  28948. /**
  28949. * Create a new {BABYLON.VertexBuffer} based on the current buffer
  28950. * @param kind defines the vertex buffer kind (position, normal, etc.)
  28951. * @param offset defines offset in the buffer (0 by default)
  28952. * @param size defines the size in floats of attributes (position is 3 for instance)
  28953. * @param stride defines the stride size in floats in the buffer (the offset to apply to reach next value when data is interleaved)
  28954. * @param instanced defines if the vertex buffer contains indexed data
  28955. * @param useBytes defines if the offset and stride are in bytes
  28956. * @returns the new vertex buffer
  28957. */
  28958. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride, instanced, useBytes) {
  28959. if (useBytes === void 0) { useBytes = false; }
  28960. var byteOffset = useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT;
  28961. var byteStride = stride ? (useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT) : this.byteStride;
  28962. // a lot of these parameters are ignored as they are overriden by the buffer
  28963. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, byteStride, instanced === undefined ? this._instanced : instanced, byteOffset, size, undefined, undefined, true);
  28964. };
  28965. // Properties
  28966. Buffer.prototype.isUpdatable = function () {
  28967. return this._updatable;
  28968. };
  28969. Buffer.prototype.getData = function () {
  28970. return this._data;
  28971. };
  28972. Buffer.prototype.getBuffer = function () {
  28973. return this._buffer;
  28974. };
  28975. /**
  28976. * Gets the stride in float32 units (i.e. byte stride / 4).
  28977. * May not be an integer if the byte stride is not divisible by 4.
  28978. * DEPRECATED. Use byteStride instead.
  28979. * @returns the stride in float32 units
  28980. */
  28981. Buffer.prototype.getStrideSize = function () {
  28982. return this.byteStride / Float32Array.BYTES_PER_ELEMENT;
  28983. };
  28984. // Methods
  28985. Buffer.prototype.create = function (data) {
  28986. if (data === void 0) { data = null; }
  28987. if (!data && this._buffer) {
  28988. return; // nothing to do
  28989. }
  28990. data = data || this._data;
  28991. if (!data) {
  28992. return;
  28993. }
  28994. if (!this._buffer) { // create buffer
  28995. if (this._updatable) {
  28996. this._buffer = this._engine.createDynamicVertexBuffer(data);
  28997. this._data = data;
  28998. }
  28999. else {
  29000. this._buffer = this._engine.createVertexBuffer(data);
  29001. }
  29002. }
  29003. else if (this._updatable) { // update buffer
  29004. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  29005. this._data = data;
  29006. }
  29007. };
  29008. /** @hidden */
  29009. Buffer.prototype._rebuild = function () {
  29010. this._buffer = null;
  29011. this.create(this._data);
  29012. };
  29013. Buffer.prototype.update = function (data) {
  29014. this.create(data);
  29015. };
  29016. /**
  29017. * Updates the data directly.
  29018. * @param data the new data
  29019. * @param offset the new offset
  29020. * @param vertexCount the vertex count (optional)
  29021. * @param useBytes set to true if the offset is in bytes
  29022. */
  29023. Buffer.prototype.updateDirectly = function (data, offset, vertexCount, useBytes) {
  29024. if (useBytes === void 0) { useBytes = false; }
  29025. if (!this._buffer) {
  29026. return;
  29027. }
  29028. if (this._updatable) { // update buffer
  29029. this._engine.updateDynamicVertexBuffer(this._buffer, data, useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT, (vertexCount ? vertexCount * this.byteStride : undefined));
  29030. this._data = null;
  29031. }
  29032. };
  29033. Buffer.prototype.dispose = function () {
  29034. if (!this._buffer) {
  29035. return;
  29036. }
  29037. if (this._engine._releaseBuffer(this._buffer)) {
  29038. this._buffer = null;
  29039. }
  29040. };
  29041. return Buffer;
  29042. }());
  29043. BABYLON.Buffer = Buffer;
  29044. })(BABYLON || (BABYLON = {}));
  29045. //# sourceMappingURL=babylon.buffer.js.map
  29046. var BABYLON;
  29047. (function (BABYLON) {
  29048. var VertexBuffer = /** @class */ (function () {
  29049. /**
  29050. * Constructor
  29051. * @param engine the engine
  29052. * @param data the data to use for this vertex buffer
  29053. * @param kind the vertex buffer kind
  29054. * @param updatable whether the data is updatable
  29055. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  29056. * @param stride the stride (optional)
  29057. * @param instanced whether the buffer is instanced (optional)
  29058. * @param offset the offset of the data (optional)
  29059. * @param size the number of components (optional)
  29060. * @param type the type of the component (optional)
  29061. * @param normalized whether the data contains normalized data (optional)
  29062. * @param useBytes set to true if stride and offset are in bytes (optional)
  29063. */
  29064. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size, type, normalized, useBytes) {
  29065. if (normalized === void 0) { normalized = false; }
  29066. if (useBytes === void 0) { useBytes = false; }
  29067. if (data instanceof BABYLON.Buffer) {
  29068. this._buffer = data;
  29069. this._ownsBuffer = false;
  29070. }
  29071. else {
  29072. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes);
  29073. this._ownsBuffer = true;
  29074. }
  29075. this._kind = kind;
  29076. if (type == undefined) {
  29077. var data_1 = this.getData();
  29078. this.type = VertexBuffer.FLOAT;
  29079. if (data_1 instanceof Int8Array)
  29080. this.type = VertexBuffer.BYTE;
  29081. else if (data_1 instanceof Uint8Array)
  29082. this.type = VertexBuffer.UNSIGNED_BYTE;
  29083. else if (data_1 instanceof Int16Array)
  29084. this.type = VertexBuffer.SHORT;
  29085. else if (data_1 instanceof Uint16Array)
  29086. this.type = VertexBuffer.UNSIGNED_SHORT;
  29087. else if (data_1 instanceof Int32Array)
  29088. this.type = VertexBuffer.INT;
  29089. else if (data_1 instanceof Uint32Array)
  29090. this.type = VertexBuffer.UNSIGNED_INT;
  29091. }
  29092. else {
  29093. this.type = type;
  29094. }
  29095. var typeByteLength = VertexBuffer.GetTypeByteLength(this.type);
  29096. if (useBytes) {
  29097. this._size = size || (stride ? (stride / typeByteLength) : VertexBuffer.DeduceStride(kind));
  29098. this.byteStride = stride || this._buffer.byteStride || (this._size * typeByteLength);
  29099. this.byteOffset = offset || 0;
  29100. }
  29101. else {
  29102. this._size = size || stride || VertexBuffer.DeduceStride(kind);
  29103. this.byteStride = stride ? (stride * typeByteLength) : (this._buffer.byteStride || (this._size * typeByteLength));
  29104. this.byteOffset = (offset || 0) * typeByteLength;
  29105. }
  29106. this.normalized = normalized;
  29107. this._instanced = instanced !== undefined ? instanced : false;
  29108. this._instanceDivisor = instanced ? 1 : 0;
  29109. }
  29110. Object.defineProperty(VertexBuffer.prototype, "instanceDivisor", {
  29111. /**
  29112. * Gets or sets the instance divisor when in instanced mode
  29113. */
  29114. get: function () {
  29115. return this._instanceDivisor;
  29116. },
  29117. set: function (value) {
  29118. this._instanceDivisor = value;
  29119. if (value == 0) {
  29120. this._instanced = false;
  29121. }
  29122. else {
  29123. this._instanced = true;
  29124. }
  29125. },
  29126. enumerable: true,
  29127. configurable: true
  29128. });
  29129. /** @hidden */
  29130. VertexBuffer.prototype._rebuild = function () {
  29131. if (!this._buffer) {
  29132. return;
  29133. }
  29134. this._buffer._rebuild();
  29135. };
  29136. /**
  29137. * Returns the kind of the VertexBuffer (string).
  29138. */
  29139. VertexBuffer.prototype.getKind = function () {
  29140. return this._kind;
  29141. };
  29142. // Properties
  29143. /**
  29144. * Boolean : is the VertexBuffer updatable ?
  29145. */
  29146. VertexBuffer.prototype.isUpdatable = function () {
  29147. return this._buffer.isUpdatable();
  29148. };
  29149. /**
  29150. * Returns an array of numbers or a typed array containing the VertexBuffer data.
  29151. */
  29152. VertexBuffer.prototype.getData = function () {
  29153. return this._buffer.getData();
  29154. };
  29155. /**
  29156. * Returns the WebGLBuffer associated to the VertexBuffer.
  29157. */
  29158. VertexBuffer.prototype.getBuffer = function () {
  29159. return this._buffer.getBuffer();
  29160. };
  29161. /**
  29162. * Returns the stride as a multiple of the type byte length.
  29163. * DEPRECATED. Use byteStride instead.
  29164. */
  29165. VertexBuffer.prototype.getStrideSize = function () {
  29166. return this.byteStride / VertexBuffer.GetTypeByteLength(this.type);
  29167. };
  29168. /**
  29169. * Returns the offset as a multiple of the type byte length.
  29170. * DEPRECATED. Use byteOffset instead.
  29171. */
  29172. VertexBuffer.prototype.getOffset = function () {
  29173. return this.byteOffset / VertexBuffer.GetTypeByteLength(this.type);
  29174. };
  29175. /**
  29176. * Returns the number of components per vertex attribute (integer).
  29177. */
  29178. VertexBuffer.prototype.getSize = function () {
  29179. return this._size;
  29180. };
  29181. /**
  29182. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  29183. */
  29184. VertexBuffer.prototype.getIsInstanced = function () {
  29185. return this._instanced;
  29186. };
  29187. /**
  29188. * Returns the instancing divisor, zero for non-instanced (integer).
  29189. */
  29190. VertexBuffer.prototype.getInstanceDivisor = function () {
  29191. return this._instanceDivisor;
  29192. };
  29193. // Methods
  29194. /**
  29195. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  29196. * Returns the created WebGLBuffer.
  29197. */
  29198. VertexBuffer.prototype.create = function (data) {
  29199. return this._buffer.create(data);
  29200. };
  29201. /**
  29202. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  29203. * This function will create a new buffer if the current one is not updatable
  29204. * Returns the updated WebGLBuffer.
  29205. */
  29206. VertexBuffer.prototype.update = function (data) {
  29207. return this._buffer.update(data);
  29208. };
  29209. /**
  29210. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  29211. * Returns the directly updated WebGLBuffer.
  29212. * @param data the new data
  29213. * @param offset the new offset
  29214. * @param useBytes set to true if the offset is in bytes
  29215. */
  29216. VertexBuffer.prototype.updateDirectly = function (data, offset, useBytes) {
  29217. if (useBytes === void 0) { useBytes = false; }
  29218. this._buffer.updateDirectly(data, offset, undefined, useBytes);
  29219. };
  29220. /**
  29221. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  29222. */
  29223. VertexBuffer.prototype.dispose = function () {
  29224. if (this._ownsBuffer) {
  29225. this._buffer.dispose();
  29226. }
  29227. };
  29228. /**
  29229. * Enumerates each value of this vertex buffer as numbers.
  29230. * @param count the number of values to enumerate
  29231. * @param callback the callback function called for each value
  29232. */
  29233. VertexBuffer.prototype.forEach = function (count, callback) {
  29234. VertexBuffer.ForEach(this._buffer.getData(), this.byteOffset, this.byteStride, this._size, this.type, count, this.normalized, callback);
  29235. };
  29236. Object.defineProperty(VertexBuffer, "PositionKind", {
  29237. get: function () {
  29238. return VertexBuffer._PositionKind;
  29239. },
  29240. enumerable: true,
  29241. configurable: true
  29242. });
  29243. Object.defineProperty(VertexBuffer, "NormalKind", {
  29244. get: function () {
  29245. return VertexBuffer._NormalKind;
  29246. },
  29247. enumerable: true,
  29248. configurable: true
  29249. });
  29250. Object.defineProperty(VertexBuffer, "TangentKind", {
  29251. get: function () {
  29252. return VertexBuffer._TangentKind;
  29253. },
  29254. enumerable: true,
  29255. configurable: true
  29256. });
  29257. Object.defineProperty(VertexBuffer, "UVKind", {
  29258. get: function () {
  29259. return VertexBuffer._UVKind;
  29260. },
  29261. enumerable: true,
  29262. configurable: true
  29263. });
  29264. Object.defineProperty(VertexBuffer, "UV2Kind", {
  29265. get: function () {
  29266. return VertexBuffer._UV2Kind;
  29267. },
  29268. enumerable: true,
  29269. configurable: true
  29270. });
  29271. Object.defineProperty(VertexBuffer, "UV3Kind", {
  29272. get: function () {
  29273. return VertexBuffer._UV3Kind;
  29274. },
  29275. enumerable: true,
  29276. configurable: true
  29277. });
  29278. Object.defineProperty(VertexBuffer, "UV4Kind", {
  29279. get: function () {
  29280. return VertexBuffer._UV4Kind;
  29281. },
  29282. enumerable: true,
  29283. configurable: true
  29284. });
  29285. Object.defineProperty(VertexBuffer, "UV5Kind", {
  29286. get: function () {
  29287. return VertexBuffer._UV5Kind;
  29288. },
  29289. enumerable: true,
  29290. configurable: true
  29291. });
  29292. Object.defineProperty(VertexBuffer, "UV6Kind", {
  29293. get: function () {
  29294. return VertexBuffer._UV6Kind;
  29295. },
  29296. enumerable: true,
  29297. configurable: true
  29298. });
  29299. Object.defineProperty(VertexBuffer, "ColorKind", {
  29300. get: function () {
  29301. return VertexBuffer._ColorKind;
  29302. },
  29303. enumerable: true,
  29304. configurable: true
  29305. });
  29306. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  29307. get: function () {
  29308. return VertexBuffer._MatricesIndicesKind;
  29309. },
  29310. enumerable: true,
  29311. configurable: true
  29312. });
  29313. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  29314. get: function () {
  29315. return VertexBuffer._MatricesWeightsKind;
  29316. },
  29317. enumerable: true,
  29318. configurable: true
  29319. });
  29320. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  29321. get: function () {
  29322. return VertexBuffer._MatricesIndicesExtraKind;
  29323. },
  29324. enumerable: true,
  29325. configurable: true
  29326. });
  29327. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  29328. get: function () {
  29329. return VertexBuffer._MatricesWeightsExtraKind;
  29330. },
  29331. enumerable: true,
  29332. configurable: true
  29333. });
  29334. /**
  29335. * Deduces the stride given a kind.
  29336. * @param kind The kind string to deduce
  29337. * @returns The deduced stride
  29338. */
  29339. VertexBuffer.DeduceStride = function (kind) {
  29340. switch (kind) {
  29341. case VertexBuffer.UVKind:
  29342. case VertexBuffer.UV2Kind:
  29343. case VertexBuffer.UV3Kind:
  29344. case VertexBuffer.UV4Kind:
  29345. case VertexBuffer.UV5Kind:
  29346. case VertexBuffer.UV6Kind:
  29347. return 2;
  29348. case VertexBuffer.NormalKind:
  29349. case VertexBuffer.PositionKind:
  29350. return 3;
  29351. case VertexBuffer.ColorKind:
  29352. case VertexBuffer.MatricesIndicesKind:
  29353. case VertexBuffer.MatricesIndicesExtraKind:
  29354. case VertexBuffer.MatricesWeightsKind:
  29355. case VertexBuffer.MatricesWeightsExtraKind:
  29356. case VertexBuffer.TangentKind:
  29357. return 4;
  29358. default:
  29359. throw new Error("Invalid kind '" + kind + "'");
  29360. }
  29361. };
  29362. /**
  29363. * Gets the byte length of the given type.
  29364. * @param type the type
  29365. * @returns the number of bytes
  29366. */
  29367. VertexBuffer.GetTypeByteLength = function (type) {
  29368. switch (type) {
  29369. case VertexBuffer.BYTE:
  29370. case VertexBuffer.UNSIGNED_BYTE:
  29371. return 1;
  29372. case VertexBuffer.SHORT:
  29373. case VertexBuffer.UNSIGNED_SHORT:
  29374. return 2;
  29375. case VertexBuffer.INT:
  29376. case VertexBuffer.FLOAT:
  29377. return 4;
  29378. default:
  29379. throw new Error("Invalid type '" + type + "'");
  29380. }
  29381. };
  29382. /**
  29383. * Enumerates each value of the given parameters as numbers.
  29384. * @param data the data to enumerate
  29385. * @param byteOffset the byte offset of the data
  29386. * @param byteStride the byte stride of the data
  29387. * @param componentCount the number of components per element
  29388. * @param componentType the type of the component
  29389. * @param count the total number of components
  29390. * @param normalized whether the data is normalized
  29391. * @param callback the callback function called for each value
  29392. */
  29393. VertexBuffer.ForEach = function (data, byteOffset, byteStride, componentCount, componentType, count, normalized, callback) {
  29394. if (data instanceof Array) {
  29395. var offset = byteOffset / 4;
  29396. var stride = byteStride / 4;
  29397. for (var index = 0; index < count; index += componentCount) {
  29398. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  29399. callback(data[offset + componentIndex], index + componentIndex);
  29400. }
  29401. offset += stride;
  29402. }
  29403. }
  29404. else {
  29405. var dataView = data instanceof ArrayBuffer ? new DataView(data) : new DataView(data.buffer, data.byteOffset, data.byteLength);
  29406. var componentByteLength = VertexBuffer.GetTypeByteLength(componentType);
  29407. for (var index = 0; index < count; index += componentCount) {
  29408. var componentByteOffset = byteOffset;
  29409. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  29410. var value = VertexBuffer._GetFloatValue(dataView, componentType, componentByteOffset, normalized);
  29411. callback(value, index + componentIndex);
  29412. componentByteOffset += componentByteLength;
  29413. }
  29414. byteOffset += byteStride;
  29415. }
  29416. }
  29417. };
  29418. VertexBuffer._GetFloatValue = function (dataView, type, byteOffset, normalized) {
  29419. switch (type) {
  29420. case VertexBuffer.BYTE: {
  29421. var value = dataView.getInt8(byteOffset);
  29422. if (normalized) {
  29423. value = Math.max(value / 127, -1);
  29424. }
  29425. return value;
  29426. }
  29427. case VertexBuffer.UNSIGNED_BYTE: {
  29428. var value = dataView.getUint8(byteOffset);
  29429. if (normalized) {
  29430. value = value / 255;
  29431. }
  29432. return value;
  29433. }
  29434. case VertexBuffer.SHORT: {
  29435. var value = dataView.getInt16(byteOffset, true);
  29436. if (normalized) {
  29437. value = Math.max(value / 16383, -1);
  29438. }
  29439. return value;
  29440. }
  29441. case VertexBuffer.UNSIGNED_SHORT: {
  29442. var value = dataView.getUint16(byteOffset, true);
  29443. if (normalized) {
  29444. value = value / 65535;
  29445. }
  29446. return value;
  29447. }
  29448. case VertexBuffer.FLOAT: {
  29449. return dataView.getFloat32(byteOffset, true);
  29450. }
  29451. default: {
  29452. throw new Error("Invalid component type " + type);
  29453. }
  29454. }
  29455. };
  29456. /**
  29457. * The byte type.
  29458. */
  29459. VertexBuffer.BYTE = 5120;
  29460. /**
  29461. * The unsigned byte type.
  29462. */
  29463. VertexBuffer.UNSIGNED_BYTE = 5121;
  29464. /**
  29465. * The short type.
  29466. */
  29467. VertexBuffer.SHORT = 5122;
  29468. /**
  29469. * The unsigned short type.
  29470. */
  29471. VertexBuffer.UNSIGNED_SHORT = 5123;
  29472. /**
  29473. * The integer type.
  29474. */
  29475. VertexBuffer.INT = 5124;
  29476. /**
  29477. * The unsigned integer type.
  29478. */
  29479. VertexBuffer.UNSIGNED_INT = 5125;
  29480. /**
  29481. * The float type.
  29482. */
  29483. VertexBuffer.FLOAT = 5126;
  29484. // Enums
  29485. VertexBuffer._PositionKind = "position";
  29486. VertexBuffer._NormalKind = "normal";
  29487. VertexBuffer._TangentKind = "tangent";
  29488. VertexBuffer._UVKind = "uv";
  29489. VertexBuffer._UV2Kind = "uv2";
  29490. VertexBuffer._UV3Kind = "uv3";
  29491. VertexBuffer._UV4Kind = "uv4";
  29492. VertexBuffer._UV5Kind = "uv5";
  29493. VertexBuffer._UV6Kind = "uv6";
  29494. VertexBuffer._ColorKind = "color";
  29495. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  29496. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  29497. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  29498. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  29499. return VertexBuffer;
  29500. }());
  29501. BABYLON.VertexBuffer = VertexBuffer;
  29502. })(BABYLON || (BABYLON = {}));
  29503. //# sourceMappingURL=babylon.vertexBuffer.js.map
  29504. //# sourceMappingURL=babylon.internalTextureLoader.js.map
  29505. var BABYLON;
  29506. (function (BABYLON) {
  29507. /**
  29508. * Internal class used by the engine to get list of {BABYLON.InternalTexture} already bound to the GL context
  29509. */
  29510. var DummyInternalTextureTracker = /** @class */ (function () {
  29511. function DummyInternalTextureTracker() {
  29512. /**
  29513. * Gets or set the previous tracker in the list
  29514. */
  29515. this.previous = null;
  29516. /**
  29517. * Gets or set the next tracker in the list
  29518. */
  29519. this.next = null;
  29520. }
  29521. return DummyInternalTextureTracker;
  29522. }());
  29523. BABYLON.DummyInternalTextureTracker = DummyInternalTextureTracker;
  29524. })(BABYLON || (BABYLON = {}));
  29525. //# sourceMappingURL=babylon.internalTextureTracker.js.map
  29526. var BABYLON;
  29527. (function (BABYLON) {
  29528. /**
  29529. * Class used to store data associated with WebGL texture data for the engine
  29530. * This class should not be used directly
  29531. */
  29532. var InternalTexture = /** @class */ (function () {
  29533. /**
  29534. * Creates a new InternalTexture
  29535. * @param engine defines the engine to use
  29536. * @param dataSource defines the type of data that will be used
  29537. */
  29538. function InternalTexture(engine, dataSource) {
  29539. /**
  29540. * Observable called when the texture is loaded
  29541. */
  29542. this.onLoadedObservable = new BABYLON.Observable();
  29543. /**
  29544. * Gets or set the previous tracker in the list
  29545. */
  29546. this.previous = null;
  29547. /**
  29548. * Gets or set the next tracker in the list
  29549. */
  29550. this.next = null;
  29551. // Private
  29552. /** @hidden */
  29553. this._initialSlot = -1;
  29554. /** @hidden */
  29555. this._designatedSlot = -1;
  29556. /** @hidden */
  29557. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  29558. /** @hidden */
  29559. this._comparisonFunction = 0;
  29560. /** @hidden */
  29561. this._sphericalPolynomial = null;
  29562. /** @hidden */
  29563. this._lodGenerationScale = 0;
  29564. /** @hidden */
  29565. this._lodGenerationOffset = 0;
  29566. /** @hidden */
  29567. this._isRGBD = false;
  29568. /** @hidden */
  29569. this._references = 1;
  29570. this._engine = engine;
  29571. this._dataSource = dataSource;
  29572. this._webGLTexture = engine._createTexture();
  29573. }
  29574. /**
  29575. * Gets the Engine the texture belongs to.
  29576. * @returns The babylon engine
  29577. */
  29578. InternalTexture.prototype.getEngine = function () {
  29579. return this._engine;
  29580. };
  29581. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  29582. /**
  29583. * Gets the data source type of the texture (can be one of the BABYLON.InternalTexture.DATASOURCE_XXXX)
  29584. */
  29585. get: function () {
  29586. return this._dataSource;
  29587. },
  29588. enumerable: true,
  29589. configurable: true
  29590. });
  29591. /**
  29592. * Increments the number of references (ie. the number of {BABYLON.Texture} that point to it)
  29593. */
  29594. InternalTexture.prototype.incrementReferences = function () {
  29595. this._references++;
  29596. };
  29597. /**
  29598. * Change the size of the texture (not the size of the content)
  29599. * @param width defines the new width
  29600. * @param height defines the new height
  29601. * @param depth defines the new depth (1 by default)
  29602. */
  29603. InternalTexture.prototype.updateSize = function (width, height, depth) {
  29604. if (depth === void 0) { depth = 1; }
  29605. this.width = width;
  29606. this.height = height;
  29607. this.depth = depth;
  29608. this.baseWidth = width;
  29609. this.baseHeight = height;
  29610. this.baseDepth = depth;
  29611. this._size = width * height * depth;
  29612. };
  29613. /** @hidden */
  29614. InternalTexture.prototype._rebuild = function () {
  29615. var _this = this;
  29616. var proxy;
  29617. this.isReady = false;
  29618. this._cachedCoordinatesMode = null;
  29619. this._cachedWrapU = null;
  29620. this._cachedWrapV = null;
  29621. this._cachedAnisotropicFilteringLevel = null;
  29622. switch (this._dataSource) {
  29623. case InternalTexture.DATASOURCE_TEMP:
  29624. return;
  29625. case InternalTexture.DATASOURCE_URL:
  29626. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  29627. _this.isReady = true;
  29628. }, null, this._buffer, undefined, this.format);
  29629. proxy._swapAndDie(this);
  29630. return;
  29631. case InternalTexture.DATASOURCE_RAW:
  29632. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  29633. proxy._swapAndDie(this);
  29634. this.isReady = true;
  29635. return;
  29636. case InternalTexture.DATASOURCE_RAW3D:
  29637. proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  29638. proxy._swapAndDie(this);
  29639. this.isReady = true;
  29640. return;
  29641. case InternalTexture.DATASOURCE_DYNAMIC:
  29642. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  29643. proxy._swapAndDie(this);
  29644. // The engine will make sure to update content so no need to flag it as isReady = true
  29645. return;
  29646. case InternalTexture.DATASOURCE_RENDERTARGET:
  29647. var options = new BABYLON.RenderTargetCreationOptions();
  29648. options.generateDepthBuffer = this._generateDepthBuffer;
  29649. options.generateMipMaps = this.generateMipMaps;
  29650. options.generateStencilBuffer = this._generateStencilBuffer;
  29651. options.samplingMode = this.samplingMode;
  29652. options.type = this.type;
  29653. if (this.isCube) {
  29654. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  29655. }
  29656. else {
  29657. var size = {
  29658. width: this.width,
  29659. height: this.height
  29660. };
  29661. proxy = this._engine.createRenderTargetTexture(size, options);
  29662. }
  29663. proxy._swapAndDie(this);
  29664. this.isReady = true;
  29665. return;
  29666. case InternalTexture.DATASOURCE_DEPTHTEXTURE:
  29667. var depthTextureOptions = {
  29668. bilinearFiltering: this.samplingMode !== BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  29669. comparisonFunction: this._comparisonFunction,
  29670. generateStencil: this._generateStencilBuffer,
  29671. isCube: this.isCube
  29672. };
  29673. proxy = this._engine.createDepthStencilTexture({ width: this.width, height: this.height }, depthTextureOptions);
  29674. proxy._swapAndDie(this);
  29675. this.isReady = true;
  29676. return;
  29677. case InternalTexture.DATASOURCE_CUBE:
  29678. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  29679. _this.isReady = true;
  29680. }, null, this.format, this._extension);
  29681. proxy._swapAndDie(this);
  29682. return;
  29683. case InternalTexture.DATASOURCE_CUBERAW:
  29684. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  29685. proxy._swapAndDie(this);
  29686. this.isReady = true;
  29687. return;
  29688. case InternalTexture.DATASOURCE_CUBERAW_RGBD:
  29689. proxy = this._engine.createRawCubeTexture(null, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  29690. BABYLON.RawCubeTexture._UpdateRGBDAsync(proxy, this._bufferViewArrayArray, this._sphericalPolynomial, this._lodGenerationScale, this._lodGenerationOffset).then(function () {
  29691. _this.isReady = true;
  29692. });
  29693. proxy._swapAndDie(this);
  29694. return;
  29695. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  29696. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  29697. if (proxy) {
  29698. proxy._swapAndDie(_this);
  29699. }
  29700. _this.isReady = true;
  29701. }, null, this.format, this._extension);
  29702. proxy._sphericalPolynomial = this._sphericalPolynomial;
  29703. return;
  29704. }
  29705. };
  29706. /** @hidden */
  29707. InternalTexture.prototype._swapAndDie = function (target) {
  29708. target._webGLTexture = this._webGLTexture;
  29709. if (this._framebuffer) {
  29710. target._framebuffer = this._framebuffer;
  29711. }
  29712. if (this._depthStencilBuffer) {
  29713. target._depthStencilBuffer = this._depthStencilBuffer;
  29714. }
  29715. if (this._lodTextureHigh) {
  29716. if (target._lodTextureHigh) {
  29717. target._lodTextureHigh.dispose();
  29718. }
  29719. target._lodTextureHigh = this._lodTextureHigh;
  29720. }
  29721. if (this._lodTextureMid) {
  29722. if (target._lodTextureMid) {
  29723. target._lodTextureMid.dispose();
  29724. }
  29725. target._lodTextureMid = this._lodTextureMid;
  29726. }
  29727. if (this._lodTextureLow) {
  29728. if (target._lodTextureLow) {
  29729. target._lodTextureLow.dispose();
  29730. }
  29731. target._lodTextureLow = this._lodTextureLow;
  29732. }
  29733. var cache = this._engine.getLoadedTexturesCache();
  29734. var index = cache.indexOf(this);
  29735. if (index !== -1) {
  29736. cache.splice(index, 1);
  29737. }
  29738. };
  29739. /**
  29740. * Dispose the current allocated resources
  29741. */
  29742. InternalTexture.prototype.dispose = function () {
  29743. if (!this._webGLTexture) {
  29744. return;
  29745. }
  29746. this._references--;
  29747. if (this._references === 0) {
  29748. this._engine._releaseTexture(this);
  29749. this._webGLTexture = null;
  29750. this.previous = null;
  29751. this.next = null;
  29752. }
  29753. };
  29754. /**
  29755. * The source of the texture data is unknown
  29756. */
  29757. InternalTexture.DATASOURCE_UNKNOWN = 0;
  29758. /**
  29759. * Texture data comes from an URL
  29760. */
  29761. InternalTexture.DATASOURCE_URL = 1;
  29762. /**
  29763. * Texture data is only used for temporary storage
  29764. */
  29765. InternalTexture.DATASOURCE_TEMP = 2;
  29766. /**
  29767. * Texture data comes from raw data (ArrayBuffer)
  29768. */
  29769. InternalTexture.DATASOURCE_RAW = 3;
  29770. /**
  29771. * Texture content is dynamic (video or dynamic texture)
  29772. */
  29773. InternalTexture.DATASOURCE_DYNAMIC = 4;
  29774. /**
  29775. * Texture content is generated by rendering to it
  29776. */
  29777. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  29778. /**
  29779. * Texture content is part of a multi render target process
  29780. */
  29781. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  29782. /**
  29783. * Texture data comes from a cube data file
  29784. */
  29785. InternalTexture.DATASOURCE_CUBE = 7;
  29786. /**
  29787. * Texture data comes from a raw cube data
  29788. */
  29789. InternalTexture.DATASOURCE_CUBERAW = 8;
  29790. /**
  29791. * Texture data come from a prefiltered cube data file
  29792. */
  29793. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  29794. /**
  29795. * Texture content is raw 3D data
  29796. */
  29797. InternalTexture.DATASOURCE_RAW3D = 10;
  29798. /**
  29799. * Texture content is a depth texture
  29800. */
  29801. InternalTexture.DATASOURCE_DEPTHTEXTURE = 11;
  29802. /**
  29803. * Texture data comes from a raw cube data encoded with RGBD
  29804. */
  29805. InternalTexture.DATASOURCE_CUBERAW_RGBD = 12;
  29806. return InternalTexture;
  29807. }());
  29808. BABYLON.InternalTexture = InternalTexture;
  29809. })(BABYLON || (BABYLON = {}));
  29810. //# sourceMappingURL=babylon.internalTexture.js.map
  29811. var BABYLON;
  29812. (function (BABYLON) {
  29813. var BaseTexture = /** @class */ (function () {
  29814. function BaseTexture(scene) {
  29815. this._hasAlpha = false;
  29816. this.getAlphaFromRGB = false;
  29817. this.level = 1;
  29818. this.coordinatesIndex = 0;
  29819. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  29820. /**
  29821. * | Value | Type | Description |
  29822. * | ----- | ------------------ | ----------- |
  29823. * | 0 | CLAMP_ADDRESSMODE | |
  29824. * | 1 | WRAP_ADDRESSMODE | |
  29825. * | 2 | MIRROR_ADDRESSMODE | |
  29826. */
  29827. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  29828. /**
  29829. * | Value | Type | Description |
  29830. * | ----- | ------------------ | ----------- |
  29831. * | 0 | CLAMP_ADDRESSMODE | |
  29832. * | 1 | WRAP_ADDRESSMODE | |
  29833. * | 2 | MIRROR_ADDRESSMODE | |
  29834. */
  29835. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  29836. /**
  29837. * | Value | Type | Description |
  29838. * | ----- | ------------------ | ----------- |
  29839. * | 0 | CLAMP_ADDRESSMODE | |
  29840. * | 1 | WRAP_ADDRESSMODE | |
  29841. * | 2 | MIRROR_ADDRESSMODE | |
  29842. */
  29843. this.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE;
  29844. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  29845. this.isCube = false;
  29846. this.is3D = false;
  29847. this.gammaSpace = true;
  29848. this.invertZ = false;
  29849. this.lodLevelInAlpha = false;
  29850. this.isRenderTarget = false;
  29851. this.animations = new Array();
  29852. /**
  29853. * An event triggered when the texture is disposed.
  29854. */
  29855. this.onDisposeObservable = new BABYLON.Observable();
  29856. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  29857. this._cachedSize = BABYLON.Size.Zero();
  29858. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  29859. if (this._scene) {
  29860. this._scene.textures.push(this);
  29861. }
  29862. this._uid = null;
  29863. }
  29864. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  29865. get: function () {
  29866. return this._hasAlpha;
  29867. },
  29868. set: function (value) {
  29869. if (this._hasAlpha === value) {
  29870. return;
  29871. }
  29872. this._hasAlpha = value;
  29873. if (this._scene) {
  29874. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  29875. }
  29876. },
  29877. enumerable: true,
  29878. configurable: true
  29879. });
  29880. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  29881. get: function () {
  29882. return this._coordinatesMode;
  29883. },
  29884. /**
  29885. * How a texture is mapped.
  29886. *
  29887. * | Value | Type | Description |
  29888. * | ----- | ----------------------------------- | ----------- |
  29889. * | 0 | EXPLICIT_MODE | |
  29890. * | 1 | SPHERICAL_MODE | |
  29891. * | 2 | PLANAR_MODE | |
  29892. * | 3 | CUBIC_MODE | |
  29893. * | 4 | PROJECTION_MODE | |
  29894. * | 5 | SKYBOX_MODE | |
  29895. * | 6 | INVCUBIC_MODE | |
  29896. * | 7 | EQUIRECTANGULAR_MODE | |
  29897. * | 8 | FIXED_EQUIRECTANGULAR_MODE | |
  29898. * | 9 | FIXED_EQUIRECTANGULAR_MIRRORED_MODE | |
  29899. */
  29900. set: function (value) {
  29901. if (this._coordinatesMode === value) {
  29902. return;
  29903. }
  29904. this._coordinatesMode = value;
  29905. if (this._scene) {
  29906. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  29907. }
  29908. },
  29909. enumerable: true,
  29910. configurable: true
  29911. });
  29912. Object.defineProperty(BaseTexture.prototype, "isRGBD", {
  29913. /**
  29914. * Gets whether or not the texture contains RGBD data.
  29915. */
  29916. get: function () {
  29917. return this._texture != null && this._texture._isRGBD;
  29918. },
  29919. enumerable: true,
  29920. configurable: true
  29921. });
  29922. Object.defineProperty(BaseTexture.prototype, "lodGenerationOffset", {
  29923. get: function () {
  29924. if (this._texture)
  29925. return this._texture._lodGenerationOffset;
  29926. return 0.0;
  29927. },
  29928. set: function (value) {
  29929. if (this._texture)
  29930. this._texture._lodGenerationOffset = value;
  29931. },
  29932. enumerable: true,
  29933. configurable: true
  29934. });
  29935. Object.defineProperty(BaseTexture.prototype, "lodGenerationScale", {
  29936. get: function () {
  29937. if (this._texture)
  29938. return this._texture._lodGenerationScale;
  29939. return 0.0;
  29940. },
  29941. set: function (value) {
  29942. if (this._texture)
  29943. this._texture._lodGenerationScale = value;
  29944. },
  29945. enumerable: true,
  29946. configurable: true
  29947. });
  29948. Object.defineProperty(BaseTexture.prototype, "uid", {
  29949. get: function () {
  29950. if (!this._uid) {
  29951. this._uid = BABYLON.Tools.RandomId();
  29952. }
  29953. return this._uid;
  29954. },
  29955. enumerable: true,
  29956. configurable: true
  29957. });
  29958. BaseTexture.prototype.toString = function () {
  29959. return this.name;
  29960. };
  29961. BaseTexture.prototype.getClassName = function () {
  29962. return "BaseTexture";
  29963. };
  29964. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  29965. set: function (callback) {
  29966. if (this._onDisposeObserver) {
  29967. this.onDisposeObservable.remove(this._onDisposeObserver);
  29968. }
  29969. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  29970. },
  29971. enumerable: true,
  29972. configurable: true
  29973. });
  29974. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  29975. get: function () {
  29976. return true;
  29977. },
  29978. enumerable: true,
  29979. configurable: true
  29980. });
  29981. BaseTexture.prototype.getScene = function () {
  29982. return this._scene;
  29983. };
  29984. BaseTexture.prototype.getTextureMatrix = function () {
  29985. return BABYLON.Matrix.IdentityReadOnly;
  29986. };
  29987. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  29988. return BABYLON.Matrix.IdentityReadOnly;
  29989. };
  29990. BaseTexture.prototype.getInternalTexture = function () {
  29991. return this._texture;
  29992. };
  29993. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  29994. return !this.isBlocking || this.isReady();
  29995. };
  29996. BaseTexture.prototype.isReady = function () {
  29997. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  29998. this.delayLoad();
  29999. return false;
  30000. }
  30001. if (this._texture) {
  30002. return this._texture.isReady;
  30003. }
  30004. return false;
  30005. };
  30006. BaseTexture.prototype.getSize = function () {
  30007. if (this._texture) {
  30008. if (this._texture.width) {
  30009. this._cachedSize.width = this._texture.width;
  30010. this._cachedSize.height = this._texture.height;
  30011. return this._cachedSize;
  30012. }
  30013. if (this._texture._size) {
  30014. this._cachedSize.width = this._texture._size;
  30015. this._cachedSize.height = this._texture._size;
  30016. return this._cachedSize;
  30017. }
  30018. }
  30019. return this._cachedSize;
  30020. };
  30021. BaseTexture.prototype.getBaseSize = function () {
  30022. if (!this.isReady() || !this._texture)
  30023. return BABYLON.Size.Zero();
  30024. if (this._texture._size) {
  30025. return new BABYLON.Size(this._texture._size, this._texture._size);
  30026. }
  30027. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  30028. };
  30029. BaseTexture.prototype.scale = function (ratio) {
  30030. };
  30031. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  30032. get: function () {
  30033. return false;
  30034. },
  30035. enumerable: true,
  30036. configurable: true
  30037. });
  30038. /** @hidden */
  30039. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  30040. if (!this._scene) {
  30041. return null;
  30042. }
  30043. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  30044. for (var index = 0; index < texturesCache.length; index++) {
  30045. var texturesCacheEntry = texturesCache[index];
  30046. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  30047. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  30048. texturesCacheEntry.incrementReferences();
  30049. return texturesCacheEntry;
  30050. }
  30051. }
  30052. }
  30053. return null;
  30054. };
  30055. /** @hidden */
  30056. BaseTexture.prototype._rebuild = function () {
  30057. };
  30058. BaseTexture.prototype.delayLoad = function () {
  30059. };
  30060. BaseTexture.prototype.clone = function () {
  30061. return null;
  30062. };
  30063. Object.defineProperty(BaseTexture.prototype, "textureType", {
  30064. get: function () {
  30065. if (!this._texture) {
  30066. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  30067. }
  30068. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  30069. },
  30070. enumerable: true,
  30071. configurable: true
  30072. });
  30073. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  30074. get: function () {
  30075. if (!this._texture) {
  30076. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  30077. }
  30078. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  30079. },
  30080. enumerable: true,
  30081. configurable: true
  30082. });
  30083. /**
  30084. * Reads the pixels stored in the webgl texture and returns them as an ArrayBuffer.
  30085. * This will returns an RGBA array buffer containing either in values (0-255) or
  30086. * float values (0-1) depending of the underlying buffer type.
  30087. * @param faceIndex defines the face of the texture to read (in case of cube texture)
  30088. * @param level defines the LOD level of the texture to read (in case of Mip Maps)
  30089. * @param buffer defines a user defined buffer to fill with data (can be null)
  30090. * @returns The Array buffer containing the pixels data.
  30091. */
  30092. BaseTexture.prototype.readPixels = function (faceIndex, level, buffer) {
  30093. if (faceIndex === void 0) { faceIndex = 0; }
  30094. if (level === void 0) { level = 0; }
  30095. if (buffer === void 0) { buffer = null; }
  30096. if (!this._texture) {
  30097. return null;
  30098. }
  30099. var size = this.getSize();
  30100. var width = size.width;
  30101. var height = size.height;
  30102. var scene = this.getScene();
  30103. if (!scene) {
  30104. return null;
  30105. }
  30106. var engine = scene.getEngine();
  30107. if (level != 0) {
  30108. width = width / Math.pow(2, level);
  30109. height = height / Math.pow(2, level);
  30110. width = Math.round(width);
  30111. height = Math.round(height);
  30112. }
  30113. if (this._texture.isCube) {
  30114. return engine._readTexturePixels(this._texture, width, height, faceIndex, level, buffer);
  30115. }
  30116. return engine._readTexturePixels(this._texture, width, height, -1, level, buffer);
  30117. };
  30118. BaseTexture.prototype.releaseInternalTexture = function () {
  30119. if (this._texture) {
  30120. this._texture.dispose();
  30121. this._texture = null;
  30122. }
  30123. };
  30124. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  30125. get: function () {
  30126. if (!this._texture || !BABYLON.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  30127. return null;
  30128. }
  30129. if (!this._texture._sphericalPolynomial) {
  30130. this._texture._sphericalPolynomial =
  30131. BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  30132. }
  30133. return this._texture._sphericalPolynomial;
  30134. },
  30135. set: function (value) {
  30136. if (this._texture) {
  30137. this._texture._sphericalPolynomial = value;
  30138. }
  30139. },
  30140. enumerable: true,
  30141. configurable: true
  30142. });
  30143. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  30144. get: function () {
  30145. if (this._texture) {
  30146. return this._texture._lodTextureHigh;
  30147. }
  30148. return null;
  30149. },
  30150. enumerable: true,
  30151. configurable: true
  30152. });
  30153. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  30154. get: function () {
  30155. if (this._texture) {
  30156. return this._texture._lodTextureMid;
  30157. }
  30158. return null;
  30159. },
  30160. enumerable: true,
  30161. configurable: true
  30162. });
  30163. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  30164. get: function () {
  30165. if (this._texture) {
  30166. return this._texture._lodTextureLow;
  30167. }
  30168. return null;
  30169. },
  30170. enumerable: true,
  30171. configurable: true
  30172. });
  30173. BaseTexture.prototype.dispose = function () {
  30174. if (!this._scene) {
  30175. return;
  30176. }
  30177. // Animations
  30178. this._scene.stopAnimation(this);
  30179. // Remove from scene
  30180. this._scene._removePendingData(this);
  30181. var index = this._scene.textures.indexOf(this);
  30182. if (index >= 0) {
  30183. this._scene.textures.splice(index, 1);
  30184. }
  30185. if (this._texture === undefined) {
  30186. return;
  30187. }
  30188. // Release
  30189. this.releaseInternalTexture();
  30190. // Callback
  30191. this.onDisposeObservable.notifyObservers(this);
  30192. this.onDisposeObservable.clear();
  30193. };
  30194. BaseTexture.prototype.serialize = function () {
  30195. if (!this.name) {
  30196. return null;
  30197. }
  30198. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  30199. // Animations
  30200. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  30201. return serializationObject;
  30202. };
  30203. BaseTexture.WhenAllReady = function (textures, callback) {
  30204. var numRemaining = textures.length;
  30205. if (numRemaining === 0) {
  30206. callback();
  30207. return;
  30208. }
  30209. var _loop_1 = function () {
  30210. texture = textures[i];
  30211. if (texture.isReady()) {
  30212. if (--numRemaining === 0) {
  30213. callback();
  30214. }
  30215. }
  30216. else {
  30217. onLoadObservable = texture.onLoadObservable;
  30218. var onLoadCallback_1 = function () {
  30219. onLoadObservable.removeCallback(onLoadCallback_1);
  30220. if (--numRemaining === 0) {
  30221. callback();
  30222. }
  30223. };
  30224. onLoadObservable.add(onLoadCallback_1);
  30225. }
  30226. };
  30227. var texture, onLoadObservable;
  30228. for (var i = 0; i < textures.length; i++) {
  30229. _loop_1();
  30230. }
  30231. };
  30232. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  30233. __decorate([
  30234. BABYLON.serialize()
  30235. ], BaseTexture.prototype, "name", void 0);
  30236. __decorate([
  30237. BABYLON.serialize("hasAlpha")
  30238. ], BaseTexture.prototype, "_hasAlpha", void 0);
  30239. __decorate([
  30240. BABYLON.serialize()
  30241. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  30242. __decorate([
  30243. BABYLON.serialize()
  30244. ], BaseTexture.prototype, "level", void 0);
  30245. __decorate([
  30246. BABYLON.serialize()
  30247. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  30248. __decorate([
  30249. BABYLON.serialize("coordinatesMode")
  30250. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  30251. __decorate([
  30252. BABYLON.serialize()
  30253. ], BaseTexture.prototype, "wrapU", void 0);
  30254. __decorate([
  30255. BABYLON.serialize()
  30256. ], BaseTexture.prototype, "wrapV", void 0);
  30257. __decorate([
  30258. BABYLON.serialize()
  30259. ], BaseTexture.prototype, "wrapR", void 0);
  30260. __decorate([
  30261. BABYLON.serialize()
  30262. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  30263. __decorate([
  30264. BABYLON.serialize()
  30265. ], BaseTexture.prototype, "isCube", void 0);
  30266. __decorate([
  30267. BABYLON.serialize()
  30268. ], BaseTexture.prototype, "is3D", void 0);
  30269. __decorate([
  30270. BABYLON.serialize()
  30271. ], BaseTexture.prototype, "gammaSpace", void 0);
  30272. __decorate([
  30273. BABYLON.serialize()
  30274. ], BaseTexture.prototype, "invertZ", void 0);
  30275. __decorate([
  30276. BABYLON.serialize()
  30277. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  30278. __decorate([
  30279. BABYLON.serialize()
  30280. ], BaseTexture.prototype, "lodGenerationOffset", null);
  30281. __decorate([
  30282. BABYLON.serialize()
  30283. ], BaseTexture.prototype, "lodGenerationScale", null);
  30284. __decorate([
  30285. BABYLON.serialize()
  30286. ], BaseTexture.prototype, "isRenderTarget", void 0);
  30287. return BaseTexture;
  30288. }());
  30289. BABYLON.BaseTexture = BaseTexture;
  30290. })(BABYLON || (BABYLON = {}));
  30291. //# sourceMappingURL=babylon.baseTexture.js.map
  30292. var BABYLON;
  30293. (function (BABYLON) {
  30294. var Texture = /** @class */ (function (_super) {
  30295. __extends(Texture, _super);
  30296. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  30297. if (noMipmap === void 0) { noMipmap = false; }
  30298. if (invertY === void 0) { invertY = true; }
  30299. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  30300. if (onLoad === void 0) { onLoad = null; }
  30301. if (onError === void 0) { onError = null; }
  30302. if (buffer === void 0) { buffer = null; }
  30303. if (deleteBuffer === void 0) { deleteBuffer = false; }
  30304. var _this = _super.call(this, scene) || this;
  30305. _this.uOffset = 0;
  30306. _this.vOffset = 0;
  30307. _this.uScale = 1.0;
  30308. _this.vScale = 1.0;
  30309. _this.uAng = 0;
  30310. _this.vAng = 0;
  30311. _this.wAng = 0;
  30312. /**
  30313. * Defines the center of rotation (U)
  30314. */
  30315. _this.uRotationCenter = 0.5;
  30316. /**
  30317. * Defines the center of rotation (V)
  30318. */
  30319. _this.vRotationCenter = 0.5;
  30320. /**
  30321. * Defines the center of rotation (W)
  30322. */
  30323. _this.wRotationCenter = 0.5;
  30324. _this._isBlocking = true;
  30325. _this.name = url || "";
  30326. _this.url = url;
  30327. _this._noMipmap = noMipmap;
  30328. _this._invertY = invertY;
  30329. _this._samplingMode = samplingMode;
  30330. _this._buffer = buffer;
  30331. _this._deleteBuffer = deleteBuffer;
  30332. if (format) {
  30333. _this._format = format;
  30334. }
  30335. scene = _this.getScene();
  30336. if (!scene) {
  30337. return _this;
  30338. }
  30339. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  30340. var load = function () {
  30341. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  30342. _this.onLoadObservable.notifyObservers(_this);
  30343. }
  30344. if (onLoad) {
  30345. onLoad();
  30346. }
  30347. if (!_this.isBlocking && scene) {
  30348. scene.resetCachedMaterial();
  30349. }
  30350. };
  30351. if (!_this.url) {
  30352. _this._delayedOnLoad = load;
  30353. _this._delayedOnError = onError;
  30354. return _this;
  30355. }
  30356. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  30357. if (!_this._texture) {
  30358. if (!scene.useDelayedTextureLoading) {
  30359. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format);
  30360. if (deleteBuffer) {
  30361. delete _this._buffer;
  30362. }
  30363. }
  30364. else {
  30365. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  30366. _this._delayedOnLoad = load;
  30367. _this._delayedOnError = onError;
  30368. }
  30369. }
  30370. else {
  30371. if (_this._texture.isReady) {
  30372. BABYLON.Tools.SetImmediate(function () { return load(); });
  30373. }
  30374. else {
  30375. _this._texture.onLoadedObservable.add(load);
  30376. }
  30377. }
  30378. return _this;
  30379. }
  30380. Object.defineProperty(Texture.prototype, "noMipmap", {
  30381. get: function () {
  30382. return this._noMipmap;
  30383. },
  30384. enumerable: true,
  30385. configurable: true
  30386. });
  30387. Object.defineProperty(Texture.prototype, "isBlocking", {
  30388. get: function () {
  30389. return this._isBlocking;
  30390. },
  30391. set: function (value) {
  30392. this._isBlocking = value;
  30393. },
  30394. enumerable: true,
  30395. configurable: true
  30396. });
  30397. Object.defineProperty(Texture.prototype, "samplingMode", {
  30398. get: function () {
  30399. return this._samplingMode;
  30400. },
  30401. enumerable: true,
  30402. configurable: true
  30403. });
  30404. /**
  30405. * Update the url (and optional buffer) of this texture if url was null during construction.
  30406. * @param url the url of the texture
  30407. * @param buffer the buffer of the texture (defaults to null)
  30408. */
  30409. Texture.prototype.updateURL = function (url, buffer) {
  30410. if (buffer === void 0) { buffer = null; }
  30411. if (this.url) {
  30412. throw new Error("URL is already set");
  30413. }
  30414. this.url = url;
  30415. this._buffer = buffer;
  30416. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  30417. this.delayLoad();
  30418. };
  30419. Texture.prototype.delayLoad = function () {
  30420. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  30421. return;
  30422. }
  30423. var scene = this.getScene();
  30424. if (!scene) {
  30425. return;
  30426. }
  30427. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  30428. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  30429. if (!this._texture) {
  30430. this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  30431. if (this._deleteBuffer) {
  30432. delete this._buffer;
  30433. }
  30434. }
  30435. else {
  30436. if (this._delayedOnLoad) {
  30437. if (this._texture.isReady) {
  30438. BABYLON.Tools.SetImmediate(this._delayedOnLoad);
  30439. }
  30440. else {
  30441. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  30442. }
  30443. }
  30444. }
  30445. this._delayedOnLoad = null;
  30446. this._delayedOnError = null;
  30447. };
  30448. /**
  30449. * Default is Trilinear mode.
  30450. *
  30451. * | Value | Type | Description |
  30452. * | ----- | ------------------ | ----------- |
  30453. * | 1 | NEAREST_SAMPLINGMODE or NEAREST_NEAREST_MIPLINEAR | Nearest is: mag = nearest, min = nearest, mip = linear |
  30454. * | 2 | BILINEAR_SAMPLINGMODE or LINEAR_LINEAR_MIPNEAREST | Bilinear is: mag = linear, min = linear, mip = nearest |
  30455. * | 3 | TRILINEAR_SAMPLINGMODE or LINEAR_LINEAR_MIPLINEAR | Trilinear is: mag = linear, min = linear, mip = linear |
  30456. * | 4 | NEAREST_NEAREST_MIPNEAREST | |
  30457. * | 5 | NEAREST_LINEAR_MIPNEAREST | |
  30458. * | 6 | NEAREST_LINEAR_MIPLINEAR | |
  30459. * | 7 | NEAREST_LINEAR | |
  30460. * | 8 | NEAREST_NEAREST | |
  30461. * | 9 | LINEAR_NEAREST_MIPNEAREST | |
  30462. * | 10 | LINEAR_NEAREST_MIPLINEAR | |
  30463. * | 11 | LINEAR_LINEAR | |
  30464. * | 12 | LINEAR_NEAREST | |
  30465. *
  30466. * > _mag_: magnification filter (close to the viewer)
  30467. * > _min_: minification filter (far from the viewer)
  30468. * > _mip_: filter used between mip map levels
  30469. *
  30470. */
  30471. Texture.prototype.updateSamplingMode = function (samplingMode) {
  30472. if (!this._texture) {
  30473. return;
  30474. }
  30475. var scene = this.getScene();
  30476. if (!scene) {
  30477. return;
  30478. }
  30479. this._samplingMode = samplingMode;
  30480. scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  30481. };
  30482. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  30483. x *= this.uScale;
  30484. y *= this.vScale;
  30485. x -= this.uRotationCenter * this.uScale;
  30486. y -= this.vRotationCenter * this.vScale;
  30487. z -= this.wRotationCenter;
  30488. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  30489. t.x += this.uRotationCenter * this.uScale + this.uOffset;
  30490. t.y += this.vRotationCenter * this.vScale + this.vOffset;
  30491. t.z += this.wRotationCenter;
  30492. };
  30493. Texture.prototype.getTextureMatrix = function () {
  30494. var _this = this;
  30495. if (this.uOffset === this._cachedUOffset &&
  30496. this.vOffset === this._cachedVOffset &&
  30497. this.uScale === this._cachedUScale &&
  30498. this.vScale === this._cachedVScale &&
  30499. this.uAng === this._cachedUAng &&
  30500. this.vAng === this._cachedVAng &&
  30501. this.wAng === this._cachedWAng) {
  30502. return this._cachedTextureMatrix;
  30503. }
  30504. this._cachedUOffset = this.uOffset;
  30505. this._cachedVOffset = this.vOffset;
  30506. this._cachedUScale = this.uScale;
  30507. this._cachedVScale = this.vScale;
  30508. this._cachedUAng = this.uAng;
  30509. this._cachedVAng = this.vAng;
  30510. this._cachedWAng = this.wAng;
  30511. if (!this._cachedTextureMatrix) {
  30512. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  30513. this._rowGenerationMatrix = new BABYLON.Matrix();
  30514. this._t0 = BABYLON.Vector3.Zero();
  30515. this._t1 = BABYLON.Vector3.Zero();
  30516. this._t2 = BABYLON.Vector3.Zero();
  30517. }
  30518. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  30519. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  30520. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  30521. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  30522. this._t1.subtractInPlace(this._t0);
  30523. this._t2.subtractInPlace(this._t0);
  30524. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  30525. this._cachedTextureMatrix.m[0] = this._t1.x;
  30526. this._cachedTextureMatrix.m[1] = this._t1.y;
  30527. this._cachedTextureMatrix.m[2] = this._t1.z;
  30528. this._cachedTextureMatrix.m[4] = this._t2.x;
  30529. this._cachedTextureMatrix.m[5] = this._t2.y;
  30530. this._cachedTextureMatrix.m[6] = this._t2.z;
  30531. this._cachedTextureMatrix.m[8] = this._t0.x;
  30532. this._cachedTextureMatrix.m[9] = this._t0.y;
  30533. this._cachedTextureMatrix.m[10] = this._t0.z;
  30534. var scene = this.getScene();
  30535. if (!scene) {
  30536. return this._cachedTextureMatrix;
  30537. }
  30538. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  30539. return mat.hasTexture(_this);
  30540. });
  30541. return this._cachedTextureMatrix;
  30542. };
  30543. Texture.prototype.getReflectionTextureMatrix = function () {
  30544. var _this = this;
  30545. var scene = this.getScene();
  30546. if (!scene) {
  30547. return this._cachedTextureMatrix;
  30548. }
  30549. if (this.uOffset === this._cachedUOffset &&
  30550. this.vOffset === this._cachedVOffset &&
  30551. this.uScale === this._cachedUScale &&
  30552. this.vScale === this._cachedVScale &&
  30553. this.coordinatesMode === this._cachedCoordinatesMode) {
  30554. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  30555. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  30556. return this._cachedTextureMatrix;
  30557. }
  30558. }
  30559. else {
  30560. return this._cachedTextureMatrix;
  30561. }
  30562. }
  30563. if (!this._cachedTextureMatrix) {
  30564. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  30565. }
  30566. if (!this._projectionModeMatrix) {
  30567. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  30568. }
  30569. this._cachedUOffset = this.uOffset;
  30570. this._cachedVOffset = this.vOffset;
  30571. this._cachedUScale = this.uScale;
  30572. this._cachedVScale = this.vScale;
  30573. this._cachedCoordinatesMode = this.coordinatesMode;
  30574. switch (this.coordinatesMode) {
  30575. case Texture.PLANAR_MODE:
  30576. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  30577. this._cachedTextureMatrix[0] = this.uScale;
  30578. this._cachedTextureMatrix[5] = this.vScale;
  30579. this._cachedTextureMatrix[12] = this.uOffset;
  30580. this._cachedTextureMatrix[13] = this.vOffset;
  30581. break;
  30582. case Texture.PROJECTION_MODE:
  30583. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  30584. this._projectionModeMatrix.m[0] = 0.5;
  30585. this._projectionModeMatrix.m[5] = -0.5;
  30586. this._projectionModeMatrix.m[10] = 0.0;
  30587. this._projectionModeMatrix.m[12] = 0.5;
  30588. this._projectionModeMatrix.m[13] = 0.5;
  30589. this._projectionModeMatrix.m[14] = 1.0;
  30590. this._projectionModeMatrix.m[15] = 1.0;
  30591. var projectionMatrix = scene.getProjectionMatrix();
  30592. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  30593. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  30594. break;
  30595. default:
  30596. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  30597. break;
  30598. }
  30599. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  30600. return (mat.getActiveTextures().indexOf(_this) !== -1);
  30601. });
  30602. return this._cachedTextureMatrix;
  30603. };
  30604. Texture.prototype.clone = function () {
  30605. var _this = this;
  30606. return BABYLON.SerializationHelper.Clone(function () {
  30607. return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  30608. }, this);
  30609. };
  30610. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  30611. get: function () {
  30612. if (!this._onLoadObservable) {
  30613. this._onLoadObservable = new BABYLON.Observable();
  30614. }
  30615. return this._onLoadObservable;
  30616. },
  30617. enumerable: true,
  30618. configurable: true
  30619. });
  30620. Texture.prototype.serialize = function () {
  30621. var serializationObject = _super.prototype.serialize.call(this);
  30622. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  30623. serializationObject.base64String = this._buffer;
  30624. serializationObject.name = serializationObject.name.replace("data:", "");
  30625. }
  30626. serializationObject.invertY = this._invertY;
  30627. serializationObject.samplingMode = this.samplingMode;
  30628. return serializationObject;
  30629. };
  30630. Texture.prototype.getClassName = function () {
  30631. return "Texture";
  30632. };
  30633. Texture.prototype.dispose = function () {
  30634. _super.prototype.dispose.call(this);
  30635. if (this._onLoadObservable) {
  30636. this._onLoadObservable.clear();
  30637. this._onLoadObservable = null;
  30638. }
  30639. this._delayedOnLoad = null;
  30640. this._delayedOnError = null;
  30641. };
  30642. // Statics
  30643. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  30644. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  30645. if (onLoad === void 0) { onLoad = null; }
  30646. if (onError === void 0) { onError = null; }
  30647. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  30648. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  30649. };
  30650. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  30651. if (parsedTexture.customType) {
  30652. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  30653. // Update Sampling Mode
  30654. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  30655. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  30656. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  30657. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  30658. }
  30659. }
  30660. return parsedCustomTexture;
  30661. }
  30662. if (parsedTexture.isCube) {
  30663. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  30664. }
  30665. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  30666. return null;
  30667. }
  30668. var texture = BABYLON.SerializationHelper.Parse(function () {
  30669. var generateMipMaps = true;
  30670. if (parsedTexture.noMipmap) {
  30671. generateMipMaps = false;
  30672. }
  30673. if (parsedTexture.mirrorPlane) {
  30674. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  30675. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  30676. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  30677. return mirrorTexture;
  30678. }
  30679. else if (parsedTexture.isRenderTarget) {
  30680. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  30681. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  30682. return renderTargetTexture;
  30683. }
  30684. else {
  30685. var texture;
  30686. if (parsedTexture.base64String) {
  30687. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene, !generateMipMaps);
  30688. }
  30689. else {
  30690. var url = rootUrl + parsedTexture.name;
  30691. if (Texture.UseSerializedUrlIfAny && parsedTexture.url) {
  30692. url = parsedTexture.url;
  30693. }
  30694. texture = new Texture(url, scene, !generateMipMaps, parsedTexture.invertY);
  30695. }
  30696. return texture;
  30697. }
  30698. }, parsedTexture, scene);
  30699. // Update Sampling Mode
  30700. if (parsedTexture.samplingMode) {
  30701. var sampling = parsedTexture.samplingMode;
  30702. if (texture._samplingMode !== sampling) {
  30703. texture.updateSamplingMode(sampling);
  30704. }
  30705. }
  30706. // Animations
  30707. if (parsedTexture.animations) {
  30708. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  30709. var parsedAnimation = parsedTexture.animations[animationIndex];
  30710. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  30711. }
  30712. }
  30713. return texture;
  30714. };
  30715. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  30716. if (deleteBuffer === void 0) { deleteBuffer = false; }
  30717. if (noMipmap === void 0) { noMipmap = false; }
  30718. if (invertY === void 0) { invertY = true; }
  30719. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  30720. if (onLoad === void 0) { onLoad = null; }
  30721. if (onError === void 0) { onError = null; }
  30722. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  30723. if (name.substr(0, 5) !== "data:") {
  30724. name = "data:" + name;
  30725. }
  30726. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  30727. };
  30728. // Constants
  30729. Texture.NEAREST_SAMPLINGMODE = BABYLON.Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  30730. Texture.NEAREST_NEAREST_MIPLINEAR = BABYLON.Engine.TEXTURE_NEAREST_NEAREST_MIPLINEAR; // nearest is mag = nearest and min = nearest and mip = linear
  30731. Texture.BILINEAR_SAMPLINGMODE = BABYLON.Engine.TEXTURE_BILINEAR_SAMPLINGMODE;
  30732. Texture.LINEAR_LINEAR_MIPNEAREST = BABYLON.Engine.TEXTURE_LINEAR_LINEAR_MIPNEAREST; // Bilinear is mag = linear and min = linear and mip = nearest
  30733. Texture.TRILINEAR_SAMPLINGMODE = BABYLON.Engine.TEXTURE_TRILINEAR_SAMPLINGMODE;
  30734. Texture.LINEAR_LINEAR_MIPLINEAR = BABYLON.Engine.TEXTURE_LINEAR_LINEAR_MIPLINEAR; // Trilinear is mag = linear and min = linear and mip = linear
  30735. Texture.NEAREST_NEAREST_MIPNEAREST = BABYLON.Engine.TEXTURE_NEAREST_NEAREST_MIPNEAREST;
  30736. Texture.NEAREST_LINEAR_MIPNEAREST = BABYLON.Engine.TEXTURE_NEAREST_LINEAR_MIPNEAREST;
  30737. Texture.NEAREST_LINEAR_MIPLINEAR = BABYLON.Engine.TEXTURE_NEAREST_LINEAR_MIPLINEAR;
  30738. Texture.NEAREST_LINEAR = BABYLON.Engine.TEXTURE_NEAREST_LINEAR;
  30739. Texture.NEAREST_NEAREST = BABYLON.Engine.TEXTURE_NEAREST_NEAREST;
  30740. Texture.LINEAR_NEAREST_MIPNEAREST = BABYLON.Engine.TEXTURE_LINEAR_NEAREST_MIPNEAREST;
  30741. Texture.LINEAR_NEAREST_MIPLINEAR = BABYLON.Engine.TEXTURE_LINEAR_NEAREST_MIPLINEAR;
  30742. Texture.LINEAR_LINEAR = BABYLON.Engine.TEXTURE_LINEAR_LINEAR;
  30743. Texture.LINEAR_NEAREST = BABYLON.Engine.TEXTURE_LINEAR_NEAREST;
  30744. Texture.EXPLICIT_MODE = BABYLON.Engine.TEXTURE_EXPLICIT_MODE;
  30745. Texture.SPHERICAL_MODE = BABYLON.Engine.TEXTURE_SPHERICAL_MODE;
  30746. Texture.PLANAR_MODE = BABYLON.Engine.TEXTURE_PLANAR_MODE;
  30747. Texture.CUBIC_MODE = BABYLON.Engine.TEXTURE_CUBIC_MODE;
  30748. Texture.PROJECTION_MODE = BABYLON.Engine.TEXTURE_PROJECTION_MODE;
  30749. Texture.SKYBOX_MODE = BABYLON.Engine.TEXTURE_SKYBOX_MODE;
  30750. Texture.INVCUBIC_MODE = BABYLON.Engine.TEXTURE_INVCUBIC_MODE;
  30751. Texture.EQUIRECTANGULAR_MODE = BABYLON.Engine.TEXTURE_EQUIRECTANGULAR_MODE;
  30752. Texture.FIXED_EQUIRECTANGULAR_MODE = BABYLON.Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MODE;
  30753. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = BABYLON.Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE;
  30754. Texture.CLAMP_ADDRESSMODE = BABYLON.Engine.TEXTURE_CLAMP_ADDRESSMODE;
  30755. Texture.WRAP_ADDRESSMODE = BABYLON.Engine.TEXTURE_WRAP_ADDRESSMODE;
  30756. Texture.MIRROR_ADDRESSMODE = BABYLON.Engine.TEXTURE_MIRROR_ADDRESSMODE;
  30757. /**
  30758. * 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
  30759. */
  30760. Texture.UseSerializedUrlIfAny = false;
  30761. __decorate([
  30762. BABYLON.serialize()
  30763. ], Texture.prototype, "url", void 0);
  30764. __decorate([
  30765. BABYLON.serialize()
  30766. ], Texture.prototype, "uOffset", void 0);
  30767. __decorate([
  30768. BABYLON.serialize()
  30769. ], Texture.prototype, "vOffset", void 0);
  30770. __decorate([
  30771. BABYLON.serialize()
  30772. ], Texture.prototype, "uScale", void 0);
  30773. __decorate([
  30774. BABYLON.serialize()
  30775. ], Texture.prototype, "vScale", void 0);
  30776. __decorate([
  30777. BABYLON.serialize()
  30778. ], Texture.prototype, "uAng", void 0);
  30779. __decorate([
  30780. BABYLON.serialize()
  30781. ], Texture.prototype, "vAng", void 0);
  30782. __decorate([
  30783. BABYLON.serialize()
  30784. ], Texture.prototype, "wAng", void 0);
  30785. __decorate([
  30786. BABYLON.serialize()
  30787. ], Texture.prototype, "uRotationCenter", void 0);
  30788. __decorate([
  30789. BABYLON.serialize()
  30790. ], Texture.prototype, "vRotationCenter", void 0);
  30791. __decorate([
  30792. BABYLON.serialize()
  30793. ], Texture.prototype, "wRotationCenter", void 0);
  30794. __decorate([
  30795. BABYLON.serialize()
  30796. ], Texture.prototype, "isBlocking", null);
  30797. return Texture;
  30798. }(BABYLON.BaseTexture));
  30799. BABYLON.Texture = Texture;
  30800. })(BABYLON || (BABYLON = {}));
  30801. //# sourceMappingURL=babylon.texture.js.map
  30802. var BABYLON;
  30803. (function (BABYLON) {
  30804. /**
  30805. * @hidden
  30806. **/
  30807. var _InstancesBatch = /** @class */ (function () {
  30808. function _InstancesBatch() {
  30809. this.mustReturn = false;
  30810. this.visibleInstances = new Array();
  30811. this.renderSelf = new Array();
  30812. }
  30813. return _InstancesBatch;
  30814. }());
  30815. BABYLON._InstancesBatch = _InstancesBatch;
  30816. /**
  30817. * Class used to represent renderable models
  30818. */
  30819. var Mesh = /** @class */ (function (_super) {
  30820. __extends(Mesh, _super);
  30821. /**
  30822. * @constructor
  30823. * @param name The value used by scene.getMeshByName() to do a lookup.
  30824. * @param scene The scene to add this mesh to.
  30825. * @param parent The parent of this mesh, if it has one
  30826. * @param source An optional Mesh from which geometry is shared, cloned.
  30827. * @param doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  30828. * When false, achieved by calling a clone(), also passing False.
  30829. * This will make creation of children, recursive.
  30830. * @param clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  30831. */
  30832. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  30833. if (scene === void 0) { scene = null; }
  30834. if (parent === void 0) { parent = null; }
  30835. if (source === void 0) { source = null; }
  30836. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  30837. var _this = _super.call(this, name, scene) || this;
  30838. // Members
  30839. /**
  30840. * Gets the delay loading state of the mesh (when delay loading is turned on)
  30841. * @see http://doc.babylonjs.com/how_to/using_the_incremental_loading_system
  30842. */
  30843. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  30844. /**
  30845. * Gets the list of instances created from this mesh
  30846. * @see http://doc.babylonjs.com/how_to/how_to_use_instances
  30847. */
  30848. _this.instances = new Array();
  30849. _this._LODLevels = new Array();
  30850. /** @hidden */
  30851. _this._visibleInstances = {};
  30852. _this._renderIdForInstances = new Array();
  30853. _this._batchCache = new _InstancesBatch();
  30854. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  30855. // Use by builder only to know what orientation were the mesh build in.
  30856. /** @hidden */
  30857. _this._originalBuilderSideOrientation = Mesh.DEFAULTSIDE;
  30858. /**
  30859. * Use this property to change the original side orientation defined at construction time
  30860. */
  30861. _this.overrideMaterialSideOrientation = null;
  30862. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  30863. // Will be used to save a source mesh reference, If any
  30864. _this._source = null;
  30865. scene = _this.getScene();
  30866. if (source) {
  30867. // Geometry
  30868. if (source._geometry) {
  30869. source._geometry.applyToMesh(_this);
  30870. }
  30871. // Deep copy
  30872. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId",
  30873. "source", "metadata", "hasLODLevels", "geometry", "isBlocked", "areNormalsFrozen",
  30874. "onBeforeDrawObservable", "onBeforeRenderObservable", "onAfterRenderObservable", "onBeforeDraw"
  30875. ], ["_poseMatrix"]);
  30876. // Source mesh
  30877. _this._source = source;
  30878. // Construction Params
  30879. // Clone parameters allowing mesh to be updated in case of parametric shapes.
  30880. _this._originalBuilderSideOrientation = source._originalBuilderSideOrientation;
  30881. var myAnyThis = _this;
  30882. var myAnySource = source;
  30883. myAnyThis._closePath = myAnySource._closePath;
  30884. myAnyThis._idx = myAnySource._idx;
  30885. myAnyThis.dashSize = myAnySource.dashSize;
  30886. myAnyThis.gapSize = myAnySource.gapSize;
  30887. myAnyThis.path3D = myAnySource.path3D;
  30888. myAnyThis.pathArray = myAnySource.pathArray;
  30889. myAnyThis.arc = myAnySource.arc;
  30890. myAnyThis.radius = myAnySource.radius;
  30891. // Animation ranges
  30892. if (_this._source._ranges) {
  30893. var ranges = _this._source._ranges;
  30894. for (var name in ranges) {
  30895. if (!ranges.hasOwnProperty(name)) {
  30896. continue;
  30897. }
  30898. if (!ranges[name]) {
  30899. continue;
  30900. }
  30901. _this.createAnimationRange(name, ranges[name].from, ranges[name].to);
  30902. }
  30903. }
  30904. // Metadata
  30905. if (source.metadata && source.metadata.clone) {
  30906. _this.metadata = source.metadata.clone();
  30907. }
  30908. else {
  30909. _this.metadata = source.metadata;
  30910. }
  30911. // Tags
  30912. if (BABYLON.Tags && BABYLON.Tags.HasTags(source)) {
  30913. BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true));
  30914. }
  30915. // Parent
  30916. _this.parent = source.parent;
  30917. // Pivot
  30918. _this.setPivotMatrix(source.getPivotMatrix());
  30919. _this.id = name + "." + source.id;
  30920. // Material
  30921. _this.material = source.material;
  30922. var index;
  30923. if (!doNotCloneChildren) {
  30924. // Children
  30925. var directDescendants = source.getDescendants(true);
  30926. for (var index_1 = 0; index_1 < directDescendants.length; index_1++) {
  30927. var child = directDescendants[index_1];
  30928. if (child.clone) {
  30929. child.clone(name + "." + child.name, _this);
  30930. }
  30931. }
  30932. }
  30933. // Physics clone
  30934. var physicsEngine = _this.getScene().getPhysicsEngine();
  30935. if (clonePhysicsImpostor && physicsEngine) {
  30936. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  30937. if (impostor) {
  30938. _this.physicsImpostor = impostor.clone(_this);
  30939. }
  30940. }
  30941. // Particles
  30942. for (index = 0; index < scene.particleSystems.length; index++) {
  30943. var system = scene.particleSystems[index];
  30944. if (system.emitter === source) {
  30945. system.clone(system.name, _this);
  30946. }
  30947. }
  30948. _this.refreshBoundingInfo();
  30949. _this.computeWorldMatrix(true);
  30950. }
  30951. // Parent
  30952. if (parent !== null) {
  30953. _this.parent = parent;
  30954. }
  30955. return _this;
  30956. }
  30957. Object.defineProperty(Mesh.prototype, "onBeforeRenderObservable", {
  30958. /**
  30959. * An event triggered before rendering the mesh
  30960. */
  30961. get: function () {
  30962. if (!this._onBeforeRenderObservable) {
  30963. this._onBeforeRenderObservable = new BABYLON.Observable();
  30964. }
  30965. return this._onBeforeRenderObservable;
  30966. },
  30967. enumerable: true,
  30968. configurable: true
  30969. });
  30970. Object.defineProperty(Mesh.prototype, "onAfterRenderObservable", {
  30971. /**
  30972. * An event triggered after rendering the mesh
  30973. */
  30974. get: function () {
  30975. if (!this._onAfterRenderObservable) {
  30976. this._onAfterRenderObservable = new BABYLON.Observable();
  30977. }
  30978. return this._onAfterRenderObservable;
  30979. },
  30980. enumerable: true,
  30981. configurable: true
  30982. });
  30983. Object.defineProperty(Mesh.prototype, "onBeforeDrawObservable", {
  30984. /**
  30985. * An event triggered before drawing the mesh
  30986. */
  30987. get: function () {
  30988. if (!this._onBeforeDrawObservable) {
  30989. this._onBeforeDrawObservable = new BABYLON.Observable();
  30990. }
  30991. return this._onBeforeDrawObservable;
  30992. },
  30993. enumerable: true,
  30994. configurable: true
  30995. });
  30996. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  30997. /**
  30998. * Sets a callback to call before drawing the mesh. It is recommended to use onBeforeDrawObservable instead
  30999. */
  31000. set: function (callback) {
  31001. if (this._onBeforeDrawObserver) {
  31002. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  31003. }
  31004. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  31005. },
  31006. enumerable: true,
  31007. configurable: true
  31008. });
  31009. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  31010. /**
  31011. * Gets or sets the morph target manager
  31012. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  31013. */
  31014. get: function () {
  31015. return this._morphTargetManager;
  31016. },
  31017. set: function (value) {
  31018. if (this._morphTargetManager === value) {
  31019. return;
  31020. }
  31021. this._morphTargetManager = value;
  31022. this._syncGeometryWithMorphTargetManager();
  31023. },
  31024. enumerable: true,
  31025. configurable: true
  31026. });
  31027. Object.defineProperty(Mesh.prototype, "source", {
  31028. /**
  31029. * Gets the source mesh (the one used to clone this one from)
  31030. */
  31031. get: function () {
  31032. return this._source;
  31033. },
  31034. enumerable: true,
  31035. configurable: true
  31036. });
  31037. Object.defineProperty(Mesh.prototype, "isUnIndexed", {
  31038. /**
  31039. * Gets or sets a boolean indicating that this mesh does not use index buffer
  31040. */
  31041. get: function () {
  31042. return this._unIndexed;
  31043. },
  31044. set: function (value) {
  31045. if (this._unIndexed !== value) {
  31046. this._unIndexed = value;
  31047. this._markSubMeshesAsAttributesDirty();
  31048. }
  31049. },
  31050. enumerable: true,
  31051. configurable: true
  31052. });
  31053. // Methods
  31054. /**
  31055. * Gets the class name
  31056. * @returns the string "Mesh".
  31057. */
  31058. Mesh.prototype.getClassName = function () {
  31059. return "Mesh";
  31060. };
  31061. /**
  31062. * Returns a description of this mesh
  31063. * @param fullDetails define if full details about this mesh must be used
  31064. * @returns a descriptive string representing this mesh
  31065. */
  31066. Mesh.prototype.toString = function (fullDetails) {
  31067. var ret = _super.prototype.toString.call(this, fullDetails);
  31068. ret += ", n vertices: " + this.getTotalVertices();
  31069. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  31070. if (this.animations) {
  31071. for (var i = 0; i < this.animations.length; i++) {
  31072. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  31073. }
  31074. }
  31075. if (fullDetails) {
  31076. if (this._geometry) {
  31077. var ib = this.getIndices();
  31078. var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31079. if (vb && ib) {
  31080. ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
  31081. }
  31082. }
  31083. else {
  31084. ret += ", flat shading: UNKNOWN";
  31085. }
  31086. }
  31087. return ret;
  31088. };
  31089. /** @hidden */
  31090. Mesh.prototype._unBindEffect = function () {
  31091. _super.prototype._unBindEffect.call(this);
  31092. for (var _i = 0, _a = this.instances; _i < _a.length; _i++) {
  31093. var instance = _a[_i];
  31094. instance._unBindEffect();
  31095. }
  31096. };
  31097. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  31098. /**
  31099. * Gets a boolean indicating if this mesh has LOD
  31100. */
  31101. get: function () {
  31102. return this._LODLevels.length > 0;
  31103. },
  31104. enumerable: true,
  31105. configurable: true
  31106. });
  31107. /**
  31108. * Gets the list of MeshLODLevel associated with the current mesh
  31109. * @returns an array of MeshLODLevel
  31110. */
  31111. Mesh.prototype.getLODLevels = function () {
  31112. return this._LODLevels;
  31113. };
  31114. Mesh.prototype._sortLODLevels = function () {
  31115. this._LODLevels.sort(function (a, b) {
  31116. if (a.distance < b.distance) {
  31117. return 1;
  31118. }
  31119. if (a.distance > b.distance) {
  31120. return -1;
  31121. }
  31122. return 0;
  31123. });
  31124. };
  31125. /**
  31126. * Add a mesh as LOD level triggered at the given distance.
  31127. * @see https://doc.babylonjs.com/how_to/how_to_use_lod
  31128. * @param distance The distance from the center of the object to show this level
  31129. * @param mesh The mesh to be added as LOD level (can be null)
  31130. * @return This mesh (for chaining)
  31131. */
  31132. Mesh.prototype.addLODLevel = function (distance, mesh) {
  31133. if (mesh && mesh._masterMesh) {
  31134. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  31135. return this;
  31136. }
  31137. var level = new BABYLON.MeshLODLevel(distance, mesh);
  31138. this._LODLevels.push(level);
  31139. if (mesh) {
  31140. mesh._masterMesh = this;
  31141. }
  31142. this._sortLODLevels();
  31143. return this;
  31144. };
  31145. /**
  31146. * Returns the LOD level mesh at the passed distance or null if not found.
  31147. * @see https://doc.babylonjs.com/how_to/how_to_use_lod
  31148. * @param distance The distance from the center of the object to show this level
  31149. * @returns a Mesh or `null`
  31150. */
  31151. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  31152. for (var index = 0; index < this._LODLevels.length; index++) {
  31153. var level = this._LODLevels[index];
  31154. if (level.distance === distance) {
  31155. return level.mesh;
  31156. }
  31157. }
  31158. return null;
  31159. };
  31160. /**
  31161. * Remove a mesh from the LOD array
  31162. * @see https://doc.babylonjs.com/how_to/how_to_use_lod
  31163. * @param mesh defines the mesh to be removed
  31164. * @return This mesh (for chaining)
  31165. */
  31166. Mesh.prototype.removeLODLevel = function (mesh) {
  31167. for (var index = 0; index < this._LODLevels.length; index++) {
  31168. if (this._LODLevels[index].mesh === mesh) {
  31169. this._LODLevels.splice(index, 1);
  31170. if (mesh) {
  31171. mesh._masterMesh = null;
  31172. }
  31173. }
  31174. }
  31175. this._sortLODLevels();
  31176. return this;
  31177. };
  31178. /**
  31179. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  31180. * @see https://doc.babylonjs.com/how_to/how_to_use_lod
  31181. * @param camera defines the camera to use to compute distance
  31182. * @param boundingSphere defines a custom bounding sphere to use instead of the one from this mesh
  31183. * @return This mesh (for chaining)
  31184. */
  31185. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  31186. if (!this._LODLevels || this._LODLevels.length === 0) {
  31187. return this;
  31188. }
  31189. var bSphere;
  31190. if (boundingSphere) {
  31191. bSphere = boundingSphere;
  31192. }
  31193. else {
  31194. var boundingInfo = this.getBoundingInfo();
  31195. bSphere = boundingInfo.boundingSphere;
  31196. }
  31197. var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
  31198. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  31199. if (this.onLODLevelSelection) {
  31200. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  31201. }
  31202. return this;
  31203. }
  31204. for (var index = 0; index < this._LODLevels.length; index++) {
  31205. var level = this._LODLevels[index];
  31206. if (level.distance < distanceToCamera) {
  31207. if (level.mesh) {
  31208. level.mesh._preActivate();
  31209. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  31210. }
  31211. if (this.onLODLevelSelection) {
  31212. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  31213. }
  31214. return level.mesh;
  31215. }
  31216. }
  31217. if (this.onLODLevelSelection) {
  31218. this.onLODLevelSelection(distanceToCamera, this, this);
  31219. }
  31220. return this;
  31221. };
  31222. Object.defineProperty(Mesh.prototype, "geometry", {
  31223. /**
  31224. * Gets the mesh internal Geometry object
  31225. */
  31226. get: function () {
  31227. return this._geometry;
  31228. },
  31229. enumerable: true,
  31230. configurable: true
  31231. });
  31232. /**
  31233. * Returns the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  31234. * @returns the total number of vertices
  31235. */
  31236. Mesh.prototype.getTotalVertices = function () {
  31237. if (this._geometry === null || this._geometry === undefined) {
  31238. return 0;
  31239. }
  31240. return this._geometry.getTotalVertices();
  31241. };
  31242. /**
  31243. * Returns the content of an associated vertex buffer
  31244. * @param kind defines which buffer to read from (positions, indices, normals, etc). Possible `kind` values :
  31245. * - BABYLON.VertexBuffer.PositionKind
  31246. * - BABYLON.VertexBuffer.UVKind
  31247. * - BABYLON.VertexBuffer.UV2Kind
  31248. * - BABYLON.VertexBuffer.UV3Kind
  31249. * - BABYLON.VertexBuffer.UV4Kind
  31250. * - BABYLON.VertexBuffer.UV5Kind
  31251. * - BABYLON.VertexBuffer.UV6Kind
  31252. * - BABYLON.VertexBuffer.ColorKind
  31253. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31254. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31255. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31256. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31257. * @param copyWhenShared defines a boolean indicating that if the mesh geometry is shared among some other meshes, the returned array is a copy of the internal one
  31258. * @param forceCopy defines a boolean forcing the copy of the buffer no matter what the value of copyWhenShared is
  31259. * @returns a FloatArray or null if the mesh has no geometry or no vertex buffer for this kind.
  31260. */
  31261. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  31262. if (!this._geometry) {
  31263. return null;
  31264. }
  31265. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  31266. };
  31267. /**
  31268. * Returns the mesh VertexBuffer object from the requested `kind`
  31269. * @param kind defines which buffer to read from (positions, indices, normals, etc). Possible `kind` values :
  31270. * - BABYLON.VertexBuffer.PositionKind
  31271. * - BABYLON.VertexBuffer.UVKind
  31272. * - BABYLON.VertexBuffer.UV2Kind
  31273. * - BABYLON.VertexBuffer.UV3Kind
  31274. * - BABYLON.VertexBuffer.UV4Kind
  31275. * - BABYLON.VertexBuffer.UV5Kind
  31276. * - BABYLON.VertexBuffer.UV6Kind
  31277. * - BABYLON.VertexBuffer.ColorKind
  31278. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31279. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31280. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31281. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31282. * @returns a FloatArray or null if the mesh has no vertex buffer for this kind.
  31283. */
  31284. Mesh.prototype.getVertexBuffer = function (kind) {
  31285. if (!this._geometry) {
  31286. return null;
  31287. }
  31288. return this._geometry.getVertexBuffer(kind);
  31289. };
  31290. /**
  31291. * Tests if a specific vertex buffer is associated with this mesh
  31292. * @param kind defines which buffer to check (positions, indices, normals, etc). Possible `kind` values :
  31293. * - BABYLON.VertexBuffer.PositionKind
  31294. * - BABYLON.VertexBuffer.UVKind
  31295. * - BABYLON.VertexBuffer.UV2Kind
  31296. * - BABYLON.VertexBuffer.UV3Kind
  31297. * - BABYLON.VertexBuffer.UV4Kind
  31298. * - BABYLON.VertexBuffer.UV5Kind
  31299. * - BABYLON.VertexBuffer.UV6Kind
  31300. * - BABYLON.VertexBuffer.ColorKind
  31301. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31302. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31303. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31304. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31305. * @returns a boolean
  31306. */
  31307. Mesh.prototype.isVerticesDataPresent = function (kind) {
  31308. if (!this._geometry) {
  31309. if (this._delayInfo) {
  31310. return this._delayInfo.indexOf(kind) !== -1;
  31311. }
  31312. return false;
  31313. }
  31314. return this._geometry.isVerticesDataPresent(kind);
  31315. };
  31316. /**
  31317. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  31318. * @param kind defines which buffer to check (positions, indices, normals, etc). Possible `kind` values :
  31319. * - BABYLON.VertexBuffer.PositionKind
  31320. * - BABYLON.VertexBuffer.UVKind
  31321. * - BABYLON.VertexBuffer.UV2Kind
  31322. * - BABYLON.VertexBuffer.UV3Kind
  31323. * - BABYLON.VertexBuffer.UV4Kind
  31324. * - BABYLON.VertexBuffer.UV5Kind
  31325. * - BABYLON.VertexBuffer.UV6Kind
  31326. * - BABYLON.VertexBuffer.ColorKind
  31327. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31328. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31329. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31330. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31331. * @returns a boolean
  31332. */
  31333. Mesh.prototype.isVertexBufferUpdatable = function (kind) {
  31334. if (!this._geometry) {
  31335. if (this._delayInfo) {
  31336. return this._delayInfo.indexOf(kind) !== -1;
  31337. }
  31338. return false;
  31339. }
  31340. return this._geometry.isVertexBufferUpdatable(kind);
  31341. };
  31342. /**
  31343. * Returns a string which contains the list of existing `kinds` of Vertex Data associated with this mesh.
  31344. * @param kind defines which buffer to read from (positions, indices, normals, etc). Possible `kind` values :
  31345. * - BABYLON.VertexBuffer.PositionKind
  31346. * - BABYLON.VertexBuffer.UVKind
  31347. * - BABYLON.VertexBuffer.UV2Kind
  31348. * - BABYLON.VertexBuffer.UV3Kind
  31349. * - BABYLON.VertexBuffer.UV4Kind
  31350. * - BABYLON.VertexBuffer.UV5Kind
  31351. * - BABYLON.VertexBuffer.UV6Kind
  31352. * - BABYLON.VertexBuffer.ColorKind
  31353. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31354. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31355. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31356. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31357. * @returns an array of strings
  31358. */
  31359. Mesh.prototype.getVerticesDataKinds = function () {
  31360. if (!this._geometry) {
  31361. var result = new Array();
  31362. if (this._delayInfo) {
  31363. this._delayInfo.forEach(function (kind, index, array) {
  31364. result.push(kind);
  31365. });
  31366. }
  31367. return result;
  31368. }
  31369. return this._geometry.getVerticesDataKinds();
  31370. };
  31371. /**
  31372. * Returns a positive integer : the total number of indices in this mesh geometry.
  31373. * @returns the numner of indices or zero if the mesh has no geometry.
  31374. */
  31375. Mesh.prototype.getTotalIndices = function () {
  31376. if (!this._geometry) {
  31377. return 0;
  31378. }
  31379. return this._geometry.getTotalIndices();
  31380. };
  31381. /**
  31382. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  31383. * @param copyWhenShared If 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.
  31384. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  31385. * @returns the indices array or an empty array if the mesh has no geometry
  31386. */
  31387. Mesh.prototype.getIndices = function (copyWhenShared, forceCopy) {
  31388. if (!this._geometry) {
  31389. return [];
  31390. }
  31391. return this._geometry.getIndices(copyWhenShared, forceCopy);
  31392. };
  31393. Object.defineProperty(Mesh.prototype, "isBlocked", {
  31394. get: function () {
  31395. return this._masterMesh !== null && this._masterMesh !== undefined;
  31396. },
  31397. enumerable: true,
  31398. configurable: true
  31399. });
  31400. /**
  31401. * Determine if the current mesh is ready to be rendered
  31402. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  31403. * @param forceInstanceSupport will check if the mesh will be ready when used with instances (false by default)
  31404. * @returns true if all associated assets are ready (material, textures, shaders)
  31405. */
  31406. Mesh.prototype.isReady = function (completeCheck, forceInstanceSupport) {
  31407. if (completeCheck === void 0) { completeCheck = false; }
  31408. if (forceInstanceSupport === void 0) { forceInstanceSupport = false; }
  31409. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  31410. return false;
  31411. }
  31412. if (!_super.prototype.isReady.call(this, completeCheck)) {
  31413. return false;
  31414. }
  31415. if (!this.subMeshes || this.subMeshes.length === 0) {
  31416. return true;
  31417. }
  31418. if (!completeCheck) {
  31419. return true;
  31420. }
  31421. var engine = this.getEngine();
  31422. var scene = this.getScene();
  31423. var hardwareInstancedRendering = forceInstanceSupport || engine.getCaps().instancedArrays && this.instances.length > 0;
  31424. this.computeWorldMatrix();
  31425. var mat = this.material || scene.defaultMaterial;
  31426. if (mat) {
  31427. if (mat.storeEffectOnSubMeshes) {
  31428. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  31429. var subMesh = _a[_i];
  31430. var effectiveMaterial = subMesh.getMaterial();
  31431. if (effectiveMaterial) {
  31432. if (effectiveMaterial.storeEffectOnSubMeshes) {
  31433. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  31434. return false;
  31435. }
  31436. }
  31437. else {
  31438. if (!effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  31439. return false;
  31440. }
  31441. }
  31442. }
  31443. }
  31444. }
  31445. else {
  31446. if (!mat.isReady(this, hardwareInstancedRendering)) {
  31447. return false;
  31448. }
  31449. }
  31450. }
  31451. // Shadows
  31452. for (var _b = 0, _c = this._lightSources; _b < _c.length; _b++) {
  31453. var light = _c[_b];
  31454. var generator = light.getShadowGenerator();
  31455. if (generator) {
  31456. for (var _d = 0, _e = this.subMeshes; _d < _e.length; _d++) {
  31457. var subMesh = _e[_d];
  31458. if (!generator.isReady(subMesh, hardwareInstancedRendering)) {
  31459. return false;
  31460. }
  31461. }
  31462. }
  31463. }
  31464. // LOD
  31465. for (var _f = 0, _g = this._LODLevels; _f < _g.length; _f++) {
  31466. var lod = _g[_f];
  31467. if (lod.mesh && !lod.mesh.isReady(hardwareInstancedRendering)) {
  31468. return false;
  31469. }
  31470. }
  31471. return true;
  31472. };
  31473. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  31474. /**
  31475. * Gets a boolean indicating if the normals aren't to be recomputed on next mesh `positions` array update. This property is pertinent only for updatable parametric shapes.
  31476. */
  31477. get: function () {
  31478. return this._areNormalsFrozen;
  31479. },
  31480. enumerable: true,
  31481. configurable: true
  31482. });
  31483. /**
  31484. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc. It has no effect at all on other shapes. It prevents the mesh normals from being recomputed on next `positions` array update.
  31485. * @returns the current mesh
  31486. */
  31487. Mesh.prototype.freezeNormals = function () {
  31488. this._areNormalsFrozen = true;
  31489. return this;
  31490. };
  31491. /**
  31492. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc. It has no effect at all on other shapes. It reactivates the mesh normals computation if it was previously frozen
  31493. * @returns the current mesh
  31494. */
  31495. Mesh.prototype.unfreezeNormals = function () {
  31496. this._areNormalsFrozen = false;
  31497. return this;
  31498. };
  31499. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  31500. /**
  31501. * Sets a value overriding the instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  31502. */
  31503. set: function (count) {
  31504. this._overridenInstanceCount = count;
  31505. },
  31506. enumerable: true,
  31507. configurable: true
  31508. });
  31509. // Methods
  31510. /** @hidden */
  31511. Mesh.prototype._preActivate = function () {
  31512. var sceneRenderId = this.getScene().getRenderId();
  31513. if (this._preActivateId === sceneRenderId) {
  31514. return this;
  31515. }
  31516. this._preActivateId = sceneRenderId;
  31517. this._visibleInstances = null;
  31518. return this;
  31519. };
  31520. /** @hidden */
  31521. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  31522. if (this._visibleInstances) {
  31523. this._visibleInstances.intermediateDefaultRenderId = renderId;
  31524. }
  31525. return this;
  31526. };
  31527. /** @hidden */
  31528. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  31529. if (!this._visibleInstances) {
  31530. this._visibleInstances = {};
  31531. this._visibleInstances.defaultRenderId = renderId;
  31532. this._visibleInstances.selfDefaultRenderId = this._renderId;
  31533. }
  31534. if (!this._visibleInstances[renderId]) {
  31535. this._visibleInstances[renderId] = new Array();
  31536. }
  31537. this._visibleInstances[renderId].push(instance);
  31538. return this;
  31539. };
  31540. /**
  31541. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  31542. * This means the mesh underlying bounding box and sphere are recomputed.
  31543. * @returns the current mesh
  31544. */
  31545. Mesh.prototype.refreshBoundingInfo = function () {
  31546. return this._refreshBoundingInfo(false);
  31547. };
  31548. /** @hidden */
  31549. Mesh.prototype._refreshBoundingInfo = function (applySkeleton) {
  31550. if (this._boundingInfo && this._boundingInfo.isLocked) {
  31551. return this;
  31552. }
  31553. var data = this._getPositionData(applySkeleton);
  31554. if (data) {
  31555. var bias = this.geometry ? this.geometry.boundingBias : null;
  31556. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices(), bias);
  31557. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  31558. }
  31559. if (this.subMeshes) {
  31560. for (var index = 0; index < this.subMeshes.length; index++) {
  31561. this.subMeshes[index].refreshBoundingInfo();
  31562. }
  31563. }
  31564. this._updateBoundingInfo();
  31565. return this;
  31566. };
  31567. Mesh.prototype._getPositionData = function (applySkeleton) {
  31568. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31569. if (data && applySkeleton && this.skeleton) {
  31570. data = BABYLON.Tools.Slice(data);
  31571. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  31572. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  31573. if (matricesWeightsData && matricesIndicesData) {
  31574. var needExtras = this.numBoneInfluencers > 4;
  31575. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  31576. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  31577. var skeletonMatrices = this.skeleton.getTransformMatrices(this);
  31578. var tempVector = BABYLON.Tmp.Vector3[0];
  31579. var finalMatrix = BABYLON.Tmp.Matrix[0];
  31580. var tempMatrix = BABYLON.Tmp.Matrix[1];
  31581. var matWeightIdx = 0;
  31582. for (var index = 0; index < data.length; index += 3, matWeightIdx += 4) {
  31583. finalMatrix.reset();
  31584. var inf;
  31585. var weight;
  31586. for (inf = 0; inf < 4; inf++) {
  31587. weight = matricesWeightsData[matWeightIdx + inf];
  31588. if (weight > 0) {
  31589. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  31590. finalMatrix.addToSelf(tempMatrix);
  31591. }
  31592. }
  31593. if (needExtras) {
  31594. for (inf = 0; inf < 4; inf++) {
  31595. weight = matricesWeightsExtraData[matWeightIdx + inf];
  31596. if (weight > 0) {
  31597. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  31598. finalMatrix.addToSelf(tempMatrix);
  31599. }
  31600. }
  31601. }
  31602. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(data[index], data[index + 1], data[index + 2], finalMatrix, tempVector);
  31603. tempVector.toArray(data, index);
  31604. }
  31605. }
  31606. }
  31607. return data;
  31608. };
  31609. /** @hidden */
  31610. Mesh.prototype._createGlobalSubMesh = function (force) {
  31611. var totalVertices = this.getTotalVertices();
  31612. if (!totalVertices || !this.getIndices()) {
  31613. return null;
  31614. }
  31615. // Check if we need to recreate the submeshes
  31616. if (this.subMeshes && this.subMeshes.length > 0) {
  31617. var ib = this.getIndices();
  31618. if (!ib) {
  31619. return null;
  31620. }
  31621. var totalIndices = ib.length;
  31622. var needToRecreate = false;
  31623. if (force) {
  31624. needToRecreate = true;
  31625. }
  31626. else {
  31627. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  31628. var submesh = _a[_i];
  31629. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  31630. needToRecreate = true;
  31631. break;
  31632. }
  31633. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  31634. needToRecreate = true;
  31635. break;
  31636. }
  31637. }
  31638. }
  31639. if (!needToRecreate) {
  31640. return this.subMeshes[0];
  31641. }
  31642. }
  31643. this.releaseSubMeshes();
  31644. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  31645. };
  31646. /**
  31647. * This function will subdivide the mesh into multiple submeshes
  31648. * @param count defines the expected number of submeshes
  31649. */
  31650. Mesh.prototype.subdivide = function (count) {
  31651. if (count < 1) {
  31652. return;
  31653. }
  31654. var totalIndices = this.getTotalIndices();
  31655. var subdivisionSize = (totalIndices / count) | 0;
  31656. var offset = 0;
  31657. // Ensure that subdivisionSize is a multiple of 3
  31658. while (subdivisionSize % 3 !== 0) {
  31659. subdivisionSize++;
  31660. }
  31661. this.releaseSubMeshes();
  31662. for (var index = 0; index < count; index++) {
  31663. if (offset >= totalIndices) {
  31664. break;
  31665. }
  31666. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  31667. offset += subdivisionSize;
  31668. }
  31669. this.synchronizeInstances();
  31670. };
  31671. /**
  31672. * Copy a FloatArray into a specific associated vertex buffer
  31673. * @param kind defines which buffer to write to (positions, indices, normals, etc). Possible `kind` values :
  31674. * - BABYLON.VertexBuffer.PositionKind
  31675. * - BABYLON.VertexBuffer.UVKind
  31676. * - BABYLON.VertexBuffer.UV2Kind
  31677. * - BABYLON.VertexBuffer.UV3Kind
  31678. * - BABYLON.VertexBuffer.UV4Kind
  31679. * - BABYLON.VertexBuffer.UV5Kind
  31680. * - BABYLON.VertexBuffer.UV6Kind
  31681. * - BABYLON.VertexBuffer.ColorKind
  31682. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31683. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31684. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31685. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31686. * @param data defines the data source
  31687. * @param updatable defines if the updated vertex buffer must be flagged as updatable
  31688. * @param stride defines the data stride size (can be null)
  31689. * @returns the current mesh
  31690. */
  31691. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  31692. if (updatable === void 0) { updatable = false; }
  31693. if (!this._geometry) {
  31694. var vertexData = new BABYLON.VertexData();
  31695. vertexData.set(data, kind);
  31696. var scene = this.getScene();
  31697. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  31698. }
  31699. else {
  31700. this._geometry.setVerticesData(kind, data, updatable, stride);
  31701. }
  31702. return this;
  31703. };
  31704. /**
  31705. * Flags an associated vertex buffer as updatable
  31706. * @param kind defines which buffer to use (positions, indices, normals, etc). Possible `kind` values :
  31707. * - BABYLON.VertexBuffer.PositionKind
  31708. * - BABYLON.VertexBuffer.UVKind
  31709. * - BABYLON.VertexBuffer.UV2Kind
  31710. * - BABYLON.VertexBuffer.UV3Kind
  31711. * - BABYLON.VertexBuffer.UV4Kind
  31712. * - BABYLON.VertexBuffer.UV5Kind
  31713. * - BABYLON.VertexBuffer.UV6Kind
  31714. * - BABYLON.VertexBuffer.ColorKind
  31715. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31716. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31717. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31718. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31719. * @param updatable defines if the updated vertex buffer must be flagged as updatable
  31720. */
  31721. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  31722. if (updatable === void 0) { updatable = true; }
  31723. var vb = this.getVertexBuffer(kind);
  31724. if (!vb || vb.isUpdatable() === updatable) {
  31725. return;
  31726. }
  31727. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  31728. };
  31729. /**
  31730. * Sets the mesh global Vertex Buffer
  31731. * @param buffer defines the buffer to use
  31732. * @returns the current mesh
  31733. */
  31734. Mesh.prototype.setVerticesBuffer = function (buffer) {
  31735. if (!this._geometry) {
  31736. this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this);
  31737. }
  31738. this._geometry.setVerticesBuffer(buffer);
  31739. return this;
  31740. };
  31741. /**
  31742. * Update a specific associated vertex buffer
  31743. * @param kind defines which buffer to write to (positions, indices, normals, etc). Possible `kind` values :
  31744. * - BABYLON.VertexBuffer.PositionKind
  31745. * - BABYLON.VertexBuffer.UVKind
  31746. * - BABYLON.VertexBuffer.UV2Kind
  31747. * - BABYLON.VertexBuffer.UV3Kind
  31748. * - BABYLON.VertexBuffer.UV4Kind
  31749. * - BABYLON.VertexBuffer.UV5Kind
  31750. * - BABYLON.VertexBuffer.UV6Kind
  31751. * - BABYLON.VertexBuffer.ColorKind
  31752. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31753. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31754. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31755. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31756. * @param data defines the data source
  31757. * @param updateExtends defines if extends info of the mesh must be updated (can be null). This is mostly useful for "position" kind
  31758. * @param makeItUnique defines if the geometry associated with the mesh must be cloned to make the change only for this mesh (and not all meshes associated with the same geometry)
  31759. * @returns the current mesh
  31760. */
  31761. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  31762. if (!this._geometry) {
  31763. return this;
  31764. }
  31765. if (!makeItUnique) {
  31766. this._geometry.updateVerticesData(kind, data, updateExtends);
  31767. }
  31768. else {
  31769. this.makeGeometryUnique();
  31770. this.updateVerticesData(kind, data, updateExtends, false);
  31771. }
  31772. return this;
  31773. };
  31774. /**
  31775. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  31776. * @see http://doc.babylonjs.com/how_to/how_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  31777. * @param positionFunction is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything
  31778. * @param computeNormals is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update
  31779. * @returns the current mesh
  31780. */
  31781. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  31782. if (computeNormals === void 0) { computeNormals = true; }
  31783. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31784. if (!positions) {
  31785. return this;
  31786. }
  31787. positionFunction(positions);
  31788. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  31789. if (computeNormals) {
  31790. var indices = this.getIndices();
  31791. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  31792. if (!normals) {
  31793. return this;
  31794. }
  31795. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  31796. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  31797. }
  31798. return this;
  31799. };
  31800. /**
  31801. * Creates a un-shared specific occurence of the geometry for the mesh.
  31802. * @returns the current mesh
  31803. */
  31804. Mesh.prototype.makeGeometryUnique = function () {
  31805. if (!this._geometry) {
  31806. return this;
  31807. }
  31808. var oldGeometry = this._geometry;
  31809. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  31810. oldGeometry.releaseForMesh(this, true);
  31811. geometry.applyToMesh(this);
  31812. return this;
  31813. };
  31814. /**
  31815. * Set the index buffer of this mesh
  31816. * @param indices defines the source data
  31817. * @param totalVertices defines the total number of vertices referenced by this index data (can be null)
  31818. * @param updatable defines if the updated index buffer must be flagged as updatable (default is false)
  31819. * @returns the current mesh
  31820. */
  31821. Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
  31822. if (totalVertices === void 0) { totalVertices = null; }
  31823. if (updatable === void 0) { updatable = false; }
  31824. if (!this._geometry) {
  31825. var vertexData = new BABYLON.VertexData();
  31826. vertexData.indices = indices;
  31827. var scene = this.getScene();
  31828. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  31829. }
  31830. else {
  31831. this._geometry.setIndices(indices, totalVertices, updatable);
  31832. }
  31833. return this;
  31834. };
  31835. /**
  31836. * Update the current index buffer
  31837. * @param indices defines the source data
  31838. * @param offset defines the offset in the index buffer where to store the new data (can be null)
  31839. * @returns the current mesh
  31840. */
  31841. Mesh.prototype.updateIndices = function (indices, offset) {
  31842. if (!this._geometry) {
  31843. return this;
  31844. }
  31845. this._geometry.updateIndices(indices, offset);
  31846. return this;
  31847. };
  31848. /**
  31849. * Invert the geometry to move from a right handed system to a left handed one.
  31850. * @returns the current mesh
  31851. */
  31852. Mesh.prototype.toLeftHanded = function () {
  31853. if (!this._geometry) {
  31854. return this;
  31855. }
  31856. this._geometry.toLeftHanded();
  31857. return this;
  31858. };
  31859. /** @hidden */
  31860. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  31861. if (!this._geometry) {
  31862. return this;
  31863. }
  31864. var engine = this.getScene().getEngine();
  31865. // Wireframe
  31866. var indexToBind;
  31867. if (this._unIndexed) {
  31868. indexToBind = null;
  31869. }
  31870. else {
  31871. switch (fillMode) {
  31872. case BABYLON.Material.PointFillMode:
  31873. indexToBind = null;
  31874. break;
  31875. case BABYLON.Material.WireFrameFillMode:
  31876. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  31877. break;
  31878. default:
  31879. case BABYLON.Material.TriangleFillMode:
  31880. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  31881. break;
  31882. }
  31883. }
  31884. // VBOs
  31885. this._geometry._bind(effect, indexToBind);
  31886. return this;
  31887. };
  31888. /** @hidden */
  31889. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  31890. if (alternate === void 0) { alternate = false; }
  31891. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  31892. return this;
  31893. }
  31894. if (this._onBeforeDrawObservable) {
  31895. this._onBeforeDrawObservable.notifyObservers(this);
  31896. }
  31897. var scene = this.getScene();
  31898. var engine = scene.getEngine();
  31899. if (this._unIndexed || fillMode == BABYLON.Material.PointFillMode) {
  31900. // or triangles as points
  31901. engine.drawArraysType(fillMode, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  31902. }
  31903. else if (fillMode == BABYLON.Material.WireFrameFillMode) {
  31904. // Triangles as wireframe
  31905. engine.drawElementsType(fillMode, 0, subMesh.linesIndexCount, instancesCount);
  31906. }
  31907. else {
  31908. engine.drawElementsType(fillMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  31909. }
  31910. if (scene._isAlternateRenderingEnabled && !alternate) {
  31911. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  31912. if (!effect || !scene.activeCamera) {
  31913. return this;
  31914. }
  31915. scene._switchToAlternateCameraConfiguration(true);
  31916. this._effectiveMaterial.bindView(effect);
  31917. this._effectiveMaterial.bindViewProjection(effect);
  31918. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  31919. this._draw(subMesh, fillMode, instancesCount, true);
  31920. engine.setViewport(scene.activeCamera.viewport);
  31921. scene._switchToAlternateCameraConfiguration(false);
  31922. this._effectiveMaterial.bindView(effect);
  31923. this._effectiveMaterial.bindViewProjection(effect);
  31924. }
  31925. return this;
  31926. };
  31927. /**
  31928. * Registers for this mesh a javascript function called just before the rendering process
  31929. * @param func defines the function to call before rendering this mesh
  31930. * @returns the current mesh
  31931. */
  31932. Mesh.prototype.registerBeforeRender = function (func) {
  31933. this.onBeforeRenderObservable.add(func);
  31934. return this;
  31935. };
  31936. /**
  31937. * Disposes a previously registered javascript function called before the rendering
  31938. * @param func defines the function to remove
  31939. * @returns the current mesh
  31940. */
  31941. Mesh.prototype.unregisterBeforeRender = function (func) {
  31942. this.onBeforeRenderObservable.removeCallback(func);
  31943. return this;
  31944. };
  31945. /**
  31946. * Registers for this mesh a javascript function called just after the rendering is complete
  31947. * @param func defines the function to call after rendering this mesh
  31948. * @returns the current mesh
  31949. */
  31950. Mesh.prototype.registerAfterRender = function (func) {
  31951. this.onAfterRenderObservable.add(func);
  31952. return this;
  31953. };
  31954. /**
  31955. * Disposes a previously registered javascript function called after the rendering.
  31956. * @param func defines the function to remove
  31957. * @returns the current mesh
  31958. */
  31959. Mesh.prototype.unregisterAfterRender = function (func) {
  31960. this.onAfterRenderObservable.removeCallback(func);
  31961. return this;
  31962. };
  31963. /** @hidden */
  31964. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  31965. var scene = this.getScene();
  31966. this._batchCache.mustReturn = false;
  31967. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  31968. this._batchCache.visibleInstances[subMeshId] = null;
  31969. if (this._visibleInstances) {
  31970. var currentRenderId = scene.getRenderId();
  31971. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  31972. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  31973. var selfRenderId = this._renderId;
  31974. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  31975. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  31976. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  31977. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  31978. }
  31979. var visibleInstancesForSubMesh = this._batchCache.visibleInstances[subMeshId];
  31980. if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
  31981. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  31982. this._batchCache.mustReturn = true;
  31983. return this._batchCache;
  31984. }
  31985. if (currentRenderId !== selfRenderId) {
  31986. this._batchCache.renderSelf[subMeshId] = false;
  31987. }
  31988. }
  31989. this._renderIdForInstances[subMeshId] = currentRenderId;
  31990. }
  31991. return this._batchCache;
  31992. };
  31993. /** @hidden */
  31994. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  31995. var visibleInstances = batch.visibleInstances[subMesh._id];
  31996. if (!visibleInstances) {
  31997. return this;
  31998. }
  31999. var matricesCount = visibleInstances.length + 1;
  32000. var bufferSize = matricesCount * 16 * 4;
  32001. var currentInstancesBufferSize = this._instancesBufferSize;
  32002. var instancesBuffer = this._instancesBuffer;
  32003. while (this._instancesBufferSize < bufferSize) {
  32004. this._instancesBufferSize *= 2;
  32005. }
  32006. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  32007. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  32008. }
  32009. var offset = 0;
  32010. var instancesCount = 0;
  32011. var world = this.getWorldMatrix();
  32012. if (batch.renderSelf[subMesh._id]) {
  32013. world.copyToArray(this._instancesData, offset);
  32014. offset += 16;
  32015. instancesCount++;
  32016. }
  32017. if (visibleInstances) {
  32018. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  32019. var instance = visibleInstances[instanceIndex];
  32020. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  32021. offset += 16;
  32022. instancesCount++;
  32023. }
  32024. }
  32025. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  32026. if (instancesBuffer) {
  32027. instancesBuffer.dispose();
  32028. }
  32029. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  32030. this._instancesBuffer = instancesBuffer;
  32031. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  32032. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  32033. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  32034. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  32035. }
  32036. else {
  32037. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  32038. }
  32039. this._bind(subMesh, effect, fillMode);
  32040. this._draw(subMesh, fillMode, instancesCount);
  32041. engine.unbindInstanceAttributes();
  32042. return this;
  32043. };
  32044. /** @hidden */
  32045. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  32046. var scene = this.getScene();
  32047. var engine = scene.getEngine();
  32048. if (hardwareInstancedRendering) {
  32049. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  32050. }
  32051. else {
  32052. if (batch.renderSelf[subMesh._id]) {
  32053. // Draw
  32054. if (onBeforeDraw) {
  32055. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  32056. }
  32057. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  32058. }
  32059. var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
  32060. if (visibleInstancesForSubMesh) {
  32061. for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
  32062. var instance = visibleInstancesForSubMesh[instanceIndex];
  32063. // World
  32064. var world = instance.getWorldMatrix();
  32065. if (onBeforeDraw) {
  32066. onBeforeDraw(true, world, effectiveMaterial);
  32067. }
  32068. // Draw
  32069. this._draw(subMesh, fillMode);
  32070. }
  32071. }
  32072. }
  32073. return this;
  32074. };
  32075. /**
  32076. * Triggers the draw call for the mesh. Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager
  32077. * @param subMesh defines the subMesh to render
  32078. * @param enableAlphaMode defines if alpha mode can be changed
  32079. * @returns the current mesh
  32080. */
  32081. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  32082. this._checkOcclusionQuery();
  32083. if (this._isOccluded) {
  32084. return this;
  32085. }
  32086. var scene = this.getScene();
  32087. // Managing instances
  32088. var batch = this._getInstancesRenderList(subMesh._id);
  32089. if (batch.mustReturn) {
  32090. return this;
  32091. }
  32092. // Checking geometry state
  32093. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  32094. return this;
  32095. }
  32096. if (this._onBeforeRenderObservable) {
  32097. this._onBeforeRenderObservable.notifyObservers(this);
  32098. }
  32099. var engine = scene.getEngine();
  32100. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  32101. // Material
  32102. var material = subMesh.getMaterial();
  32103. if (!material) {
  32104. return this;
  32105. }
  32106. this._effectiveMaterial = material;
  32107. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32108. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  32109. return this;
  32110. }
  32111. }
  32112. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  32113. return this;
  32114. }
  32115. // Alpha mode
  32116. if (enableAlphaMode) {
  32117. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  32118. }
  32119. for (var _i = 0, _a = scene._beforeRenderingMeshStage; _i < _a.length; _i++) {
  32120. var step = _a[_i];
  32121. step.action(this, subMesh, batch);
  32122. }
  32123. var effect;
  32124. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32125. effect = subMesh.effect;
  32126. }
  32127. else {
  32128. effect = this._effectiveMaterial.getEffect();
  32129. }
  32130. if (!effect) {
  32131. return this;
  32132. }
  32133. var sideOrientation = this.overrideMaterialSideOrientation;
  32134. if (sideOrientation == null) {
  32135. sideOrientation = this._effectiveMaterial.sideOrientation;
  32136. if (this._getWorldMatrixDeterminant() < 0) {
  32137. sideOrientation = (sideOrientation === BABYLON.Material.ClockWiseSideOrientation ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation);
  32138. }
  32139. }
  32140. var reverse = this._effectiveMaterial._preBind(effect, sideOrientation);
  32141. if (this._effectiveMaterial.forceDepthWrite) {
  32142. engine.setDepthWrite(true);
  32143. }
  32144. // Bind
  32145. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  32146. if (!hardwareInstancedRendering) { // Binding will be done later because we need to add more info to the VB
  32147. this._bind(subMesh, effect, fillMode);
  32148. }
  32149. var world = this.getWorldMatrix();
  32150. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32151. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  32152. }
  32153. else {
  32154. this._effectiveMaterial.bind(world, this);
  32155. }
  32156. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  32157. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  32158. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  32159. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  32160. }
  32161. // Draw
  32162. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  32163. // Unbind
  32164. this._effectiveMaterial.unbind();
  32165. for (var _b = 0, _c = scene._afterRenderingMeshStage; _b < _c.length; _b++) {
  32166. var step = _c[_b];
  32167. step.action(this, subMesh, batch);
  32168. }
  32169. if (this._onAfterRenderObservable) {
  32170. this._onAfterRenderObservable.notifyObservers(this);
  32171. }
  32172. return this;
  32173. };
  32174. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  32175. if (isInstance && effectiveMaterial) {
  32176. effectiveMaterial.bindOnlyWorldMatrix(world);
  32177. }
  32178. };
  32179. /**
  32180. * Normalize matrix weights so that all vertices have a total weight set to 1
  32181. */
  32182. Mesh.prototype.cleanMatrixWeights = function () {
  32183. var epsilon = 1e-3;
  32184. var noInfluenceBoneIndex = 0.0;
  32185. if (this.skeleton) {
  32186. noInfluenceBoneIndex = this.skeleton.bones.length;
  32187. }
  32188. else {
  32189. return;
  32190. }
  32191. var matricesIndices = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  32192. var matricesIndicesExtra = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  32193. var matricesWeights = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  32194. var matricesWeightsExtra = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  32195. var influencers = this.numBoneInfluencers;
  32196. var size = matricesWeights.length;
  32197. for (var i = 0; i < size; i += 4) {
  32198. var weight = 0.0;
  32199. var firstZeroWeight = -1;
  32200. for (var j = 0; j < 4; j++) {
  32201. var w = matricesWeights[i + j];
  32202. weight += w;
  32203. if (w < epsilon && firstZeroWeight < 0) {
  32204. firstZeroWeight = j;
  32205. }
  32206. }
  32207. if (matricesWeightsExtra) {
  32208. for (var j = 0; j < 4; j++) {
  32209. var w = matricesWeightsExtra[i + j];
  32210. weight += w;
  32211. if (w < epsilon && firstZeroWeight < 0) {
  32212. firstZeroWeight = j + 4;
  32213. }
  32214. }
  32215. }
  32216. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  32217. firstZeroWeight = influencers - 1;
  32218. }
  32219. if (weight > epsilon) {
  32220. var mweight = 1.0 / weight;
  32221. for (var j = 0; j < 4; j++) {
  32222. matricesWeights[i + j] *= mweight;
  32223. }
  32224. if (matricesWeightsExtra) {
  32225. for (var j = 0; j < 4; j++) {
  32226. matricesWeightsExtra[i + j] *= mweight;
  32227. }
  32228. }
  32229. }
  32230. else {
  32231. if (firstZeroWeight >= 4) {
  32232. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  32233. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  32234. }
  32235. else {
  32236. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  32237. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  32238. }
  32239. }
  32240. }
  32241. this.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  32242. if (matricesIndicesExtra) {
  32243. this.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  32244. }
  32245. this.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeights);
  32246. if (matricesWeightsExtra) {
  32247. this.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, matricesWeightsExtra);
  32248. }
  32249. };
  32250. /** @hidden */
  32251. Mesh.prototype._checkDelayState = function () {
  32252. var scene = this.getScene();
  32253. if (this._geometry) {
  32254. this._geometry.load(scene);
  32255. }
  32256. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  32257. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  32258. this._queueLoad(scene);
  32259. }
  32260. return this;
  32261. };
  32262. Mesh.prototype._queueLoad = function (scene) {
  32263. var _this = this;
  32264. scene._addPendingData(this);
  32265. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  32266. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  32267. if (data instanceof ArrayBuffer) {
  32268. _this._delayLoadingFunction(data, _this);
  32269. }
  32270. else {
  32271. _this._delayLoadingFunction(JSON.parse(data), _this);
  32272. }
  32273. _this.instances.forEach(function (instance) {
  32274. instance._syncSubMeshes();
  32275. });
  32276. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  32277. scene._removePendingData(_this);
  32278. }, function () { }, scene.database, getBinaryData);
  32279. return this;
  32280. };
  32281. /**
  32282. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  32283. * A mesh is in the frustum if its bounding box intersects the frustum
  32284. * @param frustumPlanes defines the frustum to test
  32285. * @returns true if the mesh is in the frustum planes
  32286. */
  32287. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  32288. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  32289. return false;
  32290. }
  32291. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  32292. return false;
  32293. }
  32294. this._checkDelayState();
  32295. return true;
  32296. };
  32297. /**
  32298. * Sets the mesh material by the material or multiMaterial `id` property
  32299. * @param id is a string identifying the material or the multiMaterial
  32300. * @returns the current mesh
  32301. */
  32302. Mesh.prototype.setMaterialByID = function (id) {
  32303. var materials = this.getScene().materials;
  32304. var index;
  32305. for (index = materials.length - 1; index > -1; index--) {
  32306. if (materials[index].id === id) {
  32307. this.material = materials[index];
  32308. return this;
  32309. }
  32310. }
  32311. // Multi
  32312. var multiMaterials = this.getScene().multiMaterials;
  32313. for (index = multiMaterials.length - 1; index > -1; index--) {
  32314. if (multiMaterials[index].id === id) {
  32315. this.material = multiMaterials[index];
  32316. return this;
  32317. }
  32318. }
  32319. return this;
  32320. };
  32321. /**
  32322. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  32323. * @returns an array of IAnimatable
  32324. */
  32325. Mesh.prototype.getAnimatables = function () {
  32326. var results = new Array();
  32327. if (this.material) {
  32328. results.push(this.material);
  32329. }
  32330. if (this.skeleton) {
  32331. results.push(this.skeleton);
  32332. }
  32333. return results;
  32334. };
  32335. /**
  32336. * Modifies the mesh geometry according to the passed transformation matrix.
  32337. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  32338. * The mesh normals are modified using the same transformation.
  32339. * Note that, under the hood, this method sets a new VertexBuffer each call.
  32340. * @param transform defines the transform matrix to use
  32341. * @see http://doc.babylonjs.com/resources/baking_transformations
  32342. * @returns the current mesh
  32343. */
  32344. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  32345. // Position
  32346. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  32347. return this;
  32348. }
  32349. var submeshes = this.subMeshes.splice(0);
  32350. this._resetPointsArrayCache();
  32351. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32352. var temp = new Array();
  32353. var index;
  32354. for (index = 0; index < data.length; index += 3) {
  32355. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  32356. }
  32357. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  32358. // Normals
  32359. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  32360. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32361. temp = [];
  32362. for (index = 0; index < data.length; index += 3) {
  32363. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  32364. }
  32365. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  32366. }
  32367. // flip faces?
  32368. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  32369. this.flipFaces();
  32370. }
  32371. // Restore submeshes
  32372. this.releaseSubMeshes();
  32373. this.subMeshes = submeshes;
  32374. return this;
  32375. };
  32376. /**
  32377. * Modifies the mesh geometry according to its own current World Matrix.
  32378. * The mesh World Matrix is then reset.
  32379. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  32380. * Note that, under the hood, this method sets a new VertexBuffer each call.
  32381. * @see http://doc.babylonjs.com/resources/baking_transformations
  32382. * @returns the current mesh
  32383. */
  32384. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  32385. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  32386. this.scaling.copyFromFloats(1, 1, 1);
  32387. this.position.copyFromFloats(0, 0, 0);
  32388. this.rotation.copyFromFloats(0, 0, 0);
  32389. //only if quaternion is already set
  32390. if (this.rotationQuaternion) {
  32391. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  32392. }
  32393. this._worldMatrix = BABYLON.Matrix.Identity();
  32394. return this;
  32395. };
  32396. Object.defineProperty(Mesh.prototype, "_positions", {
  32397. // Cache
  32398. /** @hidden */
  32399. get: function () {
  32400. if (this._geometry) {
  32401. return this._geometry._positions;
  32402. }
  32403. return null;
  32404. },
  32405. enumerable: true,
  32406. configurable: true
  32407. });
  32408. /** @hidden */
  32409. Mesh.prototype._resetPointsArrayCache = function () {
  32410. if (this._geometry) {
  32411. this._geometry._resetPointsArrayCache();
  32412. }
  32413. return this;
  32414. };
  32415. /** @hidden */
  32416. Mesh.prototype._generatePointsArray = function () {
  32417. if (this._geometry) {
  32418. return this._geometry._generatePointsArray();
  32419. }
  32420. return false;
  32421. };
  32422. /**
  32423. * Returns a new Mesh object generated from the current mesh properties.
  32424. * This method must not get confused with createInstance()
  32425. * @param name is a string, the name given to the new mesh
  32426. * @param newParent can be any Node object (default `null`)
  32427. * @param doNotCloneChildren allows/denies the recursive cloning of the original mesh children if any (default `false`)
  32428. * @param clonePhysicsImpostor allows/denies the cloning in the same time of the original mesh `body` used by the physics engine, if any (default `true`)
  32429. * @returns a new mesh
  32430. */
  32431. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  32432. if (name === void 0) { name = ""; }
  32433. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  32434. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  32435. };
  32436. /**
  32437. * Releases resources associated with this mesh.
  32438. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  32439. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  32440. */
  32441. Mesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  32442. var _this = this;
  32443. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  32444. this.morphTargetManager = null;
  32445. if (this._geometry) {
  32446. this._geometry.releaseForMesh(this, true);
  32447. }
  32448. if (this._onBeforeDrawObservable) {
  32449. this._onBeforeDrawObservable.clear();
  32450. }
  32451. if (this._onBeforeRenderObservable) {
  32452. this._onBeforeRenderObservable.clear();
  32453. }
  32454. if (this._onAfterRenderObservable) {
  32455. this._onAfterRenderObservable.clear();
  32456. }
  32457. // Sources
  32458. var meshes = this.getScene().meshes;
  32459. meshes.forEach(function (abstractMesh) {
  32460. var mesh = abstractMesh;
  32461. if (mesh._source && mesh._source === _this) {
  32462. mesh._source = null;
  32463. }
  32464. });
  32465. this._source = null;
  32466. // Instances
  32467. if (this._instancesBuffer) {
  32468. this._instancesBuffer.dispose();
  32469. this._instancesBuffer = null;
  32470. }
  32471. while (this.instances.length) {
  32472. this.instances[0].dispose();
  32473. }
  32474. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  32475. };
  32476. /**
  32477. * Modifies the mesh geometry according to a displacement map.
  32478. * 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.
  32479. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  32480. * @param url is a string, the URL from the image file is to be downloaded.
  32481. * @param minHeight is the lower limit of the displacement.
  32482. * @param maxHeight is the upper limit of the displacement.
  32483. * @param 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.
  32484. * @param uvOffset is an optional vector2 used to offset UV.
  32485. * @param uvScale is an optional vector2 used to scale UV.
  32486. * @param forceUpdate defines whether or not to force an update of the generated buffers. This is usefull to apply on a deserialized model for instance.
  32487. * @returns the Mesh.
  32488. */
  32489. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale, forceUpdate) {
  32490. var _this = this;
  32491. if (forceUpdate === void 0) { forceUpdate = false; }
  32492. var scene = this.getScene();
  32493. var onload = function (img) {
  32494. // Getting height map data
  32495. var canvas = document.createElement("canvas");
  32496. var context = canvas.getContext("2d");
  32497. var heightMapWidth = img.width;
  32498. var heightMapHeight = img.height;
  32499. canvas.width = heightMapWidth;
  32500. canvas.height = heightMapHeight;
  32501. context.drawImage(img, 0, 0);
  32502. // Create VertexData from map data
  32503. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  32504. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  32505. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale, forceUpdate);
  32506. //execute success callback, if set
  32507. if (onSuccess) {
  32508. onSuccess(_this);
  32509. }
  32510. };
  32511. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  32512. return this;
  32513. };
  32514. /**
  32515. * Modifies the mesh geometry according to a displacementMap buffer.
  32516. * 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.
  32517. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  32518. * @param buffer is a `Uint8Array` buffer containing series of `Uint8` lower than 255, the red, green, blue and alpha values of each successive pixel.
  32519. * @param heightMapWidth is the width of the buffer image.
  32520. * @param heightMapHeight is the height of the buffer image.
  32521. * @param minHeight is the lower limit of the displacement.
  32522. * @param maxHeight is the upper limit of the displacement.
  32523. * @param 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.
  32524. * @param uvOffset is an optional vector2 used to offset UV.
  32525. * @param uvScale is an optional vector2 used to scale UV.
  32526. * @param forceUpdate defines whether or not to force an update of the generated buffers. This is usefull to apply on a deserialized model for instance.
  32527. * @returns the Mesh.
  32528. */
  32529. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale, forceUpdate) {
  32530. if (forceUpdate === void 0) { forceUpdate = false; }
  32531. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  32532. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  32533. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  32534. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  32535. return this;
  32536. }
  32537. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, true, true);
  32538. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32539. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  32540. var position = BABYLON.Vector3.Zero();
  32541. var normal = BABYLON.Vector3.Zero();
  32542. var uv = BABYLON.Vector2.Zero();
  32543. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  32544. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  32545. for (var index = 0; index < positions.length; index += 3) {
  32546. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  32547. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  32548. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  32549. // Compute height
  32550. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  32551. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  32552. var pos = (u + v * heightMapWidth) * 4;
  32553. var r = buffer[pos] / 255.0;
  32554. var g = buffer[pos + 1] / 255.0;
  32555. var b = buffer[pos + 2] / 255.0;
  32556. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  32557. normal.normalize();
  32558. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  32559. position = position.add(normal);
  32560. position.toArray(positions, index);
  32561. }
  32562. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  32563. if (forceUpdate) {
  32564. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  32565. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  32566. }
  32567. else {
  32568. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  32569. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  32570. }
  32571. return this;
  32572. };
  32573. /**
  32574. * Modify the mesh to get a flat shading rendering.
  32575. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  32576. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  32577. * @returns current mesh
  32578. */
  32579. Mesh.prototype.convertToFlatShadedMesh = function () {
  32580. var kinds = this.getVerticesDataKinds();
  32581. var vbs = {};
  32582. var data = {};
  32583. var newdata = {};
  32584. var updatableNormals = false;
  32585. var kindIndex;
  32586. var kind;
  32587. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32588. kind = kinds[kindIndex];
  32589. var vertexBuffer = this.getVertexBuffer(kind);
  32590. if (kind === BABYLON.VertexBuffer.NormalKind) {
  32591. updatableNormals = vertexBuffer.isUpdatable();
  32592. kinds.splice(kindIndex, 1);
  32593. kindIndex--;
  32594. continue;
  32595. }
  32596. vbs[kind] = vertexBuffer;
  32597. data[kind] = vbs[kind].getData();
  32598. newdata[kind] = [];
  32599. }
  32600. // Save previous submeshes
  32601. var previousSubmeshes = this.subMeshes.slice(0);
  32602. var indices = this.getIndices();
  32603. var totalIndices = this.getTotalIndices();
  32604. // Generating unique vertices per face
  32605. var index;
  32606. for (index = 0; index < totalIndices; index++) {
  32607. var vertexIndex = indices[index];
  32608. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32609. kind = kinds[kindIndex];
  32610. var stride = vbs[kind].getStrideSize();
  32611. for (var offset = 0; offset < stride; offset++) {
  32612. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  32613. }
  32614. }
  32615. }
  32616. // Updating faces & normal
  32617. var normals = [];
  32618. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  32619. for (index = 0; index < totalIndices; index += 3) {
  32620. indices[index] = index;
  32621. indices[index + 1] = index + 1;
  32622. indices[index + 2] = index + 2;
  32623. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  32624. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  32625. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  32626. var p1p2 = p1.subtract(p2);
  32627. var p3p2 = p3.subtract(p2);
  32628. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  32629. // Store same normals for every vertex
  32630. for (var localIndex = 0; localIndex < 3; localIndex++) {
  32631. normals.push(normal.x);
  32632. normals.push(normal.y);
  32633. normals.push(normal.z);
  32634. }
  32635. }
  32636. this.setIndices(indices);
  32637. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  32638. // Updating vertex buffers
  32639. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32640. kind = kinds[kindIndex];
  32641. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  32642. }
  32643. // Updating submeshes
  32644. this.releaseSubMeshes();
  32645. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  32646. var previousOne = previousSubmeshes[submeshIndex];
  32647. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  32648. }
  32649. this.synchronizeInstances();
  32650. return this;
  32651. };
  32652. /**
  32653. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  32654. * In other words, more vertices, no more indices and a single bigger VBO.
  32655. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  32656. * @returns current mesh
  32657. */
  32658. Mesh.prototype.convertToUnIndexedMesh = function () {
  32659. var kinds = this.getVerticesDataKinds();
  32660. var vbs = {};
  32661. var data = {};
  32662. var newdata = {};
  32663. var kindIndex;
  32664. var kind;
  32665. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32666. kind = kinds[kindIndex];
  32667. var vertexBuffer = this.getVertexBuffer(kind);
  32668. vbs[kind] = vertexBuffer;
  32669. data[kind] = vbs[kind].getData();
  32670. newdata[kind] = [];
  32671. }
  32672. // Save previous submeshes
  32673. var previousSubmeshes = this.subMeshes.slice(0);
  32674. var indices = this.getIndices();
  32675. var totalIndices = this.getTotalIndices();
  32676. // Generating unique vertices per face
  32677. var index;
  32678. for (index = 0; index < totalIndices; index++) {
  32679. var vertexIndex = indices[index];
  32680. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32681. kind = kinds[kindIndex];
  32682. var stride = vbs[kind].getStrideSize();
  32683. for (var offset = 0; offset < stride; offset++) {
  32684. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  32685. }
  32686. }
  32687. }
  32688. // Updating indices
  32689. for (index = 0; index < totalIndices; index += 3) {
  32690. indices[index] = index;
  32691. indices[index + 1] = index + 1;
  32692. indices[index + 2] = index + 2;
  32693. }
  32694. this.setIndices(indices);
  32695. // Updating vertex buffers
  32696. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32697. kind = kinds[kindIndex];
  32698. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  32699. }
  32700. // Updating submeshes
  32701. this.releaseSubMeshes();
  32702. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  32703. var previousOne = previousSubmeshes[submeshIndex];
  32704. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  32705. }
  32706. this._unIndexed = true;
  32707. this.synchronizeInstances();
  32708. return this;
  32709. };
  32710. /**
  32711. * Inverses facet orientations.
  32712. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  32713. * @param flipNormals will also inverts the normals
  32714. * @returns current mesh
  32715. */
  32716. Mesh.prototype.flipFaces = function (flipNormals) {
  32717. if (flipNormals === void 0) { flipNormals = false; }
  32718. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  32719. var i;
  32720. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) && vertex_data.normals) {
  32721. for (i = 0; i < vertex_data.normals.length; i++) {
  32722. vertex_data.normals[i] *= -1;
  32723. }
  32724. }
  32725. if (vertex_data.indices) {
  32726. var temp;
  32727. for (i = 0; i < vertex_data.indices.length; i += 3) {
  32728. // reassign indices
  32729. temp = vertex_data.indices[i + 1];
  32730. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  32731. vertex_data.indices[i + 2] = temp;
  32732. }
  32733. }
  32734. vertex_data.applyToMesh(this);
  32735. return this;
  32736. };
  32737. // Instances
  32738. /**
  32739. * Creates a new InstancedMesh object from the mesh model.
  32740. * Warning : this method is not supported for Line mesh and LineSystem
  32741. * @see http://doc.babylonjs.com/how_to/how_to_use_instances
  32742. * @param name defines the name of the new instance
  32743. * @returns a new InstancedMesh
  32744. */
  32745. Mesh.prototype.createInstance = function (name) {
  32746. return new BABYLON.InstancedMesh(name, this);
  32747. };
  32748. /**
  32749. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  32750. * After this call, all the mesh instances have the same submeshes than the current mesh.
  32751. * @returns the current mesh
  32752. */
  32753. Mesh.prototype.synchronizeInstances = function () {
  32754. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  32755. var instance = this.instances[instanceIndex];
  32756. instance._syncSubMeshes();
  32757. }
  32758. return this;
  32759. };
  32760. /**
  32761. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  32762. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  32763. * This should be used together with the simplification to avoid disappearing triangles.
  32764. * @param successCallback an optional success callback to be called after the optimization finished.
  32765. * @returns the current mesh
  32766. */
  32767. Mesh.prototype.optimizeIndices = function (successCallback) {
  32768. var _this = this;
  32769. var indices = this.getIndices();
  32770. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32771. if (!positions || !indices) {
  32772. return this;
  32773. }
  32774. var vectorPositions = new Array();
  32775. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  32776. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  32777. }
  32778. var dupes = new Array();
  32779. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  32780. var realPos = vectorPositions.length - 1 - iteration;
  32781. var testedPosition = vectorPositions[realPos];
  32782. for (var j = 0; j < realPos; ++j) {
  32783. var againstPosition = vectorPositions[j];
  32784. if (testedPosition.equals(againstPosition)) {
  32785. dupes[realPos] = j;
  32786. break;
  32787. }
  32788. }
  32789. }, function () {
  32790. for (var i = 0; i < indices.length; ++i) {
  32791. indices[i] = dupes[indices[i]] || indices[i];
  32792. }
  32793. //indices are now reordered
  32794. var originalSubMeshes = _this.subMeshes.slice(0);
  32795. _this.setIndices(indices);
  32796. _this.subMeshes = originalSubMeshes;
  32797. if (successCallback) {
  32798. successCallback(_this);
  32799. }
  32800. });
  32801. return this;
  32802. };
  32803. /**
  32804. * Serialize current mesh
  32805. * @param serializationObject defines the object which will receive the serialization data
  32806. */
  32807. Mesh.prototype.serialize = function (serializationObject) {
  32808. serializationObject.name = this.name;
  32809. serializationObject.id = this.id;
  32810. serializationObject.type = this.getClassName();
  32811. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  32812. serializationObject.tags = BABYLON.Tags.GetTags(this);
  32813. }
  32814. serializationObject.position = this.position.asArray();
  32815. if (this.rotationQuaternion) {
  32816. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  32817. }
  32818. else if (this.rotation) {
  32819. serializationObject.rotation = this.rotation.asArray();
  32820. }
  32821. serializationObject.scaling = this.scaling.asArray();
  32822. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  32823. serializationObject.isEnabled = this.isEnabled(false);
  32824. serializationObject.isVisible = this.isVisible;
  32825. serializationObject.infiniteDistance = this.infiniteDistance;
  32826. serializationObject.pickable = this.isPickable;
  32827. serializationObject.receiveShadows = this.receiveShadows;
  32828. serializationObject.billboardMode = this.billboardMode;
  32829. serializationObject.visibility = this.visibility;
  32830. serializationObject.checkCollisions = this.checkCollisions;
  32831. serializationObject.isBlocker = this.isBlocker;
  32832. // Parent
  32833. if (this.parent) {
  32834. serializationObject.parentId = this.parent.id;
  32835. }
  32836. // Geometry
  32837. serializationObject.isUnIndexed = this.isUnIndexed;
  32838. var geometry = this._geometry;
  32839. if (geometry) {
  32840. var geometryId = geometry.id;
  32841. serializationObject.geometryId = geometryId;
  32842. // SubMeshes
  32843. serializationObject.subMeshes = [];
  32844. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  32845. var subMesh = this.subMeshes[subIndex];
  32846. serializationObject.subMeshes.push({
  32847. materialIndex: subMesh.materialIndex,
  32848. verticesStart: subMesh.verticesStart,
  32849. verticesCount: subMesh.verticesCount,
  32850. indexStart: subMesh.indexStart,
  32851. indexCount: subMesh.indexCount
  32852. });
  32853. }
  32854. }
  32855. // Material
  32856. if (this.material) {
  32857. serializationObject.materialId = this.material.id;
  32858. }
  32859. else {
  32860. this.material = null;
  32861. }
  32862. // Morph targets
  32863. if (this.morphTargetManager) {
  32864. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  32865. }
  32866. // Skeleton
  32867. if (this.skeleton) {
  32868. serializationObject.skeletonId = this.skeleton.id;
  32869. }
  32870. // Physics
  32871. //TODO implement correct serialization for physics impostors.
  32872. var impostor = this.getPhysicsImpostor();
  32873. if (impostor) {
  32874. serializationObject.physicsMass = impostor.getParam("mass");
  32875. serializationObject.physicsFriction = impostor.getParam("friction");
  32876. serializationObject.physicsRestitution = impostor.getParam("mass");
  32877. serializationObject.physicsImpostor = impostor.type;
  32878. }
  32879. // Metadata
  32880. if (this.metadata) {
  32881. serializationObject.metadata = this.metadata;
  32882. }
  32883. // Instances
  32884. serializationObject.instances = [];
  32885. for (var index = 0; index < this.instances.length; index++) {
  32886. var instance = this.instances[index];
  32887. if (instance.doNotSerialize) {
  32888. continue;
  32889. }
  32890. var serializationInstance = {
  32891. name: instance.name,
  32892. id: instance.id,
  32893. position: instance.position.asArray(),
  32894. scaling: instance.scaling.asArray()
  32895. };
  32896. if (instance.parent) {
  32897. serializationInstance.parentId = instance.parent.id;
  32898. }
  32899. if (instance.rotationQuaternion) {
  32900. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  32901. }
  32902. else if (instance.rotation) {
  32903. serializationInstance.rotation = instance.rotation.asArray();
  32904. }
  32905. serializationObject.instances.push(serializationInstance);
  32906. // Animations
  32907. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  32908. serializationInstance.ranges = instance.serializeAnimationRanges();
  32909. }
  32910. //
  32911. // Animations
  32912. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  32913. serializationObject.ranges = this.serializeAnimationRanges();
  32914. // Layer mask
  32915. serializationObject.layerMask = this.layerMask;
  32916. // Alpha
  32917. serializationObject.alphaIndex = this.alphaIndex;
  32918. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  32919. // Overlay
  32920. serializationObject.overlayAlpha = this.overlayAlpha;
  32921. serializationObject.overlayColor = this.overlayColor.asArray();
  32922. serializationObject.renderOverlay = this.renderOverlay;
  32923. // Fog
  32924. serializationObject.applyFog = this.applyFog;
  32925. // Action Manager
  32926. if (this.actionManager) {
  32927. serializationObject.actions = this.actionManager.serialize(this.name);
  32928. }
  32929. };
  32930. /** @hidden */
  32931. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  32932. if (!this.geometry) {
  32933. return;
  32934. }
  32935. this._markSubMeshesAsAttributesDirty();
  32936. var morphTargetManager = this._morphTargetManager;
  32937. if (morphTargetManager && morphTargetManager.vertexCount) {
  32938. if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
  32939. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  32940. this.morphTargetManager = null;
  32941. return;
  32942. }
  32943. for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
  32944. var morphTarget = morphTargetManager.getActiveTarget(index);
  32945. var positions = morphTarget.getPositions();
  32946. if (!positions) {
  32947. BABYLON.Tools.Error("Invalid morph target. Target must have positions.");
  32948. return;
  32949. }
  32950. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, positions, false, 3);
  32951. var normals = morphTarget.getNormals();
  32952. if (normals) {
  32953. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, normals, false, 3);
  32954. }
  32955. var tangents = morphTarget.getTangents();
  32956. if (tangents) {
  32957. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, tangents, false, 3);
  32958. }
  32959. }
  32960. }
  32961. else {
  32962. var index = 0;
  32963. // Positions
  32964. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  32965. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  32966. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  32967. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  32968. }
  32969. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  32970. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  32971. }
  32972. index++;
  32973. }
  32974. }
  32975. };
  32976. // Statics
  32977. /**
  32978. * Returns a new Mesh object parsed from the source provided.
  32979. * @param parsedMesh is the source
  32980. * @param scene defines the hosting scene
  32981. * @param rootUrl is the root URL to prefix the `delayLoadingFile` property with
  32982. * @returns a new Mesh
  32983. */
  32984. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  32985. var mesh;
  32986. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  32987. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  32988. }
  32989. else {
  32990. mesh = new Mesh(parsedMesh.name, scene);
  32991. }
  32992. mesh.id = parsedMesh.id;
  32993. if (BABYLON.Tags) {
  32994. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  32995. }
  32996. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  32997. if (parsedMesh.metadata !== undefined) {
  32998. mesh.metadata = parsedMesh.metadata;
  32999. }
  33000. if (parsedMesh.rotationQuaternion) {
  33001. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  33002. }
  33003. else if (parsedMesh.rotation) {
  33004. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  33005. }
  33006. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  33007. if (parsedMesh.localMatrix) {
  33008. mesh.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  33009. }
  33010. else if (parsedMesh.pivotMatrix) {
  33011. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  33012. }
  33013. mesh.setEnabled(parsedMesh.isEnabled);
  33014. mesh.isVisible = parsedMesh.isVisible;
  33015. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  33016. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  33017. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  33018. if (parsedMesh.applyFog !== undefined) {
  33019. mesh.applyFog = parsedMesh.applyFog;
  33020. }
  33021. if (parsedMesh.pickable !== undefined) {
  33022. mesh.isPickable = parsedMesh.pickable;
  33023. }
  33024. if (parsedMesh.alphaIndex !== undefined) {
  33025. mesh.alphaIndex = parsedMesh.alphaIndex;
  33026. }
  33027. mesh.receiveShadows = parsedMesh.receiveShadows;
  33028. mesh.billboardMode = parsedMesh.billboardMode;
  33029. if (parsedMesh.visibility !== undefined) {
  33030. mesh.visibility = parsedMesh.visibility;
  33031. }
  33032. mesh.checkCollisions = parsedMesh.checkCollisions;
  33033. if (parsedMesh.isBlocker !== undefined) {
  33034. mesh.isBlocker = parsedMesh.isBlocker;
  33035. }
  33036. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  33037. // freezeWorldMatrix
  33038. if (parsedMesh.freezeWorldMatrix) {
  33039. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  33040. }
  33041. // Parent
  33042. if (parsedMesh.parentId) {
  33043. mesh._waitingParentId = parsedMesh.parentId;
  33044. }
  33045. // Actions
  33046. if (parsedMesh.actions !== undefined) {
  33047. mesh._waitingActions = parsedMesh.actions;
  33048. }
  33049. // Overlay
  33050. if (parsedMesh.overlayAlpha !== undefined) {
  33051. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  33052. }
  33053. if (parsedMesh.overlayColor !== undefined) {
  33054. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  33055. }
  33056. if (parsedMesh.renderOverlay !== undefined) {
  33057. mesh.renderOverlay = parsedMesh.renderOverlay;
  33058. }
  33059. // Geometry
  33060. mesh.isUnIndexed = !!parsedMesh.isUnIndexed;
  33061. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  33062. if (parsedMesh.delayLoadingFile) {
  33063. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  33064. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  33065. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  33066. if (parsedMesh._binaryInfo) {
  33067. mesh._binaryInfo = parsedMesh._binaryInfo;
  33068. }
  33069. mesh._delayInfo = [];
  33070. if (parsedMesh.hasUVs) {
  33071. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  33072. }
  33073. if (parsedMesh.hasUVs2) {
  33074. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  33075. }
  33076. if (parsedMesh.hasUVs3) {
  33077. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  33078. }
  33079. if (parsedMesh.hasUVs4) {
  33080. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  33081. }
  33082. if (parsedMesh.hasUVs5) {
  33083. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  33084. }
  33085. if (parsedMesh.hasUVs6) {
  33086. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  33087. }
  33088. if (parsedMesh.hasColors) {
  33089. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  33090. }
  33091. if (parsedMesh.hasMatricesIndices) {
  33092. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  33093. }
  33094. if (parsedMesh.hasMatricesWeights) {
  33095. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  33096. }
  33097. mesh._delayLoadingFunction = BABYLON.Geometry._ImportGeometry;
  33098. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  33099. mesh._checkDelayState();
  33100. }
  33101. }
  33102. else {
  33103. BABYLON.Geometry._ImportGeometry(parsedMesh, mesh);
  33104. }
  33105. // Material
  33106. if (parsedMesh.materialId) {
  33107. mesh.setMaterialByID(parsedMesh.materialId);
  33108. }
  33109. else {
  33110. mesh.material = null;
  33111. }
  33112. // Morph targets
  33113. if (parsedMesh.morphTargetManagerId > -1) {
  33114. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  33115. }
  33116. // Skeleton
  33117. if (parsedMesh.skeletonId > -1) {
  33118. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  33119. if (parsedMesh.numBoneInfluencers) {
  33120. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  33121. }
  33122. }
  33123. // Animations
  33124. if (parsedMesh.animations) {
  33125. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  33126. var parsedAnimation = parsedMesh.animations[animationIndex];
  33127. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  33128. }
  33129. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  33130. }
  33131. if (parsedMesh.autoAnimate) {
  33132. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  33133. }
  33134. // Layer Mask
  33135. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  33136. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  33137. }
  33138. else {
  33139. mesh.layerMask = 0x0FFFFFFF;
  33140. }
  33141. // Physics
  33142. if (parsedMesh.physicsImpostor) {
  33143. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  33144. mass: parsedMesh.physicsMass,
  33145. friction: parsedMesh.physicsFriction,
  33146. restitution: parsedMesh.physicsRestitution
  33147. }, scene);
  33148. }
  33149. // Instances
  33150. if (parsedMesh.instances) {
  33151. for (var index = 0; index < parsedMesh.instances.length; index++) {
  33152. var parsedInstance = parsedMesh.instances[index];
  33153. var instance = mesh.createInstance(parsedInstance.name);
  33154. if (parsedInstance.id) {
  33155. instance.id = parsedInstance.id;
  33156. }
  33157. if (BABYLON.Tags) {
  33158. if (parsedInstance.tags) {
  33159. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  33160. }
  33161. else {
  33162. BABYLON.Tags.AddTagsTo(instance, parsedMesh.tags);
  33163. }
  33164. }
  33165. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  33166. if (parsedInstance.parentId) {
  33167. instance._waitingParentId = parsedInstance.parentId;
  33168. }
  33169. if (parsedInstance.rotationQuaternion) {
  33170. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  33171. }
  33172. else if (parsedInstance.rotation) {
  33173. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  33174. }
  33175. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  33176. if (parsedInstance.checkCollisions != undefined && parsedInstance.checkCollisions != null) {
  33177. instance.checkCollisions = parsedInstance.checkCollisions;
  33178. }
  33179. if (parsedInstance.pickable != undefined && parsedInstance.pickable != null) {
  33180. instance.isPickable = parsedInstance.pickable;
  33181. }
  33182. if (parsedInstance.showBoundingBox != undefined && parsedInstance.showBoundingBox != null) {
  33183. instance.showBoundingBox = parsedInstance.showBoundingBox;
  33184. }
  33185. if (parsedInstance.showSubMeshesBoundingBox != undefined && parsedInstance.showSubMeshesBoundingBox != null) {
  33186. instance.showSubMeshesBoundingBox = parsedInstance.showSubMeshesBoundingBox;
  33187. }
  33188. if (parsedInstance.alphaIndex != undefined && parsedInstance.showSubMeshesBoundingBox != null) {
  33189. instance.alphaIndex = parsedInstance.alphaIndex;
  33190. }
  33191. // Physics
  33192. if (parsedInstance.physicsImpostor) {
  33193. instance.physicsImpostor = new BABYLON.PhysicsImpostor(instance, parsedInstance.physicsImpostor, {
  33194. mass: parsedInstance.physicsMass,
  33195. friction: parsedInstance.physicsFriction,
  33196. restitution: parsedInstance.physicsRestitution
  33197. }, scene);
  33198. }
  33199. // Animation
  33200. if (parsedInstance.animations) {
  33201. for (animationIndex = 0; animationIndex < parsedInstance.animations.length; animationIndex++) {
  33202. parsedAnimation = parsedInstance.animations[animationIndex];
  33203. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  33204. }
  33205. BABYLON.Node.ParseAnimationRanges(instance, parsedInstance, scene);
  33206. if (parsedInstance.autoAnimate) {
  33207. scene.beginAnimation(instance, parsedInstance.autoAnimateFrom, parsedInstance.autoAnimateTo, parsedInstance.autoAnimateLoop, parsedInstance.autoAnimateSpeed || 1.0);
  33208. }
  33209. }
  33210. }
  33211. }
  33212. return mesh;
  33213. };
  33214. /**
  33215. * Creates a ribbon mesh. Please consider using the same method from the MeshBuilder class instead
  33216. * @see http://doc.babylonjs.com/how_to/parametric_shapes
  33217. * @param name defines the name of the mesh to create
  33218. * @param pathArray is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  33219. * @param closeArray creates a seam between the first and the last paths of the path array (default is false)
  33220. * @param closePath creates a seam between the first and the last points of each path of the path array
  33221. * @param offset is taken in account only if the `pathArray` is containing a single path
  33222. * @param scene defines the hosting scene
  33223. * @param updatable defines if the mesh must be flagged as updatable
  33224. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  33225. * @param instance defines an instance of an existing Ribbon object to be updated with the passed `pathArray` parameter (http://doc.babylonjs.com/how_to/How_to_dynamically_morph_a_mesh#ribbon)
  33226. * @returns a new Mesh
  33227. */
  33228. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  33229. if (closeArray === void 0) { closeArray = false; }
  33230. if (updatable === void 0) { updatable = false; }
  33231. return BABYLON.MeshBuilder.CreateRibbon(name, {
  33232. pathArray: pathArray,
  33233. closeArray: closeArray,
  33234. closePath: closePath,
  33235. offset: offset,
  33236. updatable: updatable,
  33237. sideOrientation: sideOrientation,
  33238. instance: instance
  33239. }, scene);
  33240. };
  33241. /**
  33242. * Creates a plane polygonal mesh. By default, this is a disc. Please consider using the same method from the MeshBuilder class instead
  33243. * @param name defines the name of the mesh to create
  33244. * @param radius sets the radius size (float) of the polygon (default 0.5)
  33245. * @param 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
  33246. * @param scene defines the hosting scene
  33247. * @param updatable defines if the mesh must be flagged as updatable
  33248. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  33249. * @returns a new Mesh
  33250. */
  33251. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  33252. if (scene === void 0) { scene = null; }
  33253. var options = {
  33254. radius: radius,
  33255. tessellation: tessellation,
  33256. sideOrientation: sideOrientation,
  33257. updatable: updatable
  33258. };
  33259. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  33260. };
  33261. /**
  33262. * Creates a box mesh. Please consider using the same method from the MeshBuilder class instead
  33263. * @param name defines the name of the mesh to create
  33264. * @param size sets the size (float) of each box side (default 1)
  33265. * @param scene defines the hosting scene
  33266. * @param updatable defines if the mesh must be flagged as updatable
  33267. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  33268. * @returns a new Mesh
  33269. */
  33270. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  33271. if (scene === void 0) { scene = null; }
  33272. var options = {
  33273. size: size,
  33274. sideOrientation: sideOrientation,
  33275. updatable: updatable
  33276. };
  33277. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  33278. };
  33279. /**
  33280. * Creates a sphere mesh. Please consider using the same method from the MeshBuilder class instead
  33281. * @param name defines the name of the mesh to create
  33282. * @param segments sets the sphere number of horizontal stripes (positive integer, default 32)
  33283. * @param diameter sets the diameter size (float) of the sphere (default 1)
  33284. * @param scene defines the hosting scene
  33285. * @param updatable defines if the mesh must be flagged as updatable
  33286. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  33287. * @returns a new Mesh
  33288. */
  33289. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  33290. var options = {
  33291. segments: segments,
  33292. diameterX: diameter,
  33293. diameterY: diameter,
  33294. diameterZ: diameter,
  33295. sideOrientation: sideOrientation,
  33296. updatable: updatable
  33297. };
  33298. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  33299. };
  33300. /**
  33301. * Creates a cylinder or a cone mesh. Please consider using the same method from the MeshBuilder class instead
  33302. * @param name defines the name of the mesh to create
  33303. * @param height sets the height size (float) of the cylinder/cone (float, default 2)
  33304. * @param diameterTop set the top cap diameter (floats, default 1)
  33305. * @param diameterBottom set the bottom cap diameter (floats, default 1). This value can't be zero
  33306. * @param tessellation sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance
  33307. * @param subdivisions sets the number of rings along the cylinder height (positive integer, default 1)
  33308. * @param scene defines the hosting scene
  33309. * @param updatable defines if the mesh must be flagged as updatable
  33310. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  33311. * @returns a new Mesh
  33312. */
  33313. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  33314. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  33315. if (scene !== undefined) {
  33316. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  33317. updatable = scene;
  33318. }
  33319. scene = subdivisions;
  33320. subdivisions = 1;
  33321. }
  33322. var options = {
  33323. height: height,
  33324. diameterTop: diameterTop,
  33325. diameterBottom: diameterBottom,
  33326. tessellation: tessellation,
  33327. subdivisions: subdivisions,
  33328. sideOrientation: sideOrientation,
  33329. updatable: updatable
  33330. };
  33331. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  33332. };
  33333. // Torus (Code from SharpDX.org)
  33334. /**
  33335. * Creates a torus mesh. Please consider using the same method from the MeshBuilder class instead
  33336. * @param name defines the name of the mesh to create
  33337. * @param diameter sets the diameter size (float) of the torus (default 1)
  33338. * @param thickness sets the diameter size of the tube of the torus (float, default 0.5)
  33339. * @param tessellation sets the number of torus sides (postive integer, default 16)
  33340. * @param scene defines the hosting scene
  33341. * @param updatable defines if the mesh must be flagged as updatable
  33342. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  33343. * @returns a new Mesh
  33344. */
  33345. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  33346. var options = {
  33347. diameter: diameter,
  33348. thickness: thickness,
  33349. tessellation: tessellation,
  33350. sideOrientation: sideOrientation,
  33351. updatable: updatable
  33352. };
  33353. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  33354. };
  33355. /**
  33356. * Creates a torus knot mesh. Please consider using the same method from the MeshBuilder class instead
  33357. * @param name defines the name of the mesh to create
  33358. * @param radius sets the global radius size (float) of the torus knot (default 2)
  33359. * @param tube sets the diameter size of the tube of the torus (float, default 0.5)
  33360. * @param radialSegments sets the number of sides on each tube segments (positive integer, default 32)
  33361. * @param tubularSegments sets the number of tubes to decompose the knot into (positive integer, default 32)
  33362. * @param p the number of windings on X axis (positive integers, default 2)
  33363. * @param q the number of windings on Y axis (positive integers, default 3)
  33364. * @param scene defines the hosting scene
  33365. * @param updatable defines if the mesh must be flagged as updatable
  33366. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  33367. * @returns a new Mesh
  33368. */
  33369. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  33370. var options = {
  33371. radius: radius,
  33372. tube: tube,
  33373. radialSegments: radialSegments,
  33374. tubularSegments: tubularSegments,
  33375. p: p,
  33376. q: q,
  33377. sideOrientation: sideOrientation,
  33378. updatable: updatable
  33379. };
  33380. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  33381. };
  33382. /**
  33383. * Creates a line mesh. Please consider using the same method from the MeshBuilder class instead.
  33384. * @param name defines the name of the mesh to create
  33385. * @param points is an array successive Vector3
  33386. * @param scene defines the hosting scene
  33387. * @param updatable defines if the mesh must be flagged as updatable
  33388. * @param instance is an instance of an existing LineMesh object to be updated with the passed `points` parameter (http://doc.babylonjs.com/how_to/How_to_dynamically_morph_a_mesh#lines-and-dashedlines).
  33389. * @returns a new Mesh
  33390. */
  33391. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  33392. if (scene === void 0) { scene = null; }
  33393. if (updatable === void 0) { updatable = false; }
  33394. if (instance === void 0) { instance = null; }
  33395. var options = {
  33396. points: points,
  33397. updatable: updatable,
  33398. instance: instance
  33399. };
  33400. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  33401. };
  33402. /**
  33403. * Creates a dashed line mesh. Please consider using the same method from the MeshBuilder class instead
  33404. * @param name defines the name of the mesh to create
  33405. * @param points is an array successive Vector3
  33406. * @param dashSize is the size of the dashes relatively the dash number (positive float, default 3)
  33407. * @param gapSize is the size of the gap between two successive dashes relatively the dash number (positive float, default 1)
  33408. * @param dashNb is the intended total number of dashes (positive integer, default 200)
  33409. * @param scene defines the hosting scene
  33410. * @param updatable defines if the mesh must be flagged as updatable
  33411. * @param instance is an instance of an existing LineMesh object to be updated with the passed `points` parameter (http://doc.babylonjs.com/how_to/How_to_dynamically_morph_a_mesh#lines-and-dashedlines)
  33412. * @returns a new Mesh
  33413. */
  33414. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  33415. if (scene === void 0) { scene = null; }
  33416. var options = {
  33417. points: points,
  33418. dashSize: dashSize,
  33419. gapSize: gapSize,
  33420. dashNb: dashNb,
  33421. updatable: updatable,
  33422. instance: instance
  33423. };
  33424. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  33425. };
  33426. /**
  33427. * Creates a polygon mesh.
  33428. * Please consider using the same method from the MeshBuilder class instead.
  33429. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  33430. * 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.
  33431. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33432. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33433. * Remember you can only change the shape positions, not their number when updating a polygon.
  33434. */
  33435. /**
  33436. * Creates a polygon mesh.Please consider using the same method from the MeshBuilder class instead
  33437. * @see http://doc.babylonjs.com/how_to/parametric_shapes#non-regular-polygon
  33438. * @param name defines the name of the mesh to create
  33439. * @param 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
  33440. * @param scene defines the hosting scene
  33441. * @param holes is a required array of arrays of successive Vector3 used to defines holes in the polygon
  33442. * @param updatable defines if the mesh must be flagged as updatable
  33443. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  33444. * @returns a new Mesh
  33445. */
  33446. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  33447. var options = {
  33448. shape: shape,
  33449. holes: holes,
  33450. updatable: updatable,
  33451. sideOrientation: sideOrientation
  33452. };
  33453. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  33454. };
  33455. /**
  33456. * Creates an extruded polygon mesh, with depth in the Y direction. Please consider using the same method from the MeshBuilder class instead.
  33457. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-non-regular-polygon
  33458. * @param name defines the name of the mesh to create
  33459. * @param 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
  33460. * @param depth defines the height of extrusion
  33461. * @param scene defines the hosting scene
  33462. * @param holes is a required array of arrays of successive Vector3 used to defines holes in the polygon
  33463. * @param updatable defines if the mesh must be flagged as updatable
  33464. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  33465. * @returns a new Mesh
  33466. */
  33467. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  33468. var options = {
  33469. shape: shape,
  33470. holes: holes,
  33471. depth: depth,
  33472. updatable: updatable,
  33473. sideOrientation: sideOrientation
  33474. };
  33475. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  33476. };
  33477. /**
  33478. * Creates an extruded shape mesh.
  33479. * The extrusion is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters. Please consider using the same method from the MeshBuilder class instead
  33480. * @see http://doc.babylonjs.com/how_to/parametric_shapes
  33481. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  33482. * @param name defines the name of the mesh to create
  33483. * @param 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
  33484. * @param path is a required array of successive Vector3. This is the axis curve the shape is extruded along
  33485. * @param scale is the value to scale the shape
  33486. * @param rotation 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
  33487. * @param 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
  33488. * @param scene defines the hosting scene
  33489. * @param updatable defines if the mesh must be flagged as updatable
  33490. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  33491. * @param 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/how_to/How_to_dynamically_morph_a_mesh#extruded-shape)
  33492. * @returns a new Mesh
  33493. */
  33494. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  33495. if (scene === void 0) { scene = null; }
  33496. var options = {
  33497. shape: shape,
  33498. path: path,
  33499. scale: scale,
  33500. rotation: rotation,
  33501. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  33502. sideOrientation: sideOrientation,
  33503. instance: instance,
  33504. updatable: updatable
  33505. };
  33506. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  33507. };
  33508. /**
  33509. * Creates an custom extruded shape mesh.
  33510. * The custom extrusion is a parametric shape.
  33511. * It has no predefined shape. Its final shape will depend on the input parameters.
  33512. * Please consider using the same method from the MeshBuilder class instead
  33513. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  33514. * @param name defines the name of the mesh to create
  33515. * @param 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
  33516. * @param path is a required array of successive Vector3. This is the axis curve the shape is extruded along
  33517. * @param scaleFunction is a custom Javascript function called on each path point
  33518. * @param rotationFunction is a custom Javascript function called on each path point
  33519. * @param ribbonCloseArray forces the extrusion underlying ribbon to close all the paths in its `pathArray`
  33520. * @param ribbonClosePath forces the extrusion underlying ribbon to close its `pathArray`
  33521. * @param 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
  33522. * @param scene defines the hosting scene
  33523. * @param updatable defines if the mesh must be flagged as updatable
  33524. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  33525. * @param 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/how_to/how_to_dynamically_morph_a_mesh#extruded-shape)
  33526. * @returns a new Mesh
  33527. */
  33528. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  33529. var options = {
  33530. shape: shape,
  33531. path: path,
  33532. scaleFunction: scaleFunction,
  33533. rotationFunction: rotationFunction,
  33534. ribbonCloseArray: ribbonCloseArray,
  33535. ribbonClosePath: ribbonClosePath,
  33536. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  33537. sideOrientation: sideOrientation,
  33538. instance: instance,
  33539. updatable: updatable
  33540. };
  33541. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  33542. };
  33543. /**
  33544. * Creates lathe mesh.
  33545. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  33546. * Please consider using the same method from the MeshBuilder class instead
  33547. * @param name defines the name of the mesh to create
  33548. * @param 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
  33549. * @param radius is the radius value of the lathe
  33550. * @param tessellation is the side number of the lathe.
  33551. * @param scene defines the hosting scene
  33552. * @param updatable defines if the mesh must be flagged as updatable
  33553. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  33554. * @returns a new Mesh
  33555. */
  33556. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  33557. var options = {
  33558. shape: shape,
  33559. radius: radius,
  33560. tessellation: tessellation,
  33561. sideOrientation: sideOrientation,
  33562. updatable: updatable
  33563. };
  33564. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  33565. };
  33566. /**
  33567. * Creates a plane mesh. Please consider using the same method from the MeshBuilder class instead
  33568. * @param name defines the name of the mesh to create
  33569. * @param size sets the size (float) of both sides of the plane at once (default 1)
  33570. * @param scene defines the hosting scene
  33571. * @param updatable defines if the mesh must be flagged as updatable
  33572. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  33573. * @returns a new Mesh
  33574. */
  33575. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  33576. var options = {
  33577. size: size,
  33578. width: size,
  33579. height: size,
  33580. sideOrientation: sideOrientation,
  33581. updatable: updatable
  33582. };
  33583. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  33584. };
  33585. /**
  33586. * Creates a ground mesh.
  33587. * Please consider using the same method from the MeshBuilder class instead
  33588. * @param name defines the name of the mesh to create
  33589. * @param width set the width of the ground
  33590. * @param height set the height of the ground
  33591. * @param subdivisions sets the number of subdivisions per side
  33592. * @param scene defines the hosting scene
  33593. * @param updatable defines if the mesh must be flagged as updatable
  33594. * @returns a new Mesh
  33595. */
  33596. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  33597. var options = {
  33598. width: width,
  33599. height: height,
  33600. subdivisions: subdivisions,
  33601. updatable: updatable
  33602. };
  33603. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  33604. };
  33605. /**
  33606. * Creates a tiled ground mesh.
  33607. * Please consider using the same method from the MeshBuilder class instead
  33608. * @param name defines the name of the mesh to create
  33609. * @param xmin set the ground minimum X coordinate
  33610. * @param zmin set the ground minimum Y coordinate
  33611. * @param xmax set the ground maximum X coordinate
  33612. * @param zmax set the ground maximum Z coordinate
  33613. * @param subdivisions is an 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
  33614. * @param precision is an 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
  33615. * @param scene defines the hosting scene
  33616. * @param updatable defines if the mesh must be flagged as updatable
  33617. * @returns a new Mesh
  33618. */
  33619. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  33620. var options = {
  33621. xmin: xmin,
  33622. zmin: zmin,
  33623. xmax: xmax,
  33624. zmax: zmax,
  33625. subdivisions: subdivisions,
  33626. precision: precision,
  33627. updatable: updatable
  33628. };
  33629. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  33630. };
  33631. /**
  33632. * Creates a ground mesh from a height map.
  33633. * Please consider using the same method from the MeshBuilder class instead
  33634. * @see http://doc.babylonjs.com/babylon101/height_map
  33635. * @param name defines the name of the mesh to create
  33636. * @param url sets the URL of the height map image resource
  33637. * @param width set the ground width size
  33638. * @param height set the ground height size
  33639. * @param subdivisions sets the number of subdivision per side
  33640. * @param minHeight is the minimum altitude on the ground
  33641. * @param maxHeight is the maximum altitude on the ground
  33642. * @param scene defines the hosting scene
  33643. * @param updatable defines if the mesh must be flagged as updatable
  33644. * @param onReady is a callback function that will be called once the mesh is built (the height map download can last some time)
  33645. * @param alphaFilter will filter any data where the alpha channel is below this value, defaults 0 (all data visible)
  33646. * @returns a new Mesh
  33647. */
  33648. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady, alphaFilter) {
  33649. var options = {
  33650. width: width,
  33651. height: height,
  33652. subdivisions: subdivisions,
  33653. minHeight: minHeight,
  33654. maxHeight: maxHeight,
  33655. updatable: updatable,
  33656. onReady: onReady,
  33657. alphaFilter: alphaFilter
  33658. };
  33659. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  33660. };
  33661. /**
  33662. * Creates a tube mesh.
  33663. * The tube is a parametric shape.
  33664. * It has no predefined shape. Its final shape will depend on the input parameters.
  33665. * Please consider using the same method from the MeshBuilder class instead
  33666. * @see http://doc.babylonjs.com/how_to/parametric_shapes
  33667. * @param name defines the name of the mesh to create
  33668. * @param path is a required array of successive Vector3. It is the curve used as the axis of the tube
  33669. * @param radius sets the tube radius size
  33670. * @param tessellation is the number of sides on the tubular surface
  33671. * @param radiusFunction is a custom function. If it is not null, it overwrittes the parameter `radius`. 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
  33672. * @param 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
  33673. * @param scene defines the hosting scene
  33674. * @param updatable defines if the mesh must be flagged as updatable
  33675. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  33676. * @param instance is an instance of an existing Tube object to be updated with the passed `pathArray` parameter (http://doc.babylonjs.com/how_to/How_to_dynamically_morph_a_mesh#tube)
  33677. * @returns a new Mesh
  33678. */
  33679. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  33680. var options = {
  33681. path: path,
  33682. radius: radius,
  33683. tessellation: tessellation,
  33684. radiusFunction: radiusFunction,
  33685. arc: 1,
  33686. cap: cap,
  33687. updatable: updatable,
  33688. sideOrientation: sideOrientation,
  33689. instance: instance
  33690. };
  33691. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  33692. };
  33693. /**
  33694. * Creates a polyhedron mesh.
  33695. * Please consider using the same method from the MeshBuilder class instead.
  33696. * * 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
  33697. * * The parameter `size` (positive float, default 1) sets the polygon size
  33698. * * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value)
  33699. * * 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`
  33700. * * 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
  33701. * * 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)`)
  33702. * * 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
  33703. * * 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
  33704. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33705. * * 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
  33706. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  33707. * @param name defines the name of the mesh to create
  33708. * @param options defines the options used to create the mesh
  33709. * @param scene defines the hosting scene
  33710. * @returns a new Mesh
  33711. */
  33712. Mesh.CreatePolyhedron = function (name, options, scene) {
  33713. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  33714. };
  33715. /**
  33716. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided
  33717. * * The parameter `radius` sets the radius size (float) of the icosphere (default 1)
  33718. * * 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`)
  33719. * * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size
  33720. * * 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
  33721. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33722. * * 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
  33723. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  33724. * @param name defines the name of the mesh
  33725. * @param options defines the options used to create the mesh
  33726. * @param scene defines the hosting scene
  33727. * @returns a new Mesh
  33728. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes#icosphere
  33729. */
  33730. Mesh.CreateIcoSphere = function (name, options, scene) {
  33731. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  33732. };
  33733. /**
  33734. * Creates a decal mesh.
  33735. * Please consider using the same method from the MeshBuilder class instead.
  33736. * A decal is a mesh usually applied as a model onto the surface of another mesh
  33737. * @param name defines the name of the mesh
  33738. * @param sourceMesh defines the mesh receiving the decal
  33739. * @param position sets the position of the decal in world coordinates
  33740. * @param normal sets the normal of the mesh where the decal is applied onto in world coordinates
  33741. * @param size sets the decal scaling
  33742. * @param angle sets the angle to rotate the decal
  33743. * @returns a new Mesh
  33744. */
  33745. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  33746. var options = {
  33747. position: position,
  33748. normal: normal,
  33749. size: size,
  33750. angle: angle
  33751. };
  33752. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  33753. };
  33754. // Skeletons
  33755. /**
  33756. * Prepare internal position array for software CPU skinning
  33757. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh
  33758. */
  33759. Mesh.prototype.setPositionsForCPUSkinning = function () {
  33760. if (!this._sourcePositions) {
  33761. var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33762. if (!source) {
  33763. return this._sourcePositions;
  33764. }
  33765. this._sourcePositions = new Float32Array(source);
  33766. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  33767. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  33768. }
  33769. }
  33770. return this._sourcePositions;
  33771. };
  33772. /**
  33773. * Prepare internal normal array for software CPU skinning
  33774. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  33775. */
  33776. Mesh.prototype.setNormalsForCPUSkinning = function () {
  33777. if (!this._sourceNormals) {
  33778. var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  33779. if (!source) {
  33780. return this._sourceNormals;
  33781. }
  33782. this._sourceNormals = new Float32Array(source);
  33783. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  33784. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  33785. }
  33786. }
  33787. return this._sourceNormals;
  33788. };
  33789. /**
  33790. * Updates the vertex buffer by applying transformation from the bones
  33791. * @param skeleton defines the skeleton to apply to current mesh
  33792. * @returns the current mesh
  33793. */
  33794. Mesh.prototype.applySkeleton = function (skeleton) {
  33795. if (!this.geometry) {
  33796. return this;
  33797. }
  33798. if (this.geometry._softwareSkinningFrameId == this.getScene().getFrameId()) {
  33799. return this;
  33800. }
  33801. this.geometry._softwareSkinningFrameId = this.getScene().getFrameId();
  33802. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  33803. return this;
  33804. }
  33805. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  33806. return this;
  33807. }
  33808. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  33809. return this;
  33810. }
  33811. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  33812. return this;
  33813. }
  33814. if (!this._sourcePositions) {
  33815. var submeshes = this.subMeshes.slice();
  33816. this.setPositionsForCPUSkinning();
  33817. this.subMeshes = submeshes;
  33818. }
  33819. if (!this._sourceNormals) {
  33820. this.setNormalsForCPUSkinning();
  33821. }
  33822. // positionsData checks for not being Float32Array will only pass at most once
  33823. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33824. if (!positionsData) {
  33825. return this;
  33826. }
  33827. if (!(positionsData instanceof Float32Array)) {
  33828. positionsData = new Float32Array(positionsData);
  33829. }
  33830. // normalsData checks for not being Float32Array will only pass at most once
  33831. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  33832. if (!normalsData) {
  33833. return this;
  33834. }
  33835. if (!(normalsData instanceof Float32Array)) {
  33836. normalsData = new Float32Array(normalsData);
  33837. }
  33838. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  33839. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  33840. if (!matricesWeightsData || !matricesIndicesData) {
  33841. return this;
  33842. }
  33843. var needExtras = this.numBoneInfluencers > 4;
  33844. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  33845. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  33846. var skeletonMatrices = skeleton.getTransformMatrices(this);
  33847. var tempVector3 = BABYLON.Vector3.Zero();
  33848. var finalMatrix = new BABYLON.Matrix();
  33849. var tempMatrix = new BABYLON.Matrix();
  33850. var matWeightIdx = 0;
  33851. var inf;
  33852. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  33853. var weight;
  33854. for (inf = 0; inf < 4; inf++) {
  33855. weight = matricesWeightsData[matWeightIdx + inf];
  33856. if (weight > 0) {
  33857. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  33858. finalMatrix.addToSelf(tempMatrix);
  33859. }
  33860. }
  33861. if (needExtras) {
  33862. for (inf = 0; inf < 4; inf++) {
  33863. weight = matricesWeightsExtraData[matWeightIdx + inf];
  33864. if (weight > 0) {
  33865. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  33866. finalMatrix.addToSelf(tempMatrix);
  33867. }
  33868. }
  33869. }
  33870. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  33871. tempVector3.toArray(positionsData, index);
  33872. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  33873. tempVector3.toArray(normalsData, index);
  33874. finalMatrix.reset();
  33875. }
  33876. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  33877. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  33878. return this;
  33879. };
  33880. // Tools
  33881. /**
  33882. * Returns an object containing a min and max Vector3 which are the minimum and maximum vectors of each mesh bounding box from the passed array, in the world coordinates
  33883. * @param meshes defines the list of meshes to scan
  33884. * @returns an object `{min:` Vector3`, max:` Vector3`}`
  33885. */
  33886. Mesh.MinMax = function (meshes) {
  33887. var minVector = null;
  33888. var maxVector = null;
  33889. meshes.forEach(function (mesh, index, array) {
  33890. var boundingInfo = mesh.getBoundingInfo();
  33891. var boundingBox = boundingInfo.boundingBox;
  33892. if (!minVector || !maxVector) {
  33893. minVector = boundingBox.minimumWorld;
  33894. maxVector = boundingBox.maximumWorld;
  33895. }
  33896. else {
  33897. minVector.minimizeInPlace(boundingBox.minimumWorld);
  33898. maxVector.maximizeInPlace(boundingBox.maximumWorld);
  33899. }
  33900. });
  33901. if (!minVector || !maxVector) {
  33902. return {
  33903. min: BABYLON.Vector3.Zero(),
  33904. max: BABYLON.Vector3.Zero()
  33905. };
  33906. }
  33907. return {
  33908. min: minVector,
  33909. max: maxVector
  33910. };
  33911. };
  33912. /**
  33913. * Returns the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array
  33914. * @param meshesOrMinMaxVector could be an array of meshes or a `{min:` Vector3`, max:` Vector3`}` object
  33915. * @returns a vector3
  33916. */
  33917. Mesh.Center = function (meshesOrMinMaxVector) {
  33918. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  33919. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  33920. };
  33921. /**
  33922. * Merge the array of meshes into a single mesh for performance reasons.
  33923. * @param meshes defines he vertices source. They should all be of the same material. Entries can empty
  33924. * @param disposeSource when true (default), dispose of the vertices from the source meshes
  33925. * @param allow32BitsIndices when the sum of the vertices > 64k, this must be set to true
  33926. * @param meshSubclass when set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  33927. * @param subdivideWithSubMeshes when true (false default), subdivide mesh to his subMesh array with meshes source.
  33928. * @returns a new mesh
  33929. */
  33930. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  33931. if (disposeSource === void 0) { disposeSource = true; }
  33932. var index;
  33933. if (!allow32BitsIndices) {
  33934. var totalVertices = 0;
  33935. // Counting vertices
  33936. for (index = 0; index < meshes.length; index++) {
  33937. if (meshes[index]) {
  33938. totalVertices += meshes[index].getTotalVertices();
  33939. if (totalVertices > 65536) {
  33940. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  33941. return null;
  33942. }
  33943. }
  33944. }
  33945. }
  33946. // Merge
  33947. var vertexData = null;
  33948. var otherVertexData;
  33949. var indiceArray = new Array();
  33950. var source = null;
  33951. for (index = 0; index < meshes.length; index++) {
  33952. if (meshes[index]) {
  33953. var wm = meshes[index].computeWorldMatrix(true);
  33954. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true, true);
  33955. otherVertexData.transform(wm);
  33956. if (vertexData) {
  33957. vertexData.merge(otherVertexData, allow32BitsIndices);
  33958. }
  33959. else {
  33960. vertexData = otherVertexData;
  33961. source = meshes[index];
  33962. }
  33963. if (subdivideWithSubMeshes) {
  33964. indiceArray.push(meshes[index].getTotalIndices());
  33965. }
  33966. }
  33967. }
  33968. source = source;
  33969. if (!meshSubclass) {
  33970. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  33971. }
  33972. vertexData.applyToMesh(meshSubclass);
  33973. // Setting properties
  33974. meshSubclass.material = source.material;
  33975. meshSubclass.checkCollisions = source.checkCollisions;
  33976. // Cleaning
  33977. if (disposeSource) {
  33978. for (index = 0; index < meshes.length; index++) {
  33979. if (meshes[index]) {
  33980. meshes[index].dispose();
  33981. }
  33982. }
  33983. }
  33984. // Subdivide
  33985. if (subdivideWithSubMeshes) {
  33986. //-- removal of global submesh
  33987. meshSubclass.releaseSubMeshes();
  33988. index = 0;
  33989. var offset = 0;
  33990. //-- apply subdivision according to index table
  33991. while (index < indiceArray.length) {
  33992. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  33993. offset += indiceArray[index];
  33994. index++;
  33995. }
  33996. }
  33997. return meshSubclass;
  33998. };
  33999. // Consts
  34000. /**
  34001. * Mesh side orientation : usually the external or front surface
  34002. */
  34003. Mesh.FRONTSIDE = 0;
  34004. /**
  34005. * Mesh side orientation : usually the internal or back surface
  34006. */
  34007. Mesh.BACKSIDE = 1;
  34008. /**
  34009. * Mesh side orientation : both internal and external or front and back surfaces
  34010. */
  34011. Mesh.DOUBLESIDE = 2;
  34012. /**
  34013. * Mesh side orientation : by default, `FRONTSIDE`
  34014. */
  34015. Mesh.DEFAULTSIDE = 0;
  34016. /**
  34017. * Mesh cap setting : no cap
  34018. */
  34019. Mesh.NO_CAP = 0;
  34020. /**
  34021. * Mesh cap setting : one cap at the beginning of the mesh
  34022. */
  34023. Mesh.CAP_START = 1;
  34024. /**
  34025. * Mesh cap setting : one cap at the end of the mesh
  34026. */
  34027. Mesh.CAP_END = 2;
  34028. /**
  34029. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  34030. */
  34031. Mesh.CAP_ALL = 3;
  34032. return Mesh;
  34033. }(BABYLON.AbstractMesh));
  34034. BABYLON.Mesh = Mesh;
  34035. })(BABYLON || (BABYLON = {}));
  34036. //# sourceMappingURL=babylon.mesh.js.map
  34037. var BABYLON;
  34038. (function (BABYLON) {
  34039. var BaseSubMesh = /** @class */ (function () {
  34040. function BaseSubMesh() {
  34041. }
  34042. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  34043. get: function () {
  34044. return this._materialEffect;
  34045. },
  34046. enumerable: true,
  34047. configurable: true
  34048. });
  34049. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  34050. if (defines === void 0) { defines = null; }
  34051. if (this._materialEffect === effect) {
  34052. if (!effect) {
  34053. this._materialDefines = null;
  34054. }
  34055. return;
  34056. }
  34057. this._materialDefines = defines;
  34058. this._materialEffect = effect;
  34059. };
  34060. return BaseSubMesh;
  34061. }());
  34062. BABYLON.BaseSubMesh = BaseSubMesh;
  34063. var SubMesh = /** @class */ (function (_super) {
  34064. __extends(SubMesh, _super);
  34065. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  34066. if (createBoundingBox === void 0) { createBoundingBox = true; }
  34067. var _this = _super.call(this) || this;
  34068. _this.materialIndex = materialIndex;
  34069. _this.verticesStart = verticesStart;
  34070. _this.verticesCount = verticesCount;
  34071. _this.indexStart = indexStart;
  34072. _this.indexCount = indexCount;
  34073. /** @hidden */
  34074. _this._renderId = 0;
  34075. _this._mesh = mesh;
  34076. _this._renderingMesh = renderingMesh || mesh;
  34077. mesh.subMeshes.push(_this);
  34078. _this._trianglePlanes = [];
  34079. _this._id = mesh.subMeshes.length - 1;
  34080. if (createBoundingBox) {
  34081. _this.refreshBoundingInfo();
  34082. mesh.computeWorldMatrix(true);
  34083. }
  34084. return _this;
  34085. }
  34086. SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  34087. if (createBoundingBox === void 0) { createBoundingBox = true; }
  34088. return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
  34089. };
  34090. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  34091. get: function () {
  34092. return (this.verticesStart === 0 && this.verticesCount === this._mesh.getTotalVertices());
  34093. },
  34094. enumerable: true,
  34095. configurable: true
  34096. });
  34097. /**
  34098. * Returns the submesh BoudingInfo object.
  34099. */
  34100. SubMesh.prototype.getBoundingInfo = function () {
  34101. if (this.IsGlobal) {
  34102. return this._mesh.getBoundingInfo();
  34103. }
  34104. return this._boundingInfo;
  34105. };
  34106. /**
  34107. * Sets the submesh BoundingInfo.
  34108. * Return the SubMesh.
  34109. */
  34110. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  34111. this._boundingInfo = boundingInfo;
  34112. return this;
  34113. };
  34114. /**
  34115. * Returns the mesh of the current submesh.
  34116. */
  34117. SubMesh.prototype.getMesh = function () {
  34118. return this._mesh;
  34119. };
  34120. /**
  34121. * Returns the rendering mesh of the submesh.
  34122. */
  34123. SubMesh.prototype.getRenderingMesh = function () {
  34124. return this._renderingMesh;
  34125. };
  34126. /**
  34127. * Returns the submesh material.
  34128. */
  34129. SubMesh.prototype.getMaterial = function () {
  34130. var rootMaterial = this._renderingMesh.material;
  34131. if (rootMaterial === null || rootMaterial === undefined) {
  34132. return this._mesh.getScene().defaultMaterial;
  34133. }
  34134. else if (rootMaterial.getSubMaterial) {
  34135. var multiMaterial = rootMaterial;
  34136. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  34137. if (this._currentMaterial !== effectiveMaterial) {
  34138. this._currentMaterial = effectiveMaterial;
  34139. this._materialDefines = null;
  34140. }
  34141. return effectiveMaterial;
  34142. }
  34143. return rootMaterial;
  34144. };
  34145. // Methods
  34146. /**
  34147. * Sets a new updated BoundingInfo object to the submesh.
  34148. * Returns the SubMesh.
  34149. */
  34150. SubMesh.prototype.refreshBoundingInfo = function () {
  34151. this._lastColliderWorldVertices = null;
  34152. if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
  34153. return this;
  34154. }
  34155. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34156. if (!data) {
  34157. this._boundingInfo = this._mesh.getBoundingInfo();
  34158. return this;
  34159. }
  34160. var indices = this._renderingMesh.getIndices();
  34161. var extend;
  34162. //is this the only submesh?
  34163. if (this.indexStart === 0 && this.indexCount === indices.length) {
  34164. var boundingInfo = this._renderingMesh.getBoundingInfo();
  34165. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  34166. extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
  34167. }
  34168. else {
  34169. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  34170. }
  34171. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  34172. return this;
  34173. };
  34174. /** @hidden */
  34175. SubMesh.prototype._checkCollision = function (collider) {
  34176. var boundingInfo = this.getBoundingInfo();
  34177. return boundingInfo._checkCollision(collider);
  34178. };
  34179. /**
  34180. * Updates the submesh BoundingInfo.
  34181. * Returns the Submesh.
  34182. */
  34183. SubMesh.prototype.updateBoundingInfo = function (world) {
  34184. var boundingInfo = this.getBoundingInfo();
  34185. if (!boundingInfo) {
  34186. this.refreshBoundingInfo();
  34187. boundingInfo = this.getBoundingInfo();
  34188. }
  34189. boundingInfo.update(world);
  34190. return this;
  34191. };
  34192. /**
  34193. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  34194. * Boolean returned.
  34195. */
  34196. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  34197. var boundingInfo = this.getBoundingInfo();
  34198. if (!boundingInfo) {
  34199. return false;
  34200. }
  34201. return boundingInfo.isInFrustum(frustumPlanes);
  34202. };
  34203. /**
  34204. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  34205. * Boolean returned.
  34206. */
  34207. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  34208. var boundingInfo = this.getBoundingInfo();
  34209. if (!boundingInfo) {
  34210. return false;
  34211. }
  34212. return boundingInfo.isCompletelyInFrustum(frustumPlanes);
  34213. };
  34214. /**
  34215. * Renders the submesh.
  34216. * Returns it.
  34217. */
  34218. SubMesh.prototype.render = function (enableAlphaMode) {
  34219. this._renderingMesh.render(this, enableAlphaMode);
  34220. return this;
  34221. };
  34222. /**
  34223. * Returns a new Index Buffer.
  34224. * Type returned : WebGLBuffer.
  34225. */
  34226. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  34227. if (!this._linesIndexBuffer) {
  34228. var linesIndices = [];
  34229. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  34230. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  34231. }
  34232. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  34233. this.linesIndexCount = linesIndices.length;
  34234. }
  34235. return this._linesIndexBuffer;
  34236. };
  34237. /**
  34238. * True is the passed Ray intersects the submesh bounding box.
  34239. * Boolean returned.
  34240. */
  34241. SubMesh.prototype.canIntersects = function (ray) {
  34242. var boundingInfo = this.getBoundingInfo();
  34243. if (!boundingInfo) {
  34244. return false;
  34245. }
  34246. return ray.intersectsBox(boundingInfo.boundingBox);
  34247. };
  34248. /**
  34249. * Returns an object IntersectionInfo.
  34250. */
  34251. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  34252. var intersectInfo = null;
  34253. var material = this.getMaterial();
  34254. if (!material) {
  34255. return null;
  34256. }
  34257. switch (material.fillMode) {
  34258. case BABYLON.Material.PointListDrawMode:
  34259. case BABYLON.Material.LineListDrawMode:
  34260. case BABYLON.Material.LineLoopDrawMode:
  34261. case BABYLON.Material.LineStripDrawMode:
  34262. case BABYLON.Material.TriangleFanDrawMode:
  34263. case BABYLON.Material.TriangleStripDrawMode:
  34264. return null;
  34265. }
  34266. // LineMesh first as it's also a Mesh...
  34267. if (BABYLON.LinesMesh && this._mesh instanceof BABYLON.LinesMesh) {
  34268. var lineMesh = this._mesh;
  34269. // Line test
  34270. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  34271. var p0 = positions[indices[index]];
  34272. var p1 = positions[indices[index + 1]];
  34273. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  34274. if (length < 0) {
  34275. continue;
  34276. }
  34277. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  34278. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  34279. if (fastCheck) {
  34280. break;
  34281. }
  34282. }
  34283. }
  34284. }
  34285. else {
  34286. // Triangles test
  34287. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  34288. var p0 = positions[indices[index]];
  34289. var p1 = positions[indices[index + 1]];
  34290. var p2 = positions[indices[index + 2]];
  34291. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  34292. if (currentIntersectInfo) {
  34293. if (currentIntersectInfo.distance < 0) {
  34294. continue;
  34295. }
  34296. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  34297. intersectInfo = currentIntersectInfo;
  34298. intersectInfo.faceId = index / 3;
  34299. if (fastCheck) {
  34300. break;
  34301. }
  34302. }
  34303. }
  34304. }
  34305. }
  34306. return intersectInfo;
  34307. };
  34308. /** @hidden */
  34309. SubMesh.prototype._rebuild = function () {
  34310. if (this._linesIndexBuffer) {
  34311. this._linesIndexBuffer = null;
  34312. }
  34313. };
  34314. // Clone
  34315. /**
  34316. * Creates a new Submesh from the passed Mesh.
  34317. */
  34318. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  34319. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  34320. if (!this.IsGlobal) {
  34321. var boundingInfo = this.getBoundingInfo();
  34322. if (!boundingInfo) {
  34323. return result;
  34324. }
  34325. result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
  34326. }
  34327. return result;
  34328. };
  34329. // Dispose
  34330. /**
  34331. * Disposes the Submesh.
  34332. * Returns nothing.
  34333. */
  34334. SubMesh.prototype.dispose = function () {
  34335. if (this._linesIndexBuffer) {
  34336. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  34337. this._linesIndexBuffer = null;
  34338. }
  34339. // Remove from mesh
  34340. var index = this._mesh.subMeshes.indexOf(this);
  34341. this._mesh.subMeshes.splice(index, 1);
  34342. };
  34343. // Statics
  34344. /**
  34345. * Creates a new Submesh from the passed parameters :
  34346. * - materialIndex (integer) : the index of the main mesh material.
  34347. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  34348. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  34349. * - mesh (Mesh) : the main mesh to create the submesh from.
  34350. * - renderingMesh (optional Mesh) : rendering mesh.
  34351. */
  34352. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  34353. var minVertexIndex = Number.MAX_VALUE;
  34354. var maxVertexIndex = -Number.MAX_VALUE;
  34355. renderingMesh = (renderingMesh || mesh);
  34356. var indices = renderingMesh.getIndices();
  34357. for (var index = startIndex; index < startIndex + indexCount; index++) {
  34358. var vertexIndex = indices[index];
  34359. if (vertexIndex < minVertexIndex)
  34360. minVertexIndex = vertexIndex;
  34361. if (vertexIndex > maxVertexIndex)
  34362. maxVertexIndex = vertexIndex;
  34363. }
  34364. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  34365. };
  34366. return SubMesh;
  34367. }(BaseSubMesh));
  34368. BABYLON.SubMesh = SubMesh;
  34369. })(BABYLON || (BABYLON = {}));
  34370. //# sourceMappingURL=babylon.subMesh.js.map
  34371. var __assign = (this && this.__assign) || function () {
  34372. __assign = Object.assign || function(t) {
  34373. for (var s, i = 1, n = arguments.length; i < n; i++) {
  34374. s = arguments[i];
  34375. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  34376. t[p] = s[p];
  34377. }
  34378. return t;
  34379. };
  34380. return __assign.apply(this, arguments);
  34381. };
  34382. var BABYLON;
  34383. (function (BABYLON) {
  34384. /**
  34385. * Manages the defines for the Material
  34386. */
  34387. var MaterialDefines = /** @class */ (function () {
  34388. function MaterialDefines() {
  34389. this._isDirty = true;
  34390. /** @hidden */
  34391. this._areLightsDirty = true;
  34392. /** @hidden */
  34393. this._areAttributesDirty = true;
  34394. /** @hidden */
  34395. this._areTexturesDirty = true;
  34396. /** @hidden */
  34397. this._areFresnelDirty = true;
  34398. /** @hidden */
  34399. this._areMiscDirty = true;
  34400. /** @hidden */
  34401. this._areImageProcessingDirty = true;
  34402. /** @hidden */
  34403. this._normals = false;
  34404. /** @hidden */
  34405. this._uvs = false;
  34406. /** @hidden */
  34407. this._needNormals = false;
  34408. /** @hidden */
  34409. this._needUVs = false;
  34410. }
  34411. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  34412. /**
  34413. * Specifies if the material needs to be re-calculated
  34414. */
  34415. get: function () {
  34416. return this._isDirty;
  34417. },
  34418. enumerable: true,
  34419. configurable: true
  34420. });
  34421. /**
  34422. * Marks the material to indicate that it has been re-calculated
  34423. */
  34424. MaterialDefines.prototype.markAsProcessed = function () {
  34425. this._isDirty = false;
  34426. this._areAttributesDirty = false;
  34427. this._areTexturesDirty = false;
  34428. this._areFresnelDirty = false;
  34429. this._areLightsDirty = false;
  34430. this._areMiscDirty = false;
  34431. this._areImageProcessingDirty = false;
  34432. };
  34433. /**
  34434. * Marks the material to indicate that it needs to be re-calculated
  34435. */
  34436. MaterialDefines.prototype.markAsUnprocessed = function () {
  34437. this._isDirty = true;
  34438. };
  34439. /**
  34440. * Marks the material to indicate all of its defines need to be re-calculated
  34441. */
  34442. MaterialDefines.prototype.markAllAsDirty = function () {
  34443. this._areTexturesDirty = true;
  34444. this._areAttributesDirty = true;
  34445. this._areLightsDirty = true;
  34446. this._areFresnelDirty = true;
  34447. this._areMiscDirty = true;
  34448. this._areImageProcessingDirty = true;
  34449. this._isDirty = true;
  34450. };
  34451. /**
  34452. * Marks the material to indicate that image processing needs to be re-calculated
  34453. */
  34454. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  34455. this._areImageProcessingDirty = true;
  34456. this._isDirty = true;
  34457. };
  34458. /**
  34459. * Marks the material to indicate the lights need to be re-calculated
  34460. */
  34461. MaterialDefines.prototype.markAsLightDirty = function () {
  34462. this._areLightsDirty = true;
  34463. this._isDirty = true;
  34464. };
  34465. /**
  34466. * Marks the attribute state as changed
  34467. */
  34468. MaterialDefines.prototype.markAsAttributesDirty = function () {
  34469. this._areAttributesDirty = true;
  34470. this._isDirty = true;
  34471. };
  34472. /**
  34473. * Marks the texture state as changed
  34474. */
  34475. MaterialDefines.prototype.markAsTexturesDirty = function () {
  34476. this._areTexturesDirty = true;
  34477. this._isDirty = true;
  34478. };
  34479. /**
  34480. * Marks the fresnel state as changed
  34481. */
  34482. MaterialDefines.prototype.markAsFresnelDirty = function () {
  34483. this._areFresnelDirty = true;
  34484. this._isDirty = true;
  34485. };
  34486. /**
  34487. * Marks the misc state as changed
  34488. */
  34489. MaterialDefines.prototype.markAsMiscDirty = function () {
  34490. this._areMiscDirty = true;
  34491. this._isDirty = true;
  34492. };
  34493. /**
  34494. * Rebuilds the material defines
  34495. */
  34496. MaterialDefines.prototype.rebuild = function () {
  34497. if (this._keys) {
  34498. delete this._keys;
  34499. }
  34500. this._keys = [];
  34501. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  34502. var key = _a[_i];
  34503. if (key[0] === "_") {
  34504. continue;
  34505. }
  34506. this._keys.push(key);
  34507. }
  34508. };
  34509. /**
  34510. * Specifies if two material defines are equal
  34511. * @param other - A material define instance to compare to
  34512. * @returns - Boolean indicating if the material defines are equal (true) or not (false)
  34513. */
  34514. MaterialDefines.prototype.isEqual = function (other) {
  34515. if (this._keys.length !== other._keys.length) {
  34516. return false;
  34517. }
  34518. for (var index = 0; index < this._keys.length; index++) {
  34519. var prop = this._keys[index];
  34520. if (this[prop] !== other[prop]) {
  34521. return false;
  34522. }
  34523. }
  34524. return true;
  34525. };
  34526. /**
  34527. * Clones this instance's defines to another instance
  34528. * @param other - material defines to clone values to
  34529. */
  34530. MaterialDefines.prototype.cloneTo = function (other) {
  34531. if (this._keys.length !== other._keys.length) {
  34532. other._keys = this._keys.slice(0);
  34533. }
  34534. for (var index = 0; index < this._keys.length; index++) {
  34535. var prop = this._keys[index];
  34536. other[prop] = this[prop];
  34537. }
  34538. };
  34539. /**
  34540. * Resets the material define values
  34541. */
  34542. MaterialDefines.prototype.reset = function () {
  34543. for (var index = 0; index < this._keys.length; index++) {
  34544. var prop = this._keys[index];
  34545. var type = typeof this[prop];
  34546. switch (type) {
  34547. case "number":
  34548. this[prop] = 0;
  34549. break;
  34550. case "string":
  34551. this[prop] = "";
  34552. break;
  34553. default:
  34554. this[prop] = false;
  34555. break;
  34556. }
  34557. }
  34558. };
  34559. /**
  34560. * Converts the material define values to a string
  34561. * @returns - String of material define information
  34562. */
  34563. MaterialDefines.prototype.toString = function () {
  34564. var result = "";
  34565. for (var index = 0; index < this._keys.length; index++) {
  34566. var prop = this._keys[index];
  34567. var value = this[prop];
  34568. var type = typeof value;
  34569. switch (type) {
  34570. case "number":
  34571. case "string":
  34572. result += "#define " + prop + " " + value + "\n";
  34573. break;
  34574. default:
  34575. if (value) {
  34576. result += "#define " + prop + "\n";
  34577. }
  34578. break;
  34579. }
  34580. }
  34581. return result;
  34582. };
  34583. return MaterialDefines;
  34584. }());
  34585. BABYLON.MaterialDefines = MaterialDefines;
  34586. /**
  34587. * Base class for the main features of a material in Babylon.js
  34588. */
  34589. var Material = /** @class */ (function () {
  34590. /**
  34591. * Creates a material instance
  34592. * @param name defines the name of the material
  34593. * @param scene defines the scene to reference
  34594. * @param doNotAdd specifies if the material should be added to the scene
  34595. */
  34596. function Material(name, scene, doNotAdd) {
  34597. /**
  34598. * Specifies if the ready state should be checked on each call
  34599. */
  34600. this.checkReadyOnEveryCall = false;
  34601. /**
  34602. * Specifies if the ready state should be checked once
  34603. */
  34604. this.checkReadyOnlyOnce = false;
  34605. /**
  34606. * The state of the material
  34607. */
  34608. this.state = "";
  34609. /**
  34610. * The alpha value of the material
  34611. */
  34612. this._alpha = 1.0;
  34613. /**
  34614. * Specifies if back face culling is enabled
  34615. */
  34616. this._backFaceCulling = true;
  34617. /**
  34618. * Gets a boolean indicating that current material needs to register RTT
  34619. */
  34620. this.hasRenderTargetTextures = false;
  34621. /**
  34622. * Specifies if the material should be serialized
  34623. */
  34624. this.doNotSerialize = false;
  34625. /**
  34626. * Specifies if the effect should be stored on sub meshes
  34627. */
  34628. this.storeEffectOnSubMeshes = false;
  34629. /**
  34630. * An event triggered when the material is disposed
  34631. */
  34632. this.onDisposeObservable = new BABYLON.Observable();
  34633. /**
  34634. * Stores the value of the alpha mode
  34635. */
  34636. this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  34637. /**
  34638. * Stores the state of the need depth pre-pass value
  34639. */
  34640. this._needDepthPrePass = false;
  34641. /**
  34642. * Specifies if depth writing should be disabled
  34643. */
  34644. this.disableDepthWrite = false;
  34645. /**
  34646. * Specifies if depth writing should be forced
  34647. */
  34648. this.forceDepthWrite = false;
  34649. /**
  34650. * Specifies if there should be a separate pass for culling
  34651. */
  34652. this.separateCullingPass = false;
  34653. /**
  34654. * Stores the state specifing if fog should be enabled
  34655. */
  34656. this._fogEnabled = true;
  34657. /**
  34658. * Stores the size of points
  34659. */
  34660. this.pointSize = 1.0;
  34661. /**
  34662. * Stores the z offset value
  34663. */
  34664. this.zOffset = 0;
  34665. /**
  34666. * @hidden
  34667. * Specifies if the material was previously ready
  34668. */
  34669. this._wasPreviouslyReady = false;
  34670. /**
  34671. * Stores the fill mode state
  34672. */
  34673. this._fillMode = Material.TriangleFillMode;
  34674. this.name = name;
  34675. this.id = name || BABYLON.Tools.RandomId();
  34676. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  34677. this.uniqueId = this._scene.getUniqueId();
  34678. if (this._scene.useRightHandedSystem) {
  34679. this.sideOrientation = Material.ClockWiseSideOrientation;
  34680. }
  34681. else {
  34682. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  34683. }
  34684. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  34685. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  34686. if (!doNotAdd) {
  34687. this._scene.materials.push(this);
  34688. }
  34689. }
  34690. Object.defineProperty(Material, "TriangleFillMode", {
  34691. /**
  34692. * Returns the triangle fill mode
  34693. */
  34694. get: function () {
  34695. return Material._TriangleFillMode;
  34696. },
  34697. enumerable: true,
  34698. configurable: true
  34699. });
  34700. Object.defineProperty(Material, "WireFrameFillMode", {
  34701. /**
  34702. * Returns the wireframe mode
  34703. */
  34704. get: function () {
  34705. return Material._WireFrameFillMode;
  34706. },
  34707. enumerable: true,
  34708. configurable: true
  34709. });
  34710. Object.defineProperty(Material, "PointFillMode", {
  34711. /**
  34712. * Returns the point fill mode
  34713. */
  34714. get: function () {
  34715. return Material._PointFillMode;
  34716. },
  34717. enumerable: true,
  34718. configurable: true
  34719. });
  34720. Object.defineProperty(Material, "PointListDrawMode", {
  34721. /**
  34722. * Returns the point list draw mode
  34723. */
  34724. get: function () {
  34725. return Material._PointListDrawMode;
  34726. },
  34727. enumerable: true,
  34728. configurable: true
  34729. });
  34730. Object.defineProperty(Material, "LineListDrawMode", {
  34731. /**
  34732. * Returns the line list draw mode
  34733. */
  34734. get: function () {
  34735. return Material._LineListDrawMode;
  34736. },
  34737. enumerable: true,
  34738. configurable: true
  34739. });
  34740. Object.defineProperty(Material, "LineLoopDrawMode", {
  34741. /**
  34742. * Returns the line loop draw mode
  34743. */
  34744. get: function () {
  34745. return Material._LineLoopDrawMode;
  34746. },
  34747. enumerable: true,
  34748. configurable: true
  34749. });
  34750. Object.defineProperty(Material, "LineStripDrawMode", {
  34751. /**
  34752. * Returns the line strip draw mode
  34753. */
  34754. get: function () {
  34755. return Material._LineStripDrawMode;
  34756. },
  34757. enumerable: true,
  34758. configurable: true
  34759. });
  34760. Object.defineProperty(Material, "TriangleStripDrawMode", {
  34761. /**
  34762. * Returns the triangle strip draw mode
  34763. */
  34764. get: function () {
  34765. return Material._TriangleStripDrawMode;
  34766. },
  34767. enumerable: true,
  34768. configurable: true
  34769. });
  34770. Object.defineProperty(Material, "TriangleFanDrawMode", {
  34771. /**
  34772. * Returns the triangle fan draw mode
  34773. */
  34774. get: function () {
  34775. return Material._TriangleFanDrawMode;
  34776. },
  34777. enumerable: true,
  34778. configurable: true
  34779. });
  34780. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  34781. /**
  34782. * Returns the clock-wise side orientation
  34783. */
  34784. get: function () {
  34785. return Material._ClockWiseSideOrientation;
  34786. },
  34787. enumerable: true,
  34788. configurable: true
  34789. });
  34790. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  34791. /**
  34792. * Returns the counter clock-wise side orientation
  34793. */
  34794. get: function () {
  34795. return Material._CounterClockWiseSideOrientation;
  34796. },
  34797. enumerable: true,
  34798. configurable: true
  34799. });
  34800. Object.defineProperty(Material.prototype, "alpha", {
  34801. /**
  34802. * Gets the alpha value of the material
  34803. */
  34804. get: function () {
  34805. return this._alpha;
  34806. },
  34807. /**
  34808. * Sets the alpha value of the material
  34809. */
  34810. set: function (value) {
  34811. if (this._alpha === value) {
  34812. return;
  34813. }
  34814. this._alpha = value;
  34815. this.markAsDirty(Material.MiscDirtyFlag);
  34816. },
  34817. enumerable: true,
  34818. configurable: true
  34819. });
  34820. Object.defineProperty(Material.prototype, "backFaceCulling", {
  34821. /**
  34822. * Gets the back-face culling state
  34823. */
  34824. get: function () {
  34825. return this._backFaceCulling;
  34826. },
  34827. /**
  34828. * Sets the back-face culling state
  34829. */
  34830. set: function (value) {
  34831. if (this._backFaceCulling === value) {
  34832. return;
  34833. }
  34834. this._backFaceCulling = value;
  34835. this.markAsDirty(Material.TextureDirtyFlag);
  34836. },
  34837. enumerable: true,
  34838. configurable: true
  34839. });
  34840. Object.defineProperty(Material.prototype, "onDispose", {
  34841. /**
  34842. * Called during a dispose event
  34843. */
  34844. set: function (callback) {
  34845. if (this._onDisposeObserver) {
  34846. this.onDisposeObservable.remove(this._onDisposeObserver);
  34847. }
  34848. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  34849. },
  34850. enumerable: true,
  34851. configurable: true
  34852. });
  34853. Object.defineProperty(Material.prototype, "onBindObservable", {
  34854. /**
  34855. * An event triggered when the material is bound
  34856. */
  34857. get: function () {
  34858. if (!this._onBindObservable) {
  34859. this._onBindObservable = new BABYLON.Observable();
  34860. }
  34861. return this._onBindObservable;
  34862. },
  34863. enumerable: true,
  34864. configurable: true
  34865. });
  34866. Object.defineProperty(Material.prototype, "onBind", {
  34867. /**
  34868. * Called during a bind event
  34869. */
  34870. set: function (callback) {
  34871. if (this._onBindObserver) {
  34872. this.onBindObservable.remove(this._onBindObserver);
  34873. }
  34874. this._onBindObserver = this.onBindObservable.add(callback);
  34875. },
  34876. enumerable: true,
  34877. configurable: true
  34878. });
  34879. Object.defineProperty(Material.prototype, "onUnBindObservable", {
  34880. /**
  34881. * An event triggered when the material is unbound
  34882. */
  34883. get: function () {
  34884. if (!this._onUnBindObservable) {
  34885. this._onUnBindObservable = new BABYLON.Observable();
  34886. }
  34887. return this._onUnBindObservable;
  34888. },
  34889. enumerable: true,
  34890. configurable: true
  34891. });
  34892. Object.defineProperty(Material.prototype, "alphaMode", {
  34893. /**
  34894. * Gets the value of the alpha mode
  34895. */
  34896. get: function () {
  34897. return this._alphaMode;
  34898. },
  34899. /**
  34900. * Sets the value of the alpha mode.
  34901. *
  34902. * | Value | Type | Description |
  34903. * | --- | --- | --- |
  34904. * | 0 | ALPHA_DISABLE | |
  34905. * | 1 | ALPHA_ADD | |
  34906. * | 2 | ALPHA_COMBINE | |
  34907. * | 3 | ALPHA_SUBTRACT | |
  34908. * | 4 | ALPHA_MULTIPLY | |
  34909. * | 5 | ALPHA_MAXIMIZED | |
  34910. * | 6 | ALPHA_ONEONE | |
  34911. * | 7 | ALPHA_PREMULTIPLIED | |
  34912. * | 8 | ALPHA_PREMULTIPLIED_PORTERDUFF | |
  34913. * | 9 | ALPHA_INTERPOLATE | |
  34914. * | 10 | ALPHA_SCREENMODE | |
  34915. *
  34916. */
  34917. set: function (value) {
  34918. if (this._alphaMode === value) {
  34919. return;
  34920. }
  34921. this._alphaMode = value;
  34922. this.markAsDirty(Material.TextureDirtyFlag);
  34923. },
  34924. enumerable: true,
  34925. configurable: true
  34926. });
  34927. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  34928. /**
  34929. * Gets the depth pre-pass value
  34930. */
  34931. get: function () {
  34932. return this._needDepthPrePass;
  34933. },
  34934. /**
  34935. * Sets the need depth pre-pass value
  34936. */
  34937. set: function (value) {
  34938. if (this._needDepthPrePass === value) {
  34939. return;
  34940. }
  34941. this._needDepthPrePass = value;
  34942. if (this._needDepthPrePass) {
  34943. this.checkReadyOnEveryCall = true;
  34944. }
  34945. },
  34946. enumerable: true,
  34947. configurable: true
  34948. });
  34949. Object.defineProperty(Material.prototype, "fogEnabled", {
  34950. /**
  34951. * Gets the value of the fog enabled state
  34952. */
  34953. get: function () {
  34954. return this._fogEnabled;
  34955. },
  34956. /**
  34957. * Sets the state for enabling fog
  34958. */
  34959. set: function (value) {
  34960. if (this._fogEnabled === value) {
  34961. return;
  34962. }
  34963. this._fogEnabled = value;
  34964. this.markAsDirty(Material.MiscDirtyFlag);
  34965. },
  34966. enumerable: true,
  34967. configurable: true
  34968. });
  34969. Object.defineProperty(Material.prototype, "wireframe", {
  34970. /**
  34971. * Gets a value specifying if wireframe mode is enabled
  34972. */
  34973. get: function () {
  34974. switch (this._fillMode) {
  34975. case Material.WireFrameFillMode:
  34976. case Material.LineListDrawMode:
  34977. case Material.LineLoopDrawMode:
  34978. case Material.LineStripDrawMode:
  34979. return true;
  34980. }
  34981. return this._scene.forceWireframe;
  34982. },
  34983. /**
  34984. * Sets the state of wireframe mode
  34985. */
  34986. set: function (value) {
  34987. this.fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  34988. },
  34989. enumerable: true,
  34990. configurable: true
  34991. });
  34992. Object.defineProperty(Material.prototype, "pointsCloud", {
  34993. /**
  34994. * Gets the value specifying if point clouds are enabled
  34995. */
  34996. get: function () {
  34997. switch (this._fillMode) {
  34998. case Material.PointFillMode:
  34999. case Material.PointListDrawMode:
  35000. return true;
  35001. }
  35002. return this._scene.forcePointsCloud;
  35003. },
  35004. /**
  35005. * Sets the state of point cloud mode
  35006. */
  35007. set: function (value) {
  35008. this.fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  35009. },
  35010. enumerable: true,
  35011. configurable: true
  35012. });
  35013. Object.defineProperty(Material.prototype, "fillMode", {
  35014. /**
  35015. * Gets the material fill mode
  35016. */
  35017. get: function () {
  35018. return this._fillMode;
  35019. },
  35020. /**
  35021. * Sets the material fill mode
  35022. */
  35023. set: function (value) {
  35024. if (this._fillMode === value) {
  35025. return;
  35026. }
  35027. this._fillMode = value;
  35028. this.markAsDirty(Material.MiscDirtyFlag);
  35029. },
  35030. enumerable: true,
  35031. configurable: true
  35032. });
  35033. /**
  35034. * Returns a string representation of the current material
  35035. * @param fullDetails defines a boolean indicating which levels of logging is desired
  35036. * @returns a string with material information
  35037. */
  35038. Material.prototype.toString = function (fullDetails) {
  35039. var ret = "Name: " + this.name;
  35040. if (fullDetails) {
  35041. }
  35042. return ret;
  35043. };
  35044. /**
  35045. * Gets the class name of the material
  35046. * @returns a string with the class name of the material
  35047. */
  35048. Material.prototype.getClassName = function () {
  35049. return "Material";
  35050. };
  35051. Object.defineProperty(Material.prototype, "isFrozen", {
  35052. /**
  35053. * Specifies if updates for the material been locked
  35054. */
  35055. get: function () {
  35056. return this.checkReadyOnlyOnce;
  35057. },
  35058. enumerable: true,
  35059. configurable: true
  35060. });
  35061. /**
  35062. * Locks updates for the material
  35063. */
  35064. Material.prototype.freeze = function () {
  35065. this.checkReadyOnlyOnce = true;
  35066. };
  35067. /**
  35068. * Unlocks updates for the material
  35069. */
  35070. Material.prototype.unfreeze = function () {
  35071. this.checkReadyOnlyOnce = false;
  35072. };
  35073. /**
  35074. * Specifies if the material is ready to be used
  35075. * @param mesh defines the mesh to check
  35076. * @param useInstances specifies if instances should be used
  35077. * @returns a boolean indicating if the material is ready to be used
  35078. */
  35079. Material.prototype.isReady = function (mesh, useInstances) {
  35080. return true;
  35081. };
  35082. /**
  35083. * Specifies that the submesh is ready to be used
  35084. * @param mesh defines the mesh to check
  35085. * @param subMesh defines which submesh to check
  35086. * @param useInstances specifies that instances should be used
  35087. * @returns a boolean indicating that the submesh is ready or not
  35088. */
  35089. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  35090. return false;
  35091. };
  35092. /**
  35093. * Returns the material effect
  35094. * @returns the effect associated with the material
  35095. */
  35096. Material.prototype.getEffect = function () {
  35097. return this._effect;
  35098. };
  35099. /**
  35100. * Returns the current scene
  35101. * @returns a Scene
  35102. */
  35103. Material.prototype.getScene = function () {
  35104. return this._scene;
  35105. };
  35106. /**
  35107. * Specifies if the material will require alpha blending
  35108. * @returns a boolean specifying if alpha blending is needed
  35109. */
  35110. Material.prototype.needAlphaBlending = function () {
  35111. return (this.alpha < 1.0);
  35112. };
  35113. /**
  35114. * Specifies if the mesh will require alpha blending
  35115. * @param mesh defines the mesh to check
  35116. * @returns a boolean specifying if alpha blending is needed for the mesh
  35117. */
  35118. Material.prototype.needAlphaBlendingForMesh = function (mesh) {
  35119. return this.needAlphaBlending() || (mesh.visibility < 1.0) || mesh.hasVertexAlpha;
  35120. };
  35121. /**
  35122. * Specifies if this material should be rendered in alpha test mode
  35123. * @returns a boolean specifying if an alpha test is needed.
  35124. */
  35125. Material.prototype.needAlphaTesting = function () {
  35126. return false;
  35127. };
  35128. /**
  35129. * Gets the texture used for the alpha test
  35130. * @returns the texture to use for alpha testing
  35131. */
  35132. Material.prototype.getAlphaTestTexture = function () {
  35133. return null;
  35134. };
  35135. /**
  35136. * Marks the material to indicate that it needs to be re-calculated
  35137. */
  35138. Material.prototype.markDirty = function () {
  35139. this._wasPreviouslyReady = false;
  35140. };
  35141. /** @hidden */
  35142. Material.prototype._preBind = function (effect, overrideOrientation) {
  35143. if (overrideOrientation === void 0) { overrideOrientation = null; }
  35144. var engine = this._scene.getEngine();
  35145. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  35146. var reverse = orientation === Material.ClockWiseSideOrientation;
  35147. engine.enableEffect(effect ? effect : this._effect);
  35148. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  35149. return reverse;
  35150. };
  35151. /**
  35152. * Binds the material to the mesh
  35153. * @param world defines the world transformation matrix
  35154. * @param mesh defines the mesh to bind the material to
  35155. */
  35156. Material.prototype.bind = function (world, mesh) {
  35157. };
  35158. /**
  35159. * Binds the submesh to the material
  35160. * @param world defines the world transformation matrix
  35161. * @param mesh defines the mesh containing the submesh
  35162. * @param subMesh defines the submesh to bind the material to
  35163. */
  35164. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  35165. };
  35166. /**
  35167. * Binds the world matrix to the material
  35168. * @param world defines the world transformation matrix
  35169. */
  35170. Material.prototype.bindOnlyWorldMatrix = function (world) {
  35171. };
  35172. /**
  35173. * Binds the scene's uniform buffer to the effect.
  35174. * @param effect defines the effect to bind to the scene uniform buffer
  35175. * @param sceneUbo defines the uniform buffer storing scene data
  35176. */
  35177. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  35178. sceneUbo.bindToEffect(effect, "Scene");
  35179. };
  35180. /**
  35181. * Binds the view matrix to the effect
  35182. * @param effect defines the effect to bind the view matrix to
  35183. */
  35184. Material.prototype.bindView = function (effect) {
  35185. if (!this._useUBO) {
  35186. effect.setMatrix("view", this.getScene().getViewMatrix());
  35187. }
  35188. else {
  35189. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  35190. }
  35191. };
  35192. /**
  35193. * Binds the view projection matrix to the effect
  35194. * @param effect defines the effect to bind the view projection matrix to
  35195. */
  35196. Material.prototype.bindViewProjection = function (effect) {
  35197. if (!this._useUBO) {
  35198. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  35199. }
  35200. else {
  35201. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  35202. }
  35203. };
  35204. /**
  35205. * Specifies if material alpha testing should be turned on for the mesh
  35206. * @param mesh defines the mesh to check
  35207. */
  35208. Material.prototype._shouldTurnAlphaTestOn = function (mesh) {
  35209. return (!this.needAlphaBlendingForMesh(mesh) && this.needAlphaTesting());
  35210. };
  35211. /**
  35212. * Processes to execute after binding the material to a mesh
  35213. * @param mesh defines the rendered mesh
  35214. */
  35215. Material.prototype._afterBind = function (mesh) {
  35216. this._scene._cachedMaterial = this;
  35217. if (mesh) {
  35218. this._scene._cachedVisibility = mesh.visibility;
  35219. }
  35220. else {
  35221. this._scene._cachedVisibility = 1;
  35222. }
  35223. if (this._onBindObservable && mesh) {
  35224. this._onBindObservable.notifyObservers(mesh);
  35225. }
  35226. if (this.disableDepthWrite) {
  35227. var engine = this._scene.getEngine();
  35228. this._cachedDepthWriteState = engine.getDepthWrite();
  35229. engine.setDepthWrite(false);
  35230. }
  35231. };
  35232. /**
  35233. * Unbinds the material from the mesh
  35234. */
  35235. Material.prototype.unbind = function () {
  35236. if (this._onUnBindObservable) {
  35237. this._onUnBindObservable.notifyObservers(this);
  35238. }
  35239. if (this.disableDepthWrite) {
  35240. var engine = this._scene.getEngine();
  35241. engine.setDepthWrite(this._cachedDepthWriteState);
  35242. }
  35243. };
  35244. /**
  35245. * Gets the active textures from the material
  35246. * @returns an array of textures
  35247. */
  35248. Material.prototype.getActiveTextures = function () {
  35249. return [];
  35250. };
  35251. /**
  35252. * Specifies if the material uses a texture
  35253. * @param texture defines the texture to check against the material
  35254. * @returns a boolean specifying if the material uses the texture
  35255. */
  35256. Material.prototype.hasTexture = function (texture) {
  35257. return false;
  35258. };
  35259. /**
  35260. * Makes a duplicate of the material, and gives it a new name
  35261. * @param name defines the new name for the duplicated material
  35262. * @returns the cloned material
  35263. */
  35264. Material.prototype.clone = function (name) {
  35265. return null;
  35266. };
  35267. /**
  35268. * Gets the meshes bound to the material
  35269. * @returns an array of meshes bound to the material
  35270. */
  35271. Material.prototype.getBindedMeshes = function () {
  35272. var result = new Array();
  35273. for (var index = 0; index < this._scene.meshes.length; index++) {
  35274. var mesh = this._scene.meshes[index];
  35275. if (mesh.material === this) {
  35276. result.push(mesh);
  35277. }
  35278. }
  35279. return result;
  35280. };
  35281. /**
  35282. * Force shader compilation
  35283. * @param mesh defines the mesh associated with this material
  35284. * @param onCompiled defines a function to execute once the material is compiled
  35285. * @param options defines the options to configure the compilation
  35286. */
  35287. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  35288. var _this = this;
  35289. var localOptions = __assign({ clipPlane: false }, options);
  35290. var subMesh = new BABYLON.BaseSubMesh();
  35291. var scene = this.getScene();
  35292. var checkReady = function () {
  35293. if (!_this._scene || !_this._scene.getEngine()) {
  35294. return;
  35295. }
  35296. if (subMesh._materialDefines) {
  35297. subMesh._materialDefines._renderId = -1;
  35298. }
  35299. var clipPlaneState = scene.clipPlane;
  35300. if (localOptions.clipPlane) {
  35301. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  35302. }
  35303. if (_this.storeEffectOnSubMeshes) {
  35304. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  35305. if (onCompiled) {
  35306. onCompiled(_this);
  35307. }
  35308. }
  35309. else {
  35310. setTimeout(checkReady, 16);
  35311. }
  35312. }
  35313. else {
  35314. if (_this.isReady(mesh)) {
  35315. if (onCompiled) {
  35316. onCompiled(_this);
  35317. }
  35318. }
  35319. else {
  35320. setTimeout(checkReady, 16);
  35321. }
  35322. }
  35323. if (localOptions.clipPlane) {
  35324. scene.clipPlane = clipPlaneState;
  35325. }
  35326. };
  35327. checkReady();
  35328. };
  35329. /**
  35330. * Force shader compilation
  35331. * @param mesh defines the mesh that will use this material
  35332. * @param options defines additional options for compiling the shaders
  35333. * @returns a promise that resolves when the compilation completes
  35334. */
  35335. Material.prototype.forceCompilationAsync = function (mesh, options) {
  35336. var _this = this;
  35337. return new Promise(function (resolve) {
  35338. _this.forceCompilation(mesh, function () {
  35339. resolve();
  35340. }, options);
  35341. });
  35342. };
  35343. /**
  35344. * Marks a define in the material to indicate that it needs to be re-computed
  35345. * @param flag defines a flag used to determine which parts of the material have to be marked as dirty
  35346. */
  35347. Material.prototype.markAsDirty = function (flag) {
  35348. if (flag & Material.TextureDirtyFlag) {
  35349. this._markAllSubMeshesAsTexturesDirty();
  35350. }
  35351. if (flag & Material.LightDirtyFlag) {
  35352. this._markAllSubMeshesAsLightsDirty();
  35353. }
  35354. if (flag & Material.FresnelDirtyFlag) {
  35355. this._markAllSubMeshesAsFresnelDirty();
  35356. }
  35357. if (flag & Material.AttributesDirtyFlag) {
  35358. this._markAllSubMeshesAsAttributesDirty();
  35359. }
  35360. if (flag & Material.MiscDirtyFlag) {
  35361. this._markAllSubMeshesAsMiscDirty();
  35362. }
  35363. this.getScene().resetCachedMaterial();
  35364. };
  35365. /**
  35366. * Marks all submeshes of a material to indicate that their material defines need to be re-calculated
  35367. * @param func defines a function which checks material defines against the submeshes
  35368. */
  35369. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  35370. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  35371. var mesh = _a[_i];
  35372. if (!mesh.subMeshes) {
  35373. continue;
  35374. }
  35375. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  35376. var subMesh = _c[_b];
  35377. if (subMesh.getMaterial() !== this) {
  35378. continue;
  35379. }
  35380. if (!subMesh._materialDefines) {
  35381. continue;
  35382. }
  35383. func(subMesh._materialDefines);
  35384. }
  35385. }
  35386. };
  35387. /**
  35388. * Indicates that image processing needs to be re-calculated for all submeshes
  35389. */
  35390. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  35391. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  35392. };
  35393. /**
  35394. * Indicates that textures need to be re-calculated for all submeshes
  35395. */
  35396. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  35397. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  35398. };
  35399. /**
  35400. * Indicates that fresnel needs to be re-calculated for all submeshes
  35401. */
  35402. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  35403. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  35404. };
  35405. /**
  35406. * Indicates that fresnel and misc need to be re-calculated for all submeshes
  35407. */
  35408. Material.prototype._markAllSubMeshesAsFresnelAndMiscDirty = function () {
  35409. this._markAllSubMeshesAsDirty(function (defines) {
  35410. defines.markAsFresnelDirty();
  35411. defines.markAsMiscDirty();
  35412. });
  35413. };
  35414. /**
  35415. * Indicates that lights need to be re-calculated for all submeshes
  35416. */
  35417. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  35418. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  35419. };
  35420. /**
  35421. * Indicates that attributes need to be re-calculated for all submeshes
  35422. */
  35423. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  35424. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  35425. };
  35426. /**
  35427. * Indicates that misc needs to be re-calculated for all submeshes
  35428. */
  35429. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  35430. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  35431. };
  35432. /**
  35433. * Indicates that textures and misc need to be re-calculated for all submeshes
  35434. */
  35435. Material.prototype._markAllSubMeshesAsTexturesAndMiscDirty = function () {
  35436. this._markAllSubMeshesAsDirty(function (defines) {
  35437. defines.markAsTexturesDirty();
  35438. defines.markAsMiscDirty();
  35439. });
  35440. };
  35441. /**
  35442. * Disposes the material
  35443. * @param forceDisposeEffect specifies if effects should be forcefully disposed
  35444. * @param forceDisposeTextures specifies if textures should be forcefully disposed
  35445. */
  35446. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  35447. // Animations
  35448. this.getScene().stopAnimation(this);
  35449. this.getScene().freeProcessedMaterials();
  35450. // Remove from scene
  35451. var index = this._scene.materials.indexOf(this);
  35452. if (index >= 0) {
  35453. this._scene.materials.splice(index, 1);
  35454. }
  35455. // Remove from meshes
  35456. for (index = 0; index < this._scene.meshes.length; index++) {
  35457. var mesh = this._scene.meshes[index];
  35458. if (mesh.material === this) {
  35459. mesh.material = null;
  35460. if (mesh.geometry) {
  35461. var geometry = (mesh.geometry);
  35462. if (this.storeEffectOnSubMeshes) {
  35463. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  35464. var subMesh = _a[_i];
  35465. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  35466. if (forceDisposeEffect && subMesh._materialEffect) {
  35467. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  35468. }
  35469. }
  35470. }
  35471. else {
  35472. geometry._releaseVertexArrayObject(this._effect);
  35473. }
  35474. }
  35475. }
  35476. }
  35477. this._uniformBuffer.dispose();
  35478. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  35479. if (forceDisposeEffect && this._effect) {
  35480. if (!this.storeEffectOnSubMeshes) {
  35481. this._scene.getEngine()._releaseEffect(this._effect);
  35482. }
  35483. this._effect = null;
  35484. }
  35485. // Callback
  35486. this.onDisposeObservable.notifyObservers(this);
  35487. this.onDisposeObservable.clear();
  35488. if (this._onBindObservable) {
  35489. this._onBindObservable.clear();
  35490. }
  35491. if (this._onUnBindObservable) {
  35492. this._onUnBindObservable.clear();
  35493. }
  35494. };
  35495. /**
  35496. * Serializes this material
  35497. * @returns the serialized material object
  35498. */
  35499. Material.prototype.serialize = function () {
  35500. return BABYLON.SerializationHelper.Serialize(this);
  35501. };
  35502. /**
  35503. * Creates a MultiMaterial from parsed MultiMaterial data.
  35504. * @param parsedMultiMaterial defines parsed MultiMaterial data.
  35505. * @param scene defines the hosting scene
  35506. * @returns a new MultiMaterial
  35507. */
  35508. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  35509. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  35510. multiMaterial.id = parsedMultiMaterial.id;
  35511. if (BABYLON.Tags) {
  35512. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  35513. }
  35514. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  35515. var subMatId = parsedMultiMaterial.materials[matIndex];
  35516. if (subMatId) {
  35517. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  35518. }
  35519. else {
  35520. multiMaterial.subMaterials.push(null);
  35521. }
  35522. }
  35523. return multiMaterial;
  35524. };
  35525. /**
  35526. * Creates a material from parsed material data
  35527. * @param parsedMaterial defines parsed material data
  35528. * @param scene defines the hosting scene
  35529. * @param rootUrl defines the root URL to use to load textures
  35530. * @returns a new material
  35531. */
  35532. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  35533. if (!parsedMaterial.customType || parsedMaterial.customType === "BABYLON.StandardMaterial") {
  35534. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  35535. }
  35536. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  35537. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  35538. if (!BABYLON.LegacyPBRMaterial) {
  35539. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  35540. return;
  35541. }
  35542. }
  35543. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  35544. return materialType.Parse(parsedMaterial, scene, rootUrl);
  35545. };
  35546. // Triangle views
  35547. Material._TriangleFillMode = 0;
  35548. Material._WireFrameFillMode = 1;
  35549. Material._PointFillMode = 2;
  35550. // Draw modes
  35551. Material._PointListDrawMode = 3;
  35552. Material._LineListDrawMode = 4;
  35553. Material._LineLoopDrawMode = 5;
  35554. Material._LineStripDrawMode = 6;
  35555. Material._TriangleStripDrawMode = 7;
  35556. Material._TriangleFanDrawMode = 8;
  35557. /**
  35558. * Stores the clock-wise side orientation
  35559. */
  35560. Material._ClockWiseSideOrientation = 0;
  35561. /**
  35562. * Stores the counter clock-wise side orientation
  35563. */
  35564. Material._CounterClockWiseSideOrientation = 1;
  35565. /**
  35566. * The dirty texture flag value
  35567. */
  35568. Material.TextureDirtyFlag = 1;
  35569. /**
  35570. * The dirty light flag value
  35571. */
  35572. Material.LightDirtyFlag = 2;
  35573. /**
  35574. * The dirty fresnel flag value
  35575. */
  35576. Material.FresnelDirtyFlag = 4;
  35577. /**
  35578. * The dirty attribute flag value
  35579. */
  35580. Material.AttributesDirtyFlag = 8;
  35581. /**
  35582. * The dirty misc flag value
  35583. */
  35584. Material.MiscDirtyFlag = 16;
  35585. /**
  35586. * The all dirty flag value
  35587. */
  35588. Material.AllDirtyFlag = 31;
  35589. __decorate([
  35590. BABYLON.serialize()
  35591. ], Material.prototype, "id", void 0);
  35592. __decorate([
  35593. BABYLON.serialize()
  35594. ], Material.prototype, "uniqueId", void 0);
  35595. __decorate([
  35596. BABYLON.serialize()
  35597. ], Material.prototype, "name", void 0);
  35598. __decorate([
  35599. BABYLON.serialize()
  35600. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  35601. __decorate([
  35602. BABYLON.serialize()
  35603. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  35604. __decorate([
  35605. BABYLON.serialize()
  35606. ], Material.prototype, "state", void 0);
  35607. __decorate([
  35608. BABYLON.serialize("alpha")
  35609. ], Material.prototype, "_alpha", void 0);
  35610. __decorate([
  35611. BABYLON.serialize("backFaceCulling")
  35612. ], Material.prototype, "_backFaceCulling", void 0);
  35613. __decorate([
  35614. BABYLON.serialize()
  35615. ], Material.prototype, "sideOrientation", void 0);
  35616. __decorate([
  35617. BABYLON.serialize("alphaMode")
  35618. ], Material.prototype, "_alphaMode", void 0);
  35619. __decorate([
  35620. BABYLON.serialize()
  35621. ], Material.prototype, "_needDepthPrePass", void 0);
  35622. __decorate([
  35623. BABYLON.serialize()
  35624. ], Material.prototype, "disableDepthWrite", void 0);
  35625. __decorate([
  35626. BABYLON.serialize()
  35627. ], Material.prototype, "forceDepthWrite", void 0);
  35628. __decorate([
  35629. BABYLON.serialize()
  35630. ], Material.prototype, "separateCullingPass", void 0);
  35631. __decorate([
  35632. BABYLON.serialize("fogEnabled")
  35633. ], Material.prototype, "_fogEnabled", void 0);
  35634. __decorate([
  35635. BABYLON.serialize()
  35636. ], Material.prototype, "pointSize", void 0);
  35637. __decorate([
  35638. BABYLON.serialize()
  35639. ], Material.prototype, "zOffset", void 0);
  35640. __decorate([
  35641. BABYLON.serialize()
  35642. ], Material.prototype, "wireframe", null);
  35643. __decorate([
  35644. BABYLON.serialize()
  35645. ], Material.prototype, "pointsCloud", null);
  35646. __decorate([
  35647. BABYLON.serialize()
  35648. ], Material.prototype, "fillMode", null);
  35649. return Material;
  35650. }());
  35651. BABYLON.Material = Material;
  35652. })(BABYLON || (BABYLON = {}));
  35653. //# sourceMappingURL=babylon.material.js.map
  35654. var BABYLON;
  35655. (function (BABYLON) {
  35656. var UniformBuffer = /** @class */ (function () {
  35657. /**
  35658. * Uniform buffer objects.
  35659. *
  35660. * Handles blocks of uniform on the GPU.
  35661. *
  35662. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  35663. *
  35664. * For more information, please refer to :
  35665. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  35666. */
  35667. function UniformBuffer(engine, data, dynamic) {
  35668. this._engine = engine;
  35669. this._noUBO = !engine.supportsUniformBuffers;
  35670. this._dynamic = dynamic;
  35671. this._data = data || [];
  35672. this._uniformLocations = {};
  35673. this._uniformSizes = {};
  35674. this._uniformLocationPointer = 0;
  35675. this._needSync = false;
  35676. if (this._noUBO) {
  35677. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  35678. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  35679. this.updateFloat = this._updateFloatForEffect;
  35680. this.updateFloat2 = this._updateFloat2ForEffect;
  35681. this.updateFloat3 = this._updateFloat3ForEffect;
  35682. this.updateFloat4 = this._updateFloat4ForEffect;
  35683. this.updateMatrix = this._updateMatrixForEffect;
  35684. this.updateVector3 = this._updateVector3ForEffect;
  35685. this.updateVector4 = this._updateVector4ForEffect;
  35686. this.updateColor3 = this._updateColor3ForEffect;
  35687. this.updateColor4 = this._updateColor4ForEffect;
  35688. }
  35689. else {
  35690. this._engine._uniformBuffers.push(this);
  35691. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  35692. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  35693. this.updateFloat = this._updateFloatForUniform;
  35694. this.updateFloat2 = this._updateFloat2ForUniform;
  35695. this.updateFloat3 = this._updateFloat3ForUniform;
  35696. this.updateFloat4 = this._updateFloat4ForUniform;
  35697. this.updateMatrix = this._updateMatrixForUniform;
  35698. this.updateVector3 = this._updateVector3ForUniform;
  35699. this.updateVector4 = this._updateVector4ForUniform;
  35700. this.updateColor3 = this._updateColor3ForUniform;
  35701. this.updateColor4 = this._updateColor4ForUniform;
  35702. }
  35703. }
  35704. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  35705. // Properties
  35706. /**
  35707. * Indicates if the buffer is using the WebGL2 UBO implementation,
  35708. * or just falling back on setUniformXXX calls.
  35709. */
  35710. get: function () {
  35711. return !this._noUBO;
  35712. },
  35713. enumerable: true,
  35714. configurable: true
  35715. });
  35716. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  35717. /**
  35718. * Indicates if the WebGL underlying uniform buffer is in sync
  35719. * with the javascript cache data.
  35720. */
  35721. get: function () {
  35722. return !this._needSync;
  35723. },
  35724. enumerable: true,
  35725. configurable: true
  35726. });
  35727. /**
  35728. * Indicates if the WebGL underlying uniform buffer is dynamic.
  35729. * Also, a dynamic UniformBuffer will disable cache verification and always
  35730. * update the underlying WebGL uniform buffer to the GPU.
  35731. */
  35732. UniformBuffer.prototype.isDynamic = function () {
  35733. return this._dynamic !== undefined;
  35734. };
  35735. /**
  35736. * The data cache on JS side.
  35737. */
  35738. UniformBuffer.prototype.getData = function () {
  35739. return this._bufferData;
  35740. };
  35741. /**
  35742. * The underlying WebGL Uniform buffer.
  35743. */
  35744. UniformBuffer.prototype.getBuffer = function () {
  35745. return this._buffer;
  35746. };
  35747. /**
  35748. * std140 layout specifies how to align data within an UBO structure.
  35749. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  35750. * for specs.
  35751. */
  35752. UniformBuffer.prototype._fillAlignment = function (size) {
  35753. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  35754. // and 4x4 matrices
  35755. // TODO : change if other types are used
  35756. var alignment;
  35757. if (size <= 2) {
  35758. alignment = size;
  35759. }
  35760. else {
  35761. alignment = 4;
  35762. }
  35763. if ((this._uniformLocationPointer % alignment) !== 0) {
  35764. var oldPointer = this._uniformLocationPointer;
  35765. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  35766. var diff = this._uniformLocationPointer - oldPointer;
  35767. for (var i = 0; i < diff; i++) {
  35768. this._data.push(0);
  35769. }
  35770. }
  35771. };
  35772. /**
  35773. * Adds an uniform in the buffer.
  35774. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  35775. * for the layout to be correct !
  35776. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35777. * @param {number|number[]} size Data size, or data directly.
  35778. */
  35779. UniformBuffer.prototype.addUniform = function (name, size) {
  35780. if (this._noUBO) {
  35781. return;
  35782. }
  35783. if (this._uniformLocations[name] !== undefined) {
  35784. // Already existing uniform
  35785. return;
  35786. }
  35787. // This function must be called in the order of the shader layout !
  35788. // size can be the size of the uniform, or data directly
  35789. var data;
  35790. if (size instanceof Array) {
  35791. data = size;
  35792. size = data.length;
  35793. }
  35794. else {
  35795. size = size;
  35796. data = [];
  35797. // Fill with zeros
  35798. for (var i = 0; i < size; i++) {
  35799. data.push(0);
  35800. }
  35801. }
  35802. this._fillAlignment(size);
  35803. this._uniformSizes[name] = size;
  35804. this._uniformLocations[name] = this._uniformLocationPointer;
  35805. this._uniformLocationPointer += size;
  35806. for (var i = 0; i < size; i++) {
  35807. this._data.push(data[i]);
  35808. }
  35809. this._needSync = true;
  35810. };
  35811. /**
  35812. * Wrapper for addUniform.
  35813. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35814. * @param {Matrix} mat A 4x4 matrix.
  35815. */
  35816. UniformBuffer.prototype.addMatrix = function (name, mat) {
  35817. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  35818. };
  35819. /**
  35820. * Wrapper for addUniform.
  35821. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35822. * @param {number} x
  35823. * @param {number} y
  35824. */
  35825. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  35826. var temp = [x, y];
  35827. this.addUniform(name, temp);
  35828. };
  35829. /**
  35830. * Wrapper for addUniform.
  35831. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35832. * @param {number} x
  35833. * @param {number} y
  35834. * @param {number} z
  35835. */
  35836. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  35837. var temp = [x, y, z];
  35838. this.addUniform(name, temp);
  35839. };
  35840. /**
  35841. * Wrapper for addUniform.
  35842. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35843. * @param {Color3} color
  35844. */
  35845. UniformBuffer.prototype.addColor3 = function (name, color) {
  35846. var temp = new Array();
  35847. color.toArray(temp);
  35848. this.addUniform(name, temp);
  35849. };
  35850. /**
  35851. * Wrapper for addUniform.
  35852. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35853. * @param {Color3} color
  35854. * @param {number} alpha
  35855. */
  35856. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  35857. var temp = new Array();
  35858. color.toArray(temp);
  35859. temp.push(alpha);
  35860. this.addUniform(name, temp);
  35861. };
  35862. /**
  35863. * Wrapper for addUniform.
  35864. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35865. * @param {Vector3} vector
  35866. */
  35867. UniformBuffer.prototype.addVector3 = function (name, vector) {
  35868. var temp = new Array();
  35869. vector.toArray(temp);
  35870. this.addUniform(name, temp);
  35871. };
  35872. /**
  35873. * Wrapper for addUniform.
  35874. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35875. */
  35876. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  35877. this.addUniform(name, 12);
  35878. };
  35879. /**
  35880. * Wrapper for addUniform.
  35881. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35882. */
  35883. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  35884. this.addUniform(name, 8);
  35885. };
  35886. /**
  35887. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  35888. */
  35889. UniformBuffer.prototype.create = function () {
  35890. if (this._noUBO) {
  35891. return;
  35892. }
  35893. if (this._buffer) {
  35894. return; // nothing to do
  35895. }
  35896. // See spec, alignment must be filled as a vec4
  35897. this._fillAlignment(4);
  35898. this._bufferData = new Float32Array(this._data);
  35899. this._rebuild();
  35900. this._needSync = true;
  35901. };
  35902. /** @hidden */
  35903. UniformBuffer.prototype._rebuild = function () {
  35904. if (this._noUBO) {
  35905. return;
  35906. }
  35907. if (this._dynamic) {
  35908. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  35909. }
  35910. else {
  35911. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  35912. }
  35913. };
  35914. /**
  35915. * Updates the WebGL Uniform Buffer on the GPU.
  35916. * If the `dynamic` flag is set to true, no cache comparison is done.
  35917. * Otherwise, the buffer will be updated only if the cache differs.
  35918. */
  35919. UniformBuffer.prototype.update = function () {
  35920. if (!this._buffer) {
  35921. this.create();
  35922. return;
  35923. }
  35924. if (!this._dynamic && !this._needSync) {
  35925. return;
  35926. }
  35927. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  35928. this._needSync = false;
  35929. };
  35930. /**
  35931. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  35932. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  35933. * @param {number[]|Float32Array} data Flattened data
  35934. * @param {number} size Size of the data.
  35935. */
  35936. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  35937. var location = this._uniformLocations[uniformName];
  35938. if (location === undefined) {
  35939. if (this._buffer) {
  35940. // Cannot add an uniform if the buffer is already created
  35941. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  35942. return;
  35943. }
  35944. this.addUniform(uniformName, size);
  35945. location = this._uniformLocations[uniformName];
  35946. }
  35947. if (!this._buffer) {
  35948. this.create();
  35949. }
  35950. if (!this._dynamic) {
  35951. // Cache for static uniform buffers
  35952. var changed = false;
  35953. for (var i = 0; i < size; i++) {
  35954. if (this._bufferData[location + i] !== data[i]) {
  35955. changed = true;
  35956. this._bufferData[location + i] = data[i];
  35957. }
  35958. }
  35959. this._needSync = this._needSync || changed;
  35960. }
  35961. else {
  35962. // No cache for dynamic
  35963. for (var i = 0; i < size; i++) {
  35964. this._bufferData[location + i] = data[i];
  35965. }
  35966. }
  35967. };
  35968. // Update methods
  35969. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  35970. // To match std140, matrix must be realigned
  35971. for (var i = 0; i < 3; i++) {
  35972. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  35973. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  35974. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  35975. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  35976. }
  35977. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  35978. };
  35979. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  35980. this._currentEffect.setMatrix3x3(name, matrix);
  35981. };
  35982. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  35983. this._currentEffect.setMatrix2x2(name, matrix);
  35984. };
  35985. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  35986. // To match std140, matrix must be realigned
  35987. for (var i = 0; i < 2; i++) {
  35988. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  35989. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  35990. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  35991. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  35992. }
  35993. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  35994. };
  35995. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  35996. this._currentEffect.setFloat(name, x);
  35997. };
  35998. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  35999. UniformBuffer._tempBuffer[0] = x;
  36000. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  36001. };
  36002. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  36003. if (suffix === void 0) { suffix = ""; }
  36004. this._currentEffect.setFloat2(name + suffix, x, y);
  36005. };
  36006. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  36007. if (suffix === void 0) { suffix = ""; }
  36008. UniformBuffer._tempBuffer[0] = x;
  36009. UniformBuffer._tempBuffer[1] = y;
  36010. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  36011. };
  36012. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  36013. if (suffix === void 0) { suffix = ""; }
  36014. this._currentEffect.setFloat3(name + suffix, x, y, z);
  36015. };
  36016. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  36017. if (suffix === void 0) { suffix = ""; }
  36018. UniformBuffer._tempBuffer[0] = x;
  36019. UniformBuffer._tempBuffer[1] = y;
  36020. UniformBuffer._tempBuffer[2] = z;
  36021. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  36022. };
  36023. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  36024. if (suffix === void 0) { suffix = ""; }
  36025. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  36026. };
  36027. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  36028. if (suffix === void 0) { suffix = ""; }
  36029. UniformBuffer._tempBuffer[0] = x;
  36030. UniformBuffer._tempBuffer[1] = y;
  36031. UniformBuffer._tempBuffer[2] = z;
  36032. UniformBuffer._tempBuffer[3] = w;
  36033. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  36034. };
  36035. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  36036. this._currentEffect.setMatrix(name, mat);
  36037. };
  36038. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  36039. this.updateUniform(name, mat.toArray(), 16);
  36040. };
  36041. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  36042. this._currentEffect.setVector3(name, vector);
  36043. };
  36044. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  36045. vector.toArray(UniformBuffer._tempBuffer);
  36046. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  36047. };
  36048. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  36049. this._currentEffect.setVector4(name, vector);
  36050. };
  36051. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  36052. vector.toArray(UniformBuffer._tempBuffer);
  36053. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  36054. };
  36055. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  36056. if (suffix === void 0) { suffix = ""; }
  36057. this._currentEffect.setColor3(name + suffix, color);
  36058. };
  36059. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  36060. if (suffix === void 0) { suffix = ""; }
  36061. color.toArray(UniformBuffer._tempBuffer);
  36062. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  36063. };
  36064. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  36065. if (suffix === void 0) { suffix = ""; }
  36066. this._currentEffect.setColor4(name + suffix, color, alpha);
  36067. };
  36068. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  36069. if (suffix === void 0) { suffix = ""; }
  36070. color.toArray(UniformBuffer._tempBuffer);
  36071. UniformBuffer._tempBuffer[3] = alpha;
  36072. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  36073. };
  36074. /**
  36075. * Sets a sampler uniform on the effect.
  36076. * @param {string} name Name of the sampler.
  36077. * @param {Texture} texture
  36078. */
  36079. UniformBuffer.prototype.setTexture = function (name, texture) {
  36080. this._currentEffect.setTexture(name, texture);
  36081. };
  36082. /**
  36083. * Directly updates the value of the uniform in the cache AND on the GPU.
  36084. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  36085. * @param {number[]|Float32Array} data Flattened data
  36086. */
  36087. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  36088. this.updateUniform(uniformName, data, data.length);
  36089. this.update();
  36090. };
  36091. /**
  36092. * Binds this uniform buffer to an effect.
  36093. * @param {Effect} effect
  36094. * @param {string} name Name of the uniform block in the shader.
  36095. */
  36096. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  36097. this._currentEffect = effect;
  36098. if (this._noUBO || !this._buffer) {
  36099. return;
  36100. }
  36101. effect.bindUniformBuffer(this._buffer, name);
  36102. };
  36103. /**
  36104. * Disposes the uniform buffer.
  36105. */
  36106. UniformBuffer.prototype.dispose = function () {
  36107. if (this._noUBO) {
  36108. return;
  36109. }
  36110. var index = this._engine._uniformBuffers.indexOf(this);
  36111. if (index !== -1) {
  36112. this._engine._uniformBuffers.splice(index, 1);
  36113. }
  36114. if (!this._buffer) {
  36115. return;
  36116. }
  36117. if (this._engine._releaseBuffer(this._buffer)) {
  36118. this._buffer = null;
  36119. }
  36120. };
  36121. // Pool for avoiding memory leaks
  36122. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  36123. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  36124. return UniformBuffer;
  36125. }());
  36126. BABYLON.UniformBuffer = UniformBuffer;
  36127. })(BABYLON || (BABYLON = {}));
  36128. //# sourceMappingURL=babylon.uniformBuffer.js.map
  36129. var BABYLON;
  36130. (function (BABYLON) {
  36131. /**
  36132. * This class contains the various kinds of data on every vertex of a mesh used in determining its shape and appearance
  36133. */
  36134. var VertexData = /** @class */ (function () {
  36135. function VertexData() {
  36136. }
  36137. /**
  36138. * Uses the passed data array to set the set the values for the specified kind of data
  36139. * @param data a linear array of floating numbers
  36140. * @param kind the type of data that is being set, eg positions, colors etc
  36141. */
  36142. VertexData.prototype.set = function (data, kind) {
  36143. switch (kind) {
  36144. case BABYLON.VertexBuffer.PositionKind:
  36145. this.positions = data;
  36146. break;
  36147. case BABYLON.VertexBuffer.NormalKind:
  36148. this.normals = data;
  36149. break;
  36150. case BABYLON.VertexBuffer.TangentKind:
  36151. this.tangents = data;
  36152. break;
  36153. case BABYLON.VertexBuffer.UVKind:
  36154. this.uvs = data;
  36155. break;
  36156. case BABYLON.VertexBuffer.UV2Kind:
  36157. this.uvs2 = data;
  36158. break;
  36159. case BABYLON.VertexBuffer.UV3Kind:
  36160. this.uvs3 = data;
  36161. break;
  36162. case BABYLON.VertexBuffer.UV4Kind:
  36163. this.uvs4 = data;
  36164. break;
  36165. case BABYLON.VertexBuffer.UV5Kind:
  36166. this.uvs5 = data;
  36167. break;
  36168. case BABYLON.VertexBuffer.UV6Kind:
  36169. this.uvs6 = data;
  36170. break;
  36171. case BABYLON.VertexBuffer.ColorKind:
  36172. this.colors = data;
  36173. break;
  36174. case BABYLON.VertexBuffer.MatricesIndicesKind:
  36175. this.matricesIndices = data;
  36176. break;
  36177. case BABYLON.VertexBuffer.MatricesWeightsKind:
  36178. this.matricesWeights = data;
  36179. break;
  36180. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  36181. this.matricesIndicesExtra = data;
  36182. break;
  36183. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  36184. this.matricesWeightsExtra = data;
  36185. break;
  36186. }
  36187. };
  36188. /**
  36189. * Associates the vertexData to the passed Mesh.
  36190. * Sets it as updatable or not (default `false`)
  36191. * @param mesh the mesh the vertexData is applied to
  36192. * @param updatable when used and having the value true allows new data to update the vertexData
  36193. * @returns the VertexData
  36194. */
  36195. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  36196. this._applyTo(mesh, updatable);
  36197. return this;
  36198. };
  36199. /**
  36200. * Associates the vertexData to the passed Geometry.
  36201. * Sets it as updatable or not (default `false`)
  36202. * @param geometry the geometry the vertexData is applied to
  36203. * @param updatable when used and having the value true allows new data to update the vertexData
  36204. * @returns VertexData
  36205. */
  36206. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  36207. this._applyTo(geometry, updatable);
  36208. return this;
  36209. };
  36210. /**
  36211. * Updates the associated mesh
  36212. * @param mesh the mesh to be updated
  36213. * @param updateExtends when true the mesh BoundingInfo will be renewed when and if position kind is updated, optional with default false
  36214. * @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
  36215. * @returns VertexData
  36216. */
  36217. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  36218. this._update(mesh);
  36219. return this;
  36220. };
  36221. /**
  36222. * Updates the associated geometry
  36223. * @param geometry the geometry to be updated
  36224. * @param updateExtends when true BoundingInfo will be renewed when and if position kind is updated, optional with default false
  36225. * @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
  36226. * @returns VertexData.
  36227. */
  36228. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  36229. this._update(geometry);
  36230. return this;
  36231. };
  36232. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  36233. if (updatable === void 0) { updatable = false; }
  36234. if (this.positions) {
  36235. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  36236. }
  36237. if (this.normals) {
  36238. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  36239. }
  36240. if (this.tangents) {
  36241. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  36242. }
  36243. if (this.uvs) {
  36244. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  36245. }
  36246. if (this.uvs2) {
  36247. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  36248. }
  36249. if (this.uvs3) {
  36250. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  36251. }
  36252. if (this.uvs4) {
  36253. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  36254. }
  36255. if (this.uvs5) {
  36256. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  36257. }
  36258. if (this.uvs6) {
  36259. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  36260. }
  36261. if (this.colors) {
  36262. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  36263. }
  36264. if (this.matricesIndices) {
  36265. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  36266. }
  36267. if (this.matricesWeights) {
  36268. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  36269. }
  36270. if (this.matricesIndicesExtra) {
  36271. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  36272. }
  36273. if (this.matricesWeightsExtra) {
  36274. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  36275. }
  36276. if (this.indices) {
  36277. meshOrGeometry.setIndices(this.indices, null, updatable);
  36278. }
  36279. else {
  36280. meshOrGeometry.setIndices([], null);
  36281. }
  36282. return this;
  36283. };
  36284. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  36285. if (this.positions) {
  36286. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  36287. }
  36288. if (this.normals) {
  36289. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  36290. }
  36291. if (this.tangents) {
  36292. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  36293. }
  36294. if (this.uvs) {
  36295. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  36296. }
  36297. if (this.uvs2) {
  36298. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  36299. }
  36300. if (this.uvs3) {
  36301. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  36302. }
  36303. if (this.uvs4) {
  36304. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  36305. }
  36306. if (this.uvs5) {
  36307. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  36308. }
  36309. if (this.uvs6) {
  36310. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  36311. }
  36312. if (this.colors) {
  36313. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  36314. }
  36315. if (this.matricesIndices) {
  36316. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  36317. }
  36318. if (this.matricesWeights) {
  36319. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  36320. }
  36321. if (this.matricesIndicesExtra) {
  36322. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  36323. }
  36324. if (this.matricesWeightsExtra) {
  36325. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  36326. }
  36327. if (this.indices) {
  36328. meshOrGeometry.setIndices(this.indices, null);
  36329. }
  36330. return this;
  36331. };
  36332. /**
  36333. * Transforms each position and each normal of the vertexData according to the passed Matrix
  36334. * @param matrix the transforming matrix
  36335. * @returns the VertexData
  36336. */
  36337. VertexData.prototype.transform = function (matrix) {
  36338. var flip = matrix.m[0] * matrix.m[5] * matrix.m[10] < 0;
  36339. var transformed = BABYLON.Vector3.Zero();
  36340. var index;
  36341. if (this.positions) {
  36342. var position = BABYLON.Vector3.Zero();
  36343. for (index = 0; index < this.positions.length; index += 3) {
  36344. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  36345. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  36346. this.positions[index] = transformed.x;
  36347. this.positions[index + 1] = transformed.y;
  36348. this.positions[index + 2] = transformed.z;
  36349. }
  36350. }
  36351. if (this.normals) {
  36352. var normal = BABYLON.Vector3.Zero();
  36353. for (index = 0; index < this.normals.length; index += 3) {
  36354. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  36355. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  36356. this.normals[index] = transformed.x;
  36357. this.normals[index + 1] = transformed.y;
  36358. this.normals[index + 2] = transformed.z;
  36359. }
  36360. }
  36361. if (this.tangents) {
  36362. var tangent = BABYLON.Vector4.Zero();
  36363. var tangentTransformed = BABYLON.Vector4.Zero();
  36364. for (index = 0; index < this.tangents.length; index += 4) {
  36365. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  36366. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  36367. this.tangents[index] = tangentTransformed.x;
  36368. this.tangents[index + 1] = tangentTransformed.y;
  36369. this.tangents[index + 2] = tangentTransformed.z;
  36370. this.tangents[index + 3] = tangentTransformed.w;
  36371. }
  36372. }
  36373. if (flip && this.indices) {
  36374. for (index = 0; index < this.indices.length; index += 3) {
  36375. var tmp = this.indices[index + 1];
  36376. this.indices[index + 1] = this.indices[index + 2];
  36377. this.indices[index + 2] = tmp;
  36378. }
  36379. }
  36380. return this;
  36381. };
  36382. /**
  36383. * Merges the passed VertexData into the current one
  36384. * @param other the VertexData to be merged into the current one
  36385. * @param use32BitsIndices defines a boolean indicating if indices must be store in a 32 bits array
  36386. * @returns the modified VertexData
  36387. */
  36388. VertexData.prototype.merge = function (other, use32BitsIndices) {
  36389. if (use32BitsIndices === void 0) { use32BitsIndices = false; }
  36390. this._validate();
  36391. other._validate();
  36392. if (!this.normals !== !other.normals ||
  36393. !this.tangents !== !other.tangents ||
  36394. !this.uvs !== !other.uvs ||
  36395. !this.uvs2 !== !other.uvs2 ||
  36396. !this.uvs3 !== !other.uvs3 ||
  36397. !this.uvs4 !== !other.uvs4 ||
  36398. !this.uvs5 !== !other.uvs5 ||
  36399. !this.uvs6 !== !other.uvs6 ||
  36400. !this.colors !== !other.colors ||
  36401. !this.matricesIndices !== !other.matricesIndices ||
  36402. !this.matricesWeights !== !other.matricesWeights ||
  36403. !this.matricesIndicesExtra !== !other.matricesIndicesExtra ||
  36404. !this.matricesWeightsExtra !== !other.matricesWeightsExtra) {
  36405. throw new Error("Cannot merge vertex data that do not have the same set of attributes");
  36406. }
  36407. if (other.indices) {
  36408. if (!this.indices) {
  36409. this.indices = [];
  36410. }
  36411. var offset = this.positions ? this.positions.length / 3 : 0;
  36412. var isSrcTypedArray = this.indices.BYTES_PER_ELEMENT !== undefined;
  36413. if (isSrcTypedArray) {
  36414. var len = this.indices.length + other.indices.length;
  36415. var temp = use32BitsIndices || this.indices instanceof Uint32Array ? new Uint32Array(len) : new Uint16Array(len);
  36416. temp.set(this.indices);
  36417. var decal = this.indices.length;
  36418. for (var index = 0; index < other.indices.length; index++) {
  36419. temp[decal + index] = other.indices[index] + offset;
  36420. }
  36421. this.indices = temp;
  36422. }
  36423. else {
  36424. for (var index = 0; index < other.indices.length; index++) {
  36425. this.indices.push(other.indices[index] + offset);
  36426. }
  36427. }
  36428. }
  36429. this.positions = this._mergeElement(this.positions, other.positions);
  36430. this.normals = this._mergeElement(this.normals, other.normals);
  36431. this.tangents = this._mergeElement(this.tangents, other.tangents);
  36432. this.uvs = this._mergeElement(this.uvs, other.uvs);
  36433. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  36434. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  36435. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  36436. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  36437. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  36438. this.colors = this._mergeElement(this.colors, other.colors);
  36439. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  36440. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  36441. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  36442. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  36443. return this;
  36444. };
  36445. VertexData.prototype._mergeElement = function (source, other) {
  36446. if (!source) {
  36447. return other;
  36448. }
  36449. if (!other) {
  36450. return source;
  36451. }
  36452. var len = other.length + source.length;
  36453. var isSrcTypedArray = source instanceof Float32Array;
  36454. var isOthTypedArray = other instanceof Float32Array;
  36455. // use non-loop method when the source is Float32Array
  36456. if (isSrcTypedArray) {
  36457. var ret32 = new Float32Array(len);
  36458. ret32.set(source);
  36459. ret32.set(other, source.length);
  36460. return ret32;
  36461. // source is number[], when other is also use concat
  36462. }
  36463. else if (!isOthTypedArray) {
  36464. return source.concat(other);
  36465. // source is a number[], but other is a Float32Array, loop required
  36466. }
  36467. else {
  36468. var ret = source.slice(0); // copy source to a separate array
  36469. for (var i = 0, len = other.length; i < len; i++) {
  36470. ret.push(other[i]);
  36471. }
  36472. return ret;
  36473. }
  36474. };
  36475. VertexData.prototype._validate = function () {
  36476. if (!this.positions) {
  36477. throw new Error("Positions are required");
  36478. }
  36479. var getElementCount = function (kind, values) {
  36480. var stride = BABYLON.VertexBuffer.DeduceStride(kind);
  36481. if ((values.length % stride) !== 0) {
  36482. throw new Error("The " + kind + "s array count must be a multiple of " + stride);
  36483. }
  36484. return values.length / stride;
  36485. };
  36486. var positionsElementCount = getElementCount(BABYLON.VertexBuffer.PositionKind, this.positions);
  36487. var validateElementCount = function (kind, values) {
  36488. var elementCount = getElementCount(kind, values);
  36489. if (elementCount !== positionsElementCount) {
  36490. throw new Error("The " + kind + "s element count (" + elementCount + ") does not match the positions count (" + positionsElementCount + ")");
  36491. }
  36492. };
  36493. if (this.normals)
  36494. validateElementCount(BABYLON.VertexBuffer.NormalKind, this.normals);
  36495. if (this.tangents)
  36496. validateElementCount(BABYLON.VertexBuffer.TangentKind, this.tangents);
  36497. if (this.uvs)
  36498. validateElementCount(BABYLON.VertexBuffer.UVKind, this.uvs);
  36499. if (this.uvs2)
  36500. validateElementCount(BABYLON.VertexBuffer.UV2Kind, this.uvs2);
  36501. if (this.uvs3)
  36502. validateElementCount(BABYLON.VertexBuffer.UV3Kind, this.uvs3);
  36503. if (this.uvs4)
  36504. validateElementCount(BABYLON.VertexBuffer.UV4Kind, this.uvs4);
  36505. if (this.uvs5)
  36506. validateElementCount(BABYLON.VertexBuffer.UV5Kind, this.uvs5);
  36507. if (this.uvs6)
  36508. validateElementCount(BABYLON.VertexBuffer.UV6Kind, this.uvs6);
  36509. if (this.colors)
  36510. validateElementCount(BABYLON.VertexBuffer.ColorKind, this.colors);
  36511. if (this.matricesIndices)
  36512. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices);
  36513. if (this.matricesWeights)
  36514. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights);
  36515. if (this.matricesIndicesExtra)
  36516. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra);
  36517. if (this.matricesWeightsExtra)
  36518. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra);
  36519. };
  36520. /**
  36521. * Serializes the VertexData
  36522. * @returns a serialized object
  36523. */
  36524. VertexData.prototype.serialize = function () {
  36525. var serializationObject = this.serialize();
  36526. if (this.positions) {
  36527. serializationObject.positions = this.positions;
  36528. }
  36529. if (this.normals) {
  36530. serializationObject.normals = this.normals;
  36531. }
  36532. if (this.tangents) {
  36533. serializationObject.tangents = this.tangents;
  36534. }
  36535. if (this.uvs) {
  36536. serializationObject.uvs = this.uvs;
  36537. }
  36538. if (this.uvs2) {
  36539. serializationObject.uvs2 = this.uvs2;
  36540. }
  36541. if (this.uvs3) {
  36542. serializationObject.uvs3 = this.uvs3;
  36543. }
  36544. if (this.uvs4) {
  36545. serializationObject.uvs4 = this.uvs4;
  36546. }
  36547. if (this.uvs5) {
  36548. serializationObject.uvs5 = this.uvs5;
  36549. }
  36550. if (this.uvs6) {
  36551. serializationObject.uvs6 = this.uvs6;
  36552. }
  36553. if (this.colors) {
  36554. serializationObject.colors = this.colors;
  36555. }
  36556. if (this.matricesIndices) {
  36557. serializationObject.matricesIndices = this.matricesIndices;
  36558. serializationObject.matricesIndices._isExpanded = true;
  36559. }
  36560. if (this.matricesWeights) {
  36561. serializationObject.matricesWeights = this.matricesWeights;
  36562. }
  36563. if (this.matricesIndicesExtra) {
  36564. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  36565. serializationObject.matricesIndicesExtra._isExpanded = true;
  36566. }
  36567. if (this.matricesWeightsExtra) {
  36568. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  36569. }
  36570. serializationObject.indices = this.indices;
  36571. return serializationObject;
  36572. };
  36573. // Statics
  36574. /**
  36575. * Extracts the vertexData from a mesh
  36576. * @param mesh the mesh from which to extract the VertexData
  36577. * @param copyWhenShared defines if the VertexData must be cloned when shared between multiple meshes, optional, default false
  36578. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  36579. * @returns the object VertexData associated to the passed mesh
  36580. */
  36581. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  36582. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  36583. };
  36584. /**
  36585. * Extracts the vertexData from the geometry
  36586. * @param geometry the geometry from which to extract the VertexData
  36587. * @param copyWhenShared defines if the VertexData must be cloned when the geometrty is shared between multiple meshes, optional, default false
  36588. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  36589. * @returns the object VertexData associated to the passed mesh
  36590. */
  36591. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  36592. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  36593. };
  36594. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  36595. var result = new VertexData();
  36596. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  36597. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  36598. }
  36599. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  36600. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  36601. }
  36602. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  36603. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  36604. }
  36605. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  36606. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  36607. }
  36608. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  36609. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  36610. }
  36611. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  36612. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  36613. }
  36614. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  36615. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  36616. }
  36617. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  36618. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  36619. }
  36620. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  36621. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  36622. }
  36623. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  36624. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  36625. }
  36626. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  36627. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  36628. }
  36629. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  36630. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  36631. }
  36632. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  36633. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  36634. }
  36635. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  36636. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  36637. }
  36638. result.indices = meshOrGeometry.getIndices(copyWhenShared, forceCopy);
  36639. return result;
  36640. };
  36641. /**
  36642. * Creates the VertexData for a Ribbon
  36643. * @param options an object used to set the following optional parameters for the ribbon, required but can be empty
  36644. * * pathArray array of paths, each of which an array of successive Vector3
  36645. * * closeArray creates a seam between the first and the last paths of the pathArray, optional, default false
  36646. * * closePath creates a seam between the first and the last points of each path of the path array, optional, default false
  36647. * * 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
  36648. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36649. * * 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)
  36650. * * 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)
  36651. * * invertUV swaps in the U and V coordinates when applying a texture, optional, default false
  36652. * * uvs a linear array, of length 2 * number of vertices, of custom UV values, optional
  36653. * * colors a linear array, of length 4 * number of vertices, of custom color values, optional
  36654. * @returns the VertexData of the ribbon
  36655. */
  36656. VertexData.CreateRibbon = function (options) {
  36657. var pathArray = options.pathArray;
  36658. var closeArray = options.closeArray || false;
  36659. var closePath = options.closePath || false;
  36660. var invertUV = options.invertUV || false;
  36661. var defaultOffset = Math.floor(pathArray[0].length / 2);
  36662. var offset = options.offset || defaultOffset;
  36663. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  36664. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36665. var customUV = options.uvs;
  36666. var customColors = options.colors;
  36667. var positions = [];
  36668. var indices = [];
  36669. var normals = [];
  36670. var uvs = [];
  36671. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  36672. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  36673. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  36674. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  36675. var minlg; // minimal length among all paths from pathArray
  36676. var lg = []; // array of path lengths : nb of vertex per path
  36677. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  36678. var p; // path iterator
  36679. var i; // point iterator
  36680. var j; // point iterator
  36681. // if single path in pathArray
  36682. if (pathArray.length < 2) {
  36683. var ar1 = [];
  36684. var ar2 = [];
  36685. for (i = 0; i < pathArray[0].length - offset; i++) {
  36686. ar1.push(pathArray[0][i]);
  36687. ar2.push(pathArray[0][i + offset]);
  36688. }
  36689. pathArray = [ar1, ar2];
  36690. }
  36691. // positions and horizontal distances (u)
  36692. var idc = 0;
  36693. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  36694. var path;
  36695. var l;
  36696. minlg = pathArray[0].length;
  36697. var vectlg;
  36698. var dist;
  36699. for (p = 0; p < pathArray.length; p++) {
  36700. uTotalDistance[p] = 0;
  36701. us[p] = [0];
  36702. path = pathArray[p];
  36703. l = path.length;
  36704. minlg = (minlg < l) ? minlg : l;
  36705. j = 0;
  36706. while (j < l) {
  36707. positions.push(path[j].x, path[j].y, path[j].z);
  36708. if (j > 0) {
  36709. vectlg = path[j].subtract(path[j - 1]).length();
  36710. dist = vectlg + uTotalDistance[p];
  36711. us[p].push(dist);
  36712. uTotalDistance[p] = dist;
  36713. }
  36714. j++;
  36715. }
  36716. if (closePath) { // an extra hidden vertex is added in the "positions" array
  36717. j--;
  36718. positions.push(path[0].x, path[0].y, path[0].z);
  36719. vectlg = path[j].subtract(path[0]).length();
  36720. dist = vectlg + uTotalDistance[p];
  36721. us[p].push(dist);
  36722. uTotalDistance[p] = dist;
  36723. }
  36724. lg[p] = l + closePathCorr;
  36725. idx[p] = idc;
  36726. idc += (l + closePathCorr);
  36727. }
  36728. // vertical distances (v)
  36729. var path1;
  36730. var path2;
  36731. var vertex1 = null;
  36732. var vertex2 = null;
  36733. for (i = 0; i < minlg + closePathCorr; i++) {
  36734. vTotalDistance[i] = 0;
  36735. vs[i] = [0];
  36736. for (p = 0; p < pathArray.length - 1; p++) {
  36737. path1 = pathArray[p];
  36738. path2 = pathArray[p + 1];
  36739. if (i === minlg) { // closePath
  36740. vertex1 = path1[0];
  36741. vertex2 = path2[0];
  36742. }
  36743. else {
  36744. vertex1 = path1[i];
  36745. vertex2 = path2[i];
  36746. }
  36747. vectlg = vertex2.subtract(vertex1).length();
  36748. dist = vectlg + vTotalDistance[i];
  36749. vs[i].push(dist);
  36750. vTotalDistance[i] = dist;
  36751. }
  36752. if (closeArray && vertex2 && vertex1) {
  36753. path1 = pathArray[p];
  36754. path2 = pathArray[0];
  36755. if (i === minlg) { // closePath
  36756. vertex2 = path2[0];
  36757. }
  36758. vectlg = vertex2.subtract(vertex1).length();
  36759. dist = vectlg + vTotalDistance[i];
  36760. vTotalDistance[i] = dist;
  36761. }
  36762. }
  36763. // uvs
  36764. var u;
  36765. var v;
  36766. if (customUV) {
  36767. for (p = 0; p < customUV.length; p++) {
  36768. uvs.push(customUV[p].x, customUV[p].y);
  36769. }
  36770. }
  36771. else {
  36772. for (p = 0; p < pathArray.length; p++) {
  36773. for (i = 0; i < minlg + closePathCorr; i++) {
  36774. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  36775. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  36776. if (invertUV) {
  36777. uvs.push(v, u);
  36778. }
  36779. else {
  36780. uvs.push(u, v);
  36781. }
  36782. }
  36783. }
  36784. }
  36785. // indices
  36786. p = 0; // path index
  36787. var pi = 0; // positions array index
  36788. var l1 = lg[p] - 1; // path1 length
  36789. var l2 = lg[p + 1] - 1; // path2 length
  36790. var min = (l1 < l2) ? l1 : l2; // current path stop index
  36791. var shft = idx[1] - idx[0]; // shift
  36792. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  36793. while (pi <= min && p < path1nb) { // stay under min and don't go over next to last path
  36794. // 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
  36795. indices.push(pi, pi + shft, pi + 1);
  36796. indices.push(pi + shft + 1, pi + 1, pi + shft);
  36797. pi += 1;
  36798. if (pi === min) { // if end of one of two consecutive paths reached, go to next existing path
  36799. p++;
  36800. if (p === lg.length - 1) { // last path of pathArray reached <=> closeArray == true
  36801. shft = idx[0] - idx[p];
  36802. l1 = lg[p] - 1;
  36803. l2 = lg[0] - 1;
  36804. }
  36805. else {
  36806. shft = idx[p + 1] - idx[p];
  36807. l1 = lg[p] - 1;
  36808. l2 = lg[p + 1] - 1;
  36809. }
  36810. pi = idx[p];
  36811. min = (l1 < l2) ? l1 + pi : l2 + pi;
  36812. }
  36813. }
  36814. // normals
  36815. VertexData.ComputeNormals(positions, indices, normals);
  36816. if (closePath) { // update both the first and last vertex normals to their average value
  36817. var indexFirst = 0;
  36818. var indexLast = 0;
  36819. for (p = 0; p < pathArray.length; p++) {
  36820. indexFirst = idx[p] * 3;
  36821. if (p + 1 < pathArray.length) {
  36822. indexLast = (idx[p + 1] - 1) * 3;
  36823. }
  36824. else {
  36825. indexLast = normals.length - 3;
  36826. }
  36827. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  36828. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  36829. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  36830. normals[indexLast] = normals[indexFirst];
  36831. normals[indexLast + 1] = normals[indexFirst + 1];
  36832. normals[indexLast + 2] = normals[indexFirst + 2];
  36833. }
  36834. }
  36835. // sides
  36836. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  36837. // Colors
  36838. var colors = null;
  36839. if (customColors) {
  36840. colors = new Float32Array(customColors.length * 4);
  36841. for (var c = 0; c < customColors.length; c++) {
  36842. colors[c * 4] = customColors[c].r;
  36843. colors[c * 4 + 1] = customColors[c].g;
  36844. colors[c * 4 + 2] = customColors[c].b;
  36845. colors[c * 4 + 3] = customColors[c].a;
  36846. }
  36847. }
  36848. // Result
  36849. var vertexData = new VertexData();
  36850. var positions32 = new Float32Array(positions);
  36851. var normals32 = new Float32Array(normals);
  36852. var uvs32 = new Float32Array(uvs);
  36853. vertexData.indices = indices;
  36854. vertexData.positions = positions32;
  36855. vertexData.normals = normals32;
  36856. vertexData.uvs = uvs32;
  36857. if (colors) {
  36858. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  36859. }
  36860. if (closePath) {
  36861. vertexData._idx = idx;
  36862. }
  36863. return vertexData;
  36864. };
  36865. /**
  36866. * Creates the VertexData for a box
  36867. * @param options an object used to set the following optional parameters for the box, required but can be empty
  36868. * * size sets the width, height and depth of the box to the value of size, optional default 1
  36869. * * width sets the width (x direction) of the box, overwrites the width set by size, optional, default size
  36870. * * height sets the height (y direction) of the box, overwrites the height set by size, optional, default size
  36871. * * depth sets the depth (z direction) of the box, overwrites the depth set by size, optional, default size
  36872. * * faceUV an array of 6 Vector4 elements used to set different images to each box side
  36873. * * faceColors an array of 6 Color3 elements used to set different colors to each box side
  36874. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36875. * * 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)
  36876. * * 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)
  36877. * @returns the VertexData of the box
  36878. */
  36879. VertexData.CreateBox = function (options) {
  36880. var normalsSource = [
  36881. new BABYLON.Vector3(0, 0, 1),
  36882. new BABYLON.Vector3(0, 0, -1),
  36883. new BABYLON.Vector3(1, 0, 0),
  36884. new BABYLON.Vector3(-1, 0, 0),
  36885. new BABYLON.Vector3(0, 1, 0),
  36886. new BABYLON.Vector3(0, -1, 0)
  36887. ];
  36888. var indices = [];
  36889. var positions = [];
  36890. var normals = [];
  36891. var uvs = [];
  36892. var width = options.width || options.size || 1;
  36893. var height = options.height || options.size || 1;
  36894. var depth = options.depth || options.size || 1;
  36895. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36896. var faceUV = options.faceUV || new Array(6);
  36897. var faceColors = options.faceColors;
  36898. var colors = [];
  36899. // default face colors and UV if undefined
  36900. for (var f = 0; f < 6; f++) {
  36901. if (faceUV[f] === undefined) {
  36902. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  36903. }
  36904. if (faceColors && faceColors[f] === undefined) {
  36905. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  36906. }
  36907. }
  36908. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  36909. // Create each face in turn.
  36910. for (var index = 0; index < normalsSource.length; index++) {
  36911. var normal = normalsSource[index];
  36912. // Get two vectors perpendicular to the face normal and to each other.
  36913. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  36914. var side2 = BABYLON.Vector3.Cross(normal, side1);
  36915. // Six indices (two triangles) per face.
  36916. var verticesLength = positions.length / 3;
  36917. indices.push(verticesLength);
  36918. indices.push(verticesLength + 1);
  36919. indices.push(verticesLength + 2);
  36920. indices.push(verticesLength);
  36921. indices.push(verticesLength + 2);
  36922. indices.push(verticesLength + 3);
  36923. // Four vertices per face.
  36924. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  36925. positions.push(vertex.x, vertex.y, vertex.z);
  36926. normals.push(normal.x, normal.y, normal.z);
  36927. uvs.push(faceUV[index].z, faceUV[index].w);
  36928. if (faceColors) {
  36929. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  36930. }
  36931. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  36932. positions.push(vertex.x, vertex.y, vertex.z);
  36933. normals.push(normal.x, normal.y, normal.z);
  36934. uvs.push(faceUV[index].x, faceUV[index].w);
  36935. if (faceColors) {
  36936. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  36937. }
  36938. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  36939. positions.push(vertex.x, vertex.y, vertex.z);
  36940. normals.push(normal.x, normal.y, normal.z);
  36941. uvs.push(faceUV[index].x, faceUV[index].y);
  36942. if (faceColors) {
  36943. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  36944. }
  36945. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  36946. positions.push(vertex.x, vertex.y, vertex.z);
  36947. normals.push(normal.x, normal.y, normal.z);
  36948. uvs.push(faceUV[index].z, faceUV[index].y);
  36949. if (faceColors) {
  36950. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  36951. }
  36952. }
  36953. // sides
  36954. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  36955. // Result
  36956. var vertexData = new VertexData();
  36957. vertexData.indices = indices;
  36958. vertexData.positions = positions;
  36959. vertexData.normals = normals;
  36960. vertexData.uvs = uvs;
  36961. if (faceColors) {
  36962. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  36963. vertexData.colors = totalColors;
  36964. }
  36965. return vertexData;
  36966. };
  36967. /**
  36968. * Creates the VertexData for an ellipsoid, defaults to a sphere
  36969. * @param options an object used to set the following optional parameters for the box, required but can be empty
  36970. * * segments sets the number of horizontal strips optional, default 32
  36971. * * diameter sets the axes dimensions, diameterX, diameterY and diameterZ to the value of diameter, optional default 1
  36972. * * diameterX sets the diameterX (x direction) of the ellipsoid, overwrites the diameterX set by diameter, optional, default diameter
  36973. * * diameterY sets the diameterY (y direction) of the ellipsoid, overwrites the diameterY set by diameter, optional, default diameter
  36974. * * diameterZ sets the diameterZ (z direction) of the ellipsoid, overwrites the diameterZ set by diameter, optional, default diameter
  36975. * * 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
  36976. * * 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
  36977. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36978. * * 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)
  36979. * * 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)
  36980. * @returns the VertexData of the ellipsoid
  36981. */
  36982. VertexData.CreateSphere = function (options) {
  36983. var segments = options.segments || 32;
  36984. var diameterX = options.diameterX || options.diameter || 1;
  36985. var diameterY = options.diameterY || options.diameter || 1;
  36986. var diameterZ = options.diameterZ || options.diameter || 1;
  36987. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  36988. var slice = options.slice && (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  36989. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36990. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  36991. var totalZRotationSteps = 2 + segments;
  36992. var totalYRotationSteps = 2 * totalZRotationSteps;
  36993. var indices = [];
  36994. var positions = [];
  36995. var normals = [];
  36996. var uvs = [];
  36997. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  36998. var normalizedZ = zRotationStep / totalZRotationSteps;
  36999. var angleZ = normalizedZ * Math.PI * slice;
  37000. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  37001. var normalizedY = yRotationStep / totalYRotationSteps;
  37002. var angleY = normalizedY * Math.PI * 2 * arc;
  37003. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  37004. var rotationY = BABYLON.Matrix.RotationY(angleY);
  37005. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  37006. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  37007. var vertex = complete.multiply(radius);
  37008. var normal = complete.divide(radius).normalize();
  37009. positions.push(vertex.x, vertex.y, vertex.z);
  37010. normals.push(normal.x, normal.y, normal.z);
  37011. uvs.push(normalizedY, normalizedZ);
  37012. }
  37013. if (zRotationStep > 0) {
  37014. var verticesCount = positions.length / 3;
  37015. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  37016. indices.push((firstIndex));
  37017. indices.push((firstIndex + 1));
  37018. indices.push(firstIndex + totalYRotationSteps + 1);
  37019. indices.push((firstIndex + totalYRotationSteps + 1));
  37020. indices.push((firstIndex + 1));
  37021. indices.push((firstIndex + totalYRotationSteps + 2));
  37022. }
  37023. }
  37024. }
  37025. // Sides
  37026. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37027. // Result
  37028. var vertexData = new VertexData();
  37029. vertexData.indices = indices;
  37030. vertexData.positions = positions;
  37031. vertexData.normals = normals;
  37032. vertexData.uvs = uvs;
  37033. return vertexData;
  37034. };
  37035. /**
  37036. * Creates the VertexData for a cylinder, cone or prism
  37037. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37038. * * height sets the height (y direction) of the cylinder, optional, default 2
  37039. * * diameterTop sets the diameter of the top of the cone, overwrites diameter, optional, default diameter
  37040. * * diameterBottom sets the diameter of the bottom of the cone, overwrites diameter, optional, default diameter
  37041. * * diameter sets the diameter of the top and bottom of the cone, optional default 1
  37042. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  37043. * * subdivisions` the number of rings along the cylinder height, optional, default 1
  37044. * * 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
  37045. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  37046. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  37047. * * hasRings when true makes each subdivision independantly treated as a face for faceUV and faceColors, optional, default false
  37048. * * enclose when true closes an open cylinder by adding extra flat faces between the height axis and vertical edges, think cut cake
  37049. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37050. * * 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)
  37051. * * 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)
  37052. * @returns the VertexData of the cylinder, cone or prism
  37053. */
  37054. VertexData.CreateCylinder = function (options) {
  37055. var height = options.height || 2;
  37056. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  37057. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  37058. var tessellation = options.tessellation || 24;
  37059. var subdivisions = options.subdivisions || 1;
  37060. var hasRings = options.hasRings ? true : false;
  37061. var enclose = options.enclose ? true : false;
  37062. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  37063. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37064. var faceUV = options.faceUV || new Array(3);
  37065. var faceColors = options.faceColors;
  37066. // default face colors and UV if undefined
  37067. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  37068. var ringNb = (hasRings) ? subdivisions : 1;
  37069. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  37070. var f;
  37071. for (f = 0; f < surfaceNb; f++) {
  37072. if (faceColors && faceColors[f] === undefined) {
  37073. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  37074. }
  37075. }
  37076. for (f = 0; f < surfaceNb; f++) {
  37077. if (faceUV && faceUV[f] === undefined) {
  37078. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  37079. }
  37080. }
  37081. var indices = new Array();
  37082. var positions = new Array();
  37083. var normals = new Array();
  37084. var uvs = new Array();
  37085. var colors = new Array();
  37086. var angle_step = Math.PI * 2 * arc / tessellation;
  37087. var angle;
  37088. var h;
  37089. var radius;
  37090. var tan = (diameterBottom - diameterTop) / 2 / height;
  37091. var ringVertex = BABYLON.Vector3.Zero();
  37092. var ringNormal = BABYLON.Vector3.Zero();
  37093. var ringFirstVertex = BABYLON.Vector3.Zero();
  37094. var ringFirstNormal = BABYLON.Vector3.Zero();
  37095. var quadNormal = BABYLON.Vector3.Zero();
  37096. var Y = BABYLON.Axis.Y;
  37097. // positions, normals, uvs
  37098. var i;
  37099. var j;
  37100. var r;
  37101. var ringIdx = 1;
  37102. var s = 1; // surface index
  37103. var cs = 0;
  37104. var v = 0;
  37105. for (i = 0; i <= subdivisions; i++) {
  37106. h = i / subdivisions;
  37107. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  37108. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  37109. for (r = 0; r < ringIdx; r++) {
  37110. if (hasRings) {
  37111. s += r;
  37112. }
  37113. if (enclose) {
  37114. s += 2 * r;
  37115. }
  37116. for (j = 0; j <= tessellation; j++) {
  37117. angle = j * angle_step;
  37118. // position
  37119. ringVertex.x = Math.cos(-angle) * radius;
  37120. ringVertex.y = -height / 2 + h * height;
  37121. ringVertex.z = Math.sin(-angle) * radius;
  37122. // normal
  37123. if (diameterTop === 0 && i === subdivisions) {
  37124. // if no top cap, reuse former normals
  37125. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  37126. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  37127. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  37128. }
  37129. else {
  37130. ringNormal.x = ringVertex.x;
  37131. ringNormal.z = ringVertex.z;
  37132. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  37133. ringNormal.normalize();
  37134. }
  37135. // keep first ring vertex values for enclose
  37136. if (j === 0) {
  37137. ringFirstVertex.copyFrom(ringVertex);
  37138. ringFirstNormal.copyFrom(ringNormal);
  37139. }
  37140. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  37141. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  37142. if (hasRings) {
  37143. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  37144. }
  37145. else {
  37146. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  37147. }
  37148. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  37149. if (faceColors) {
  37150. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  37151. }
  37152. }
  37153. // if enclose, add four vertices and their dedicated normals
  37154. if (arc !== 1 && enclose) {
  37155. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  37156. positions.push(0, ringVertex.y, 0);
  37157. positions.push(0, ringVertex.y, 0);
  37158. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  37159. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  37160. quadNormal.normalize();
  37161. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  37162. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  37163. quadNormal.normalize();
  37164. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  37165. if (hasRings) {
  37166. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  37167. }
  37168. else {
  37169. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  37170. }
  37171. uvs.push(faceUV[s + 1].x, v);
  37172. uvs.push(faceUV[s + 1].z, v);
  37173. if (hasRings) {
  37174. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  37175. }
  37176. else {
  37177. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  37178. }
  37179. uvs.push(faceUV[s + 2].x, v);
  37180. uvs.push(faceUV[s + 2].z, v);
  37181. if (faceColors) {
  37182. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  37183. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  37184. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  37185. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  37186. }
  37187. }
  37188. if (cs !== s) {
  37189. cs = s;
  37190. }
  37191. }
  37192. }
  37193. // indices
  37194. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  37195. var s;
  37196. i = 0;
  37197. for (s = 0; s < subdivisions; s++) {
  37198. var i0 = 0;
  37199. var i1 = 0;
  37200. var i2 = 0;
  37201. var i3 = 0;
  37202. for (j = 0; j < tessellation; j++) {
  37203. i0 = i * (e + 1) + j;
  37204. i1 = (i + 1) * (e + 1) + j;
  37205. i2 = i * (e + 1) + (j + 1);
  37206. i3 = (i + 1) * (e + 1) + (j + 1);
  37207. indices.push(i0, i1, i2);
  37208. indices.push(i3, i2, i1);
  37209. }
  37210. if (arc !== 1 && enclose) { // if enclose, add two quads
  37211. indices.push(i0 + 2, i1 + 2, i2 + 2);
  37212. indices.push(i3 + 2, i2 + 2, i1 + 2);
  37213. indices.push(i0 + 4, i1 + 4, i2 + 4);
  37214. indices.push(i3 + 4, i2 + 4, i1 + 4);
  37215. }
  37216. i = (hasRings) ? (i + 2) : (i + 1);
  37217. }
  37218. // Caps
  37219. var createCylinderCap = function (isTop) {
  37220. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  37221. if (radius === 0) {
  37222. return;
  37223. }
  37224. // Cap positions, normals & uvs
  37225. var angle;
  37226. var circleVector;
  37227. var i;
  37228. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  37229. var c = null;
  37230. if (faceColors) {
  37231. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  37232. }
  37233. // cap center
  37234. var vbase = positions.length / 3;
  37235. var offset = isTop ? height / 2 : -height / 2;
  37236. var center = new BABYLON.Vector3(0, offset, 0);
  37237. positions.push(center.x, center.y, center.z);
  37238. normals.push(0, isTop ? 1 : -1, 0);
  37239. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  37240. if (c) {
  37241. colors.push(c.r, c.g, c.b, c.a);
  37242. }
  37243. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  37244. for (i = 0; i <= tessellation; i++) {
  37245. angle = Math.PI * 2 * i * arc / tessellation;
  37246. var cos = Math.cos(-angle);
  37247. var sin = Math.sin(-angle);
  37248. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  37249. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  37250. positions.push(circleVector.x, circleVector.y, circleVector.z);
  37251. normals.push(0, isTop ? 1 : -1, 0);
  37252. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  37253. if (c) {
  37254. colors.push(c.r, c.g, c.b, c.a);
  37255. }
  37256. }
  37257. // Cap indices
  37258. for (i = 0; i < tessellation; i++) {
  37259. if (!isTop) {
  37260. indices.push(vbase);
  37261. indices.push(vbase + (i + 1));
  37262. indices.push(vbase + (i + 2));
  37263. }
  37264. else {
  37265. indices.push(vbase);
  37266. indices.push(vbase + (i + 2));
  37267. indices.push(vbase + (i + 1));
  37268. }
  37269. }
  37270. };
  37271. // add caps to geometry
  37272. createCylinderCap(false);
  37273. createCylinderCap(true);
  37274. // Sides
  37275. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37276. var vertexData = new VertexData();
  37277. vertexData.indices = indices;
  37278. vertexData.positions = positions;
  37279. vertexData.normals = normals;
  37280. vertexData.uvs = uvs;
  37281. if (faceColors) {
  37282. vertexData.colors = colors;
  37283. }
  37284. return vertexData;
  37285. };
  37286. /**
  37287. * Creates the VertexData for a torus
  37288. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37289. * * diameter the diameter of the torus, optional default 1
  37290. * * thickness the diameter of the tube forming the torus, optional default 0.5
  37291. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  37292. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37293. * * 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)
  37294. * * 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)
  37295. * @returns the VertexData of the torus
  37296. */
  37297. VertexData.CreateTorus = function (options) {
  37298. var indices = [];
  37299. var positions = [];
  37300. var normals = [];
  37301. var uvs = [];
  37302. var diameter = options.diameter || 1;
  37303. var thickness = options.thickness || 0.5;
  37304. var tessellation = options.tessellation || 16;
  37305. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37306. var stride = tessellation + 1;
  37307. for (var i = 0; i <= tessellation; i++) {
  37308. var u = i / tessellation;
  37309. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  37310. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  37311. for (var j = 0; j <= tessellation; j++) {
  37312. var v = 1 - j / tessellation;
  37313. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  37314. var dx = Math.cos(innerAngle);
  37315. var dy = Math.sin(innerAngle);
  37316. // Create a vertex.
  37317. var normal = new BABYLON.Vector3(dx, dy, 0);
  37318. var position = normal.scale(thickness / 2);
  37319. var textureCoordinate = new BABYLON.Vector2(u, v);
  37320. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  37321. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  37322. positions.push(position.x, position.y, position.z);
  37323. normals.push(normal.x, normal.y, normal.z);
  37324. uvs.push(textureCoordinate.x, textureCoordinate.y);
  37325. // And create indices for two triangles.
  37326. var nextI = (i + 1) % stride;
  37327. var nextJ = (j + 1) % stride;
  37328. indices.push(i * stride + j);
  37329. indices.push(i * stride + nextJ);
  37330. indices.push(nextI * stride + j);
  37331. indices.push(i * stride + nextJ);
  37332. indices.push(nextI * stride + nextJ);
  37333. indices.push(nextI * stride + j);
  37334. }
  37335. }
  37336. // Sides
  37337. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37338. // Result
  37339. var vertexData = new VertexData();
  37340. vertexData.indices = indices;
  37341. vertexData.positions = positions;
  37342. vertexData.normals = normals;
  37343. vertexData.uvs = uvs;
  37344. return vertexData;
  37345. };
  37346. /**
  37347. * Creates the VertexData of the LineSystem
  37348. * @param options an object used to set the following optional parameters for the LineSystem, required but can be empty
  37349. * - lines an array of lines, each line being an array of successive Vector3
  37350. * - colors an array of line colors, each of the line colors being an array of successive Color4, one per line point
  37351. * @returns the VertexData of the LineSystem
  37352. */
  37353. VertexData.CreateLineSystem = function (options) {
  37354. var indices = [];
  37355. var positions = [];
  37356. var lines = options.lines;
  37357. var colors = options.colors;
  37358. var vertexColors = [];
  37359. var idx = 0;
  37360. for (var l = 0; l < lines.length; l++) {
  37361. var points = lines[l];
  37362. for (var index = 0; index < points.length; index++) {
  37363. positions.push(points[index].x, points[index].y, points[index].z);
  37364. if (colors) {
  37365. var color = colors[l];
  37366. vertexColors.push(color[index].r, color[index].g, color[index].b, color[index].a);
  37367. }
  37368. if (index > 0) {
  37369. indices.push(idx - 1);
  37370. indices.push(idx);
  37371. }
  37372. idx++;
  37373. }
  37374. }
  37375. var vertexData = new VertexData();
  37376. vertexData.indices = indices;
  37377. vertexData.positions = positions;
  37378. if (colors) {
  37379. vertexData.colors = vertexColors;
  37380. }
  37381. return vertexData;
  37382. };
  37383. /**
  37384. * Create the VertexData for a DashedLines
  37385. * @param options an object used to set the following optional parameters for the DashedLines, required but can be empty
  37386. * - points an array successive Vector3
  37387. * - dashSize the size of the dashes relative to the dash number, optional, default 3
  37388. * - gapSize the size of the gap between two successive dashes relative to the dash number, optional, default 1
  37389. * - dashNb the intended total number of dashes, optional, default 200
  37390. * @returns the VertexData for the DashedLines
  37391. */
  37392. VertexData.CreateDashedLines = function (options) {
  37393. var dashSize = options.dashSize || 3;
  37394. var gapSize = options.gapSize || 1;
  37395. var dashNb = options.dashNb || 200;
  37396. var points = options.points;
  37397. var positions = new Array();
  37398. var indices = new Array();
  37399. var curvect = BABYLON.Vector3.Zero();
  37400. var lg = 0;
  37401. var nb = 0;
  37402. var shft = 0;
  37403. var dashshft = 0;
  37404. var curshft = 0;
  37405. var idx = 0;
  37406. var i = 0;
  37407. for (i = 0; i < points.length - 1; i++) {
  37408. points[i + 1].subtractToRef(points[i], curvect);
  37409. lg += curvect.length();
  37410. }
  37411. shft = lg / dashNb;
  37412. dashshft = dashSize * shft / (dashSize + gapSize);
  37413. for (i = 0; i < points.length - 1; i++) {
  37414. points[i + 1].subtractToRef(points[i], curvect);
  37415. nb = Math.floor(curvect.length() / shft);
  37416. curvect.normalize();
  37417. for (var j = 0; j < nb; j++) {
  37418. curshft = shft * j;
  37419. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  37420. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  37421. indices.push(idx, idx + 1);
  37422. idx += 2;
  37423. }
  37424. }
  37425. // Result
  37426. var vertexData = new VertexData();
  37427. vertexData.positions = positions;
  37428. vertexData.indices = indices;
  37429. return vertexData;
  37430. };
  37431. /**
  37432. * Creates the VertexData for a Ground
  37433. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  37434. * - width the width (x direction) of the ground, optional, default 1
  37435. * - height the height (z direction) of the ground, optional, default 1
  37436. * - subdivisions the number of subdivisions per side, optional, default 1
  37437. * @returns the VertexData of the Ground
  37438. */
  37439. VertexData.CreateGround = function (options) {
  37440. var indices = [];
  37441. var positions = [];
  37442. var normals = [];
  37443. var uvs = [];
  37444. var row, col;
  37445. var width = options.width || 1;
  37446. var height = options.height || 1;
  37447. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  37448. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  37449. for (row = 0; row <= subdivisionsY; row++) {
  37450. for (col = 0; col <= subdivisionsX; col++) {
  37451. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  37452. var normal = new BABYLON.Vector3(0, 1.0, 0);
  37453. positions.push(position.x, position.y, position.z);
  37454. normals.push(normal.x, normal.y, normal.z);
  37455. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  37456. }
  37457. }
  37458. for (row = 0; row < subdivisionsY; row++) {
  37459. for (col = 0; col < subdivisionsX; col++) {
  37460. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  37461. indices.push(col + 1 + row * (subdivisionsX + 1));
  37462. indices.push(col + row * (subdivisionsX + 1));
  37463. indices.push(col + (row + 1) * (subdivisionsX + 1));
  37464. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  37465. indices.push(col + row * (subdivisionsX + 1));
  37466. }
  37467. }
  37468. // Result
  37469. var vertexData = new VertexData();
  37470. vertexData.indices = indices;
  37471. vertexData.positions = positions;
  37472. vertexData.normals = normals;
  37473. vertexData.uvs = uvs;
  37474. return vertexData;
  37475. };
  37476. /**
  37477. * Creates the VertexData for a TiledGround by subdividing the ground into tiles
  37478. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  37479. * * xmin the ground minimum X coordinate, optional, default -1
  37480. * * zmin the ground minimum Z coordinate, optional, default -1
  37481. * * xmax the ground maximum X coordinate, optional, default 1
  37482. * * zmax the ground maximum Z coordinate, optional, default 1
  37483. * * 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}
  37484. * * 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}
  37485. * @returns the VertexData of the TiledGround
  37486. */
  37487. VertexData.CreateTiledGround = function (options) {
  37488. var xmin = (options.xmin !== undefined && options.xmin !== null) ? options.xmin : -1.0;
  37489. var zmin = (options.zmin !== undefined && options.zmin !== null) ? options.zmin : -1.0;
  37490. var xmax = (options.xmax !== undefined && options.xmax !== null) ? options.xmax : 1.0;
  37491. var zmax = (options.zmax !== undefined && options.zmax !== null) ? options.zmax : 1.0;
  37492. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  37493. var precision = options.precision || { w: 1, h: 1 };
  37494. var indices = new Array();
  37495. var positions = new Array();
  37496. var normals = new Array();
  37497. var uvs = new Array();
  37498. var row, col, tileRow, tileCol;
  37499. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  37500. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  37501. precision.w = (precision.w < 1) ? 1 : precision.w;
  37502. precision.h = (precision.h < 1) ? 1 : precision.h;
  37503. var tileSize = {
  37504. 'w': (xmax - xmin) / subdivisions.w,
  37505. 'h': (zmax - zmin) / subdivisions.h
  37506. };
  37507. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  37508. // Indices
  37509. var base = positions.length / 3;
  37510. var rowLength = precision.w + 1;
  37511. for (row = 0; row < precision.h; row++) {
  37512. for (col = 0; col < precision.w; col++) {
  37513. var square = [
  37514. base + col + row * rowLength,
  37515. base + (col + 1) + row * rowLength,
  37516. base + (col + 1) + (row + 1) * rowLength,
  37517. base + col + (row + 1) * rowLength
  37518. ];
  37519. indices.push(square[1]);
  37520. indices.push(square[2]);
  37521. indices.push(square[3]);
  37522. indices.push(square[0]);
  37523. indices.push(square[1]);
  37524. indices.push(square[3]);
  37525. }
  37526. }
  37527. // Position, normals and uvs
  37528. var position = BABYLON.Vector3.Zero();
  37529. var normal = new BABYLON.Vector3(0, 1.0, 0);
  37530. for (row = 0; row <= precision.h; row++) {
  37531. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  37532. for (col = 0; col <= precision.w; col++) {
  37533. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  37534. position.y = 0;
  37535. positions.push(position.x, position.y, position.z);
  37536. normals.push(normal.x, normal.y, normal.z);
  37537. uvs.push(col / precision.w, row / precision.h);
  37538. }
  37539. }
  37540. }
  37541. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  37542. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  37543. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  37544. }
  37545. }
  37546. // Result
  37547. var vertexData = new VertexData();
  37548. vertexData.indices = indices;
  37549. vertexData.positions = positions;
  37550. vertexData.normals = normals;
  37551. vertexData.uvs = uvs;
  37552. return vertexData;
  37553. };
  37554. /**
  37555. * Creates the VertexData of the Ground designed from a heightmap
  37556. * @param options an object used to set the following parameters for the Ground, required and provided by MeshBuilder.CreateGroundFromHeightMap
  37557. * * width the width (x direction) of the ground
  37558. * * height the height (z direction) of the ground
  37559. * * subdivisions the number of subdivisions per side
  37560. * * minHeight the minimum altitude on the ground, optional, default 0
  37561. * * maxHeight the maximum altitude on the ground, optional default 1
  37562. * * colorFilter the filter to apply to the image pixel colors to compute the height, optional Color3, default (0.3, 0.59, 0.11)
  37563. * * buffer the array holding the image color data
  37564. * * bufferWidth the width of image
  37565. * * bufferHeight the height of image
  37566. * * alphaFilter Remove any data where the alpha channel is below this value, defaults 0 (all data visible)
  37567. * @returns the VertexData of the Ground designed from a heightmap
  37568. */
  37569. VertexData.CreateGroundFromHeightMap = function (options) {
  37570. var indices = [];
  37571. var positions = [];
  37572. var normals = [];
  37573. var uvs = [];
  37574. var row, col;
  37575. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  37576. var alphaFilter = options.alphaFilter || 0.0;
  37577. // Vertices
  37578. for (row = 0; row <= options.subdivisions; row++) {
  37579. for (col = 0; col <= options.subdivisions; col++) {
  37580. 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));
  37581. // Compute height
  37582. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  37583. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  37584. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  37585. var r = options.buffer[pos] / 255.0;
  37586. var g = options.buffer[pos + 1] / 255.0;
  37587. var b = options.buffer[pos + 2] / 255.0;
  37588. var a = options.buffer[pos + 3] / 255.0;
  37589. var gradient = r * filter.r + g * filter.g + b * filter.b;
  37590. // If our alpha channel is not within our filter then we will assign a 'special' height
  37591. // Then when building the indices, we will ignore any vertex that is using the special height
  37592. if (a >= alphaFilter)
  37593. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  37594. else {
  37595. position.y = options.minHeight - BABYLON.Epsilon; // We can't have a height below minHeight, normally.
  37596. }
  37597. // Add vertex
  37598. positions.push(position.x, position.y, position.z);
  37599. normals.push(0, 0, 0);
  37600. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  37601. }
  37602. }
  37603. // Indices
  37604. for (row = 0; row < options.subdivisions; row++) {
  37605. for (col = 0; col < options.subdivisions; col++) {
  37606. // Calculate Indices
  37607. var idx1 = (col + 1 + (row + 1) * (options.subdivisions + 1));
  37608. var idx2 = (col + 1 + row * (options.subdivisions + 1));
  37609. var idx3 = (col + row * (options.subdivisions + 1));
  37610. var idx4 = (col + (row + 1) * (options.subdivisions + 1));
  37611. // Check that all indices are visible (based on our special height)
  37612. // Only display the vertex if all Indices are visible
  37613. // Positions are stored x,y,z for each vertex, hence the * 3 and + 1 for height
  37614. var isVisibleIdx1 = positions[idx1 * 3 + 1] >= options.minHeight;
  37615. var isVisibleIdx2 = positions[idx2 * 3 + 1] >= options.minHeight;
  37616. var isVisibleIdx3 = positions[idx3 * 3 + 1] >= options.minHeight;
  37617. if (isVisibleIdx1 && isVisibleIdx2 && isVisibleIdx3) {
  37618. indices.push(idx1);
  37619. indices.push(idx2);
  37620. indices.push(idx3);
  37621. }
  37622. var isVisibleIdx4 = positions[idx4 * 3 + 1] >= options.minHeight;
  37623. if (isVisibleIdx4 && isVisibleIdx1 && isVisibleIdx3) {
  37624. indices.push(idx4);
  37625. indices.push(idx1);
  37626. indices.push(idx3);
  37627. }
  37628. }
  37629. }
  37630. // Normals
  37631. VertexData.ComputeNormals(positions, indices, normals);
  37632. // Result
  37633. var vertexData = new VertexData();
  37634. vertexData.indices = indices;
  37635. vertexData.positions = positions;
  37636. vertexData.normals = normals;
  37637. vertexData.uvs = uvs;
  37638. return vertexData;
  37639. };
  37640. /**
  37641. * Creates the VertexData for a Plane
  37642. * @param options an object used to set the following optional parameters for the plane, required but can be empty
  37643. * * size sets the width and height of the plane to the value of size, optional default 1
  37644. * * width sets the width (x direction) of the plane, overwrites the width set by size, optional, default size
  37645. * * height sets the height (y direction) of the plane, overwrites the height set by size, optional, default size
  37646. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37647. * * 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)
  37648. * * 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)
  37649. * @returns the VertexData of the box
  37650. */
  37651. VertexData.CreatePlane = function (options) {
  37652. var indices = [];
  37653. var positions = [];
  37654. var normals = [];
  37655. var uvs = [];
  37656. var width = options.width || options.size || 1;
  37657. var height = options.height || options.size || 1;
  37658. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37659. // Vertices
  37660. var halfWidth = width / 2.0;
  37661. var halfHeight = height / 2.0;
  37662. positions.push(-halfWidth, -halfHeight, 0);
  37663. normals.push(0, 0, -1.0);
  37664. uvs.push(0.0, 0.0);
  37665. positions.push(halfWidth, -halfHeight, 0);
  37666. normals.push(0, 0, -1.0);
  37667. uvs.push(1.0, 0.0);
  37668. positions.push(halfWidth, halfHeight, 0);
  37669. normals.push(0, 0, -1.0);
  37670. uvs.push(1.0, 1.0);
  37671. positions.push(-halfWidth, halfHeight, 0);
  37672. normals.push(0, 0, -1.0);
  37673. uvs.push(0.0, 1.0);
  37674. // Indices
  37675. indices.push(0);
  37676. indices.push(1);
  37677. indices.push(2);
  37678. indices.push(0);
  37679. indices.push(2);
  37680. indices.push(3);
  37681. // Sides
  37682. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37683. // Result
  37684. var vertexData = new VertexData();
  37685. vertexData.indices = indices;
  37686. vertexData.positions = positions;
  37687. vertexData.normals = normals;
  37688. vertexData.uvs = uvs;
  37689. return vertexData;
  37690. };
  37691. /**
  37692. * Creates the VertexData of the Disc or regular Polygon
  37693. * @param options an object used to set the following optional parameters for the disc, required but can be empty
  37694. * * radius the radius of the disc, optional default 0.5
  37695. * * tessellation the number of polygon sides, optional, default 64
  37696. * * 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
  37697. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37698. * * 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)
  37699. * * 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)
  37700. * @returns the VertexData of the box
  37701. */
  37702. VertexData.CreateDisc = function (options) {
  37703. var positions = new Array();
  37704. var indices = new Array();
  37705. var normals = new Array();
  37706. var uvs = new Array();
  37707. var radius = options.radius || 0.5;
  37708. var tessellation = options.tessellation || 64;
  37709. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  37710. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37711. // positions and uvs
  37712. positions.push(0, 0, 0); // disc center first
  37713. uvs.push(0.5, 0.5);
  37714. var theta = Math.PI * 2 * arc;
  37715. var step = theta / tessellation;
  37716. for (var a = 0; a < theta; a += step) {
  37717. var x = Math.cos(a);
  37718. var y = Math.sin(a);
  37719. var u = (x + 1) / 2;
  37720. var v = (1 - y) / 2;
  37721. positions.push(radius * x, radius * y, 0);
  37722. uvs.push(u, v);
  37723. }
  37724. if (arc === 1) {
  37725. positions.push(positions[3], positions[4], positions[5]); // close the circle
  37726. uvs.push(uvs[2], uvs[3]);
  37727. }
  37728. //indices
  37729. var vertexNb = positions.length / 3;
  37730. for (var i = 1; i < vertexNb - 1; i++) {
  37731. indices.push(i + 1, 0, i);
  37732. }
  37733. // result
  37734. VertexData.ComputeNormals(positions, indices, normals);
  37735. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37736. var vertexData = new VertexData();
  37737. vertexData.indices = indices;
  37738. vertexData.positions = positions;
  37739. vertexData.normals = normals;
  37740. vertexData.uvs = uvs;
  37741. return vertexData;
  37742. };
  37743. /**
  37744. * Creates the VertexData for an irregular Polygon in the XoZ plane using a mesh built by polygonTriangulation.build()
  37745. * All parameters are provided by MeshBuilder.CreatePolygon as needed
  37746. * @param polygon a mesh built from polygonTriangulation.build()
  37747. * @param sideOrientation takes the values BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37748. * @param fUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  37749. * @param fColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  37750. * @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)
  37751. * @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)
  37752. * @returns the VertexData of the Polygon
  37753. */
  37754. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  37755. var faceUV = fUV || new Array(3);
  37756. var faceColors = fColors;
  37757. var colors = [];
  37758. // default face colors and UV if undefined
  37759. for (var f = 0; f < 3; f++) {
  37760. if (faceUV[f] === undefined) {
  37761. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  37762. }
  37763. if (faceColors && faceColors[f] === undefined) {
  37764. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  37765. }
  37766. }
  37767. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  37768. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  37769. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  37770. var indices = polygon.getIndices();
  37771. // set face colours and textures
  37772. var idx = 0;
  37773. var face = 0;
  37774. for (var index = 0; index < normals.length; index += 3) {
  37775. //Edge Face no. 1
  37776. if (Math.abs(normals[index + 1]) < 0.001) {
  37777. face = 1;
  37778. }
  37779. //Top Face no. 0
  37780. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  37781. face = 0;
  37782. }
  37783. //Bottom Face no. 2
  37784. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  37785. face = 2;
  37786. }
  37787. idx = index / 3;
  37788. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  37789. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  37790. if (faceColors) {
  37791. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  37792. }
  37793. }
  37794. // sides
  37795. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  37796. // Result
  37797. var vertexData = new VertexData();
  37798. vertexData.indices = indices;
  37799. vertexData.positions = positions;
  37800. vertexData.normals = normals;
  37801. vertexData.uvs = uvs;
  37802. if (faceColors) {
  37803. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  37804. vertexData.colors = totalColors;
  37805. }
  37806. return vertexData;
  37807. };
  37808. /**
  37809. * Creates the VertexData of the IcoSphere
  37810. * @param options an object used to set the following optional parameters for the IcoSphere, required but can be empty
  37811. * * radius the radius of the IcoSphere, optional default 1
  37812. * * radiusX allows stretching in the x direction, optional, default radius
  37813. * * radiusY allows stretching in the y direction, optional, default radius
  37814. * * radiusZ allows stretching in the z direction, optional, default radius
  37815. * * flat when true creates a flat shaded mesh, optional, default true
  37816. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  37817. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37818. * * 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)
  37819. * * 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)
  37820. * @returns the VertexData of the IcoSphere
  37821. */
  37822. VertexData.CreateIcoSphere = function (options) {
  37823. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37824. var radius = options.radius || 1;
  37825. var flat = (options.flat === undefined) ? true : options.flat;
  37826. var subdivisions = options.subdivisions || 4;
  37827. var radiusX = options.radiusX || radius;
  37828. var radiusY = options.radiusY || radius;
  37829. var radiusZ = options.radiusZ || radius;
  37830. var t = (1 + Math.sqrt(5)) / 2;
  37831. // 12 vertex x,y,z
  37832. var ico_vertices = [
  37833. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  37834. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  37835. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  37836. ];
  37837. // index of 3 vertex makes a face of icopshere
  37838. var ico_indices = [
  37839. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  37840. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  37841. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  37842. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  37843. ];
  37844. // vertex for uv have aliased position, not for UV
  37845. var vertices_unalias_id = [
  37846. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  37847. // vertex alias
  37848. 0,
  37849. 2,
  37850. 3,
  37851. 3,
  37852. 3,
  37853. 4,
  37854. 7,
  37855. 8,
  37856. 9,
  37857. 9,
  37858. 10,
  37859. 11 // 23: B + 12
  37860. ];
  37861. // uv as integer step (not pixels !)
  37862. var ico_vertexuv = [
  37863. 5, 1, 3, 1, 6, 4, 0, 0,
  37864. 5, 3, 4, 2, 2, 2, 4, 0,
  37865. 2, 0, 1, 1, 6, 0, 6, 2,
  37866. // vertex alias (for same vertex on different faces)
  37867. 0, 4,
  37868. 3, 3,
  37869. 4, 4,
  37870. 3, 1,
  37871. 4, 2,
  37872. 4, 4,
  37873. 0, 2,
  37874. 1, 1,
  37875. 2, 2,
  37876. 3, 3,
  37877. 1, 3,
  37878. 2, 4 // 23: B + 12
  37879. ];
  37880. // Vertices[0, 1, ...9, A, B] : position on UV plane
  37881. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  37882. // First island of uv mapping
  37883. // v = 4h 3+ 2
  37884. // v = 3h 9+ 4
  37885. // v = 2h 9+ 5 B
  37886. // v = 1h 9 1 0
  37887. // v = 0h 3 8 7 A
  37888. // u = 0 1 2 3 4 5 6 *a
  37889. // Second island of uv mapping
  37890. // v = 4h 0+ B+ 4+
  37891. // v = 3h A+ 2+
  37892. // v = 2h 7+ 6 3+
  37893. // v = 1h 8+ 3+
  37894. // v = 0h
  37895. // u = 0 1 2 3 4 5 6 *a
  37896. // Face layout on texture UV mapping
  37897. // ============
  37898. // \ 4 /\ 16 / ======
  37899. // \ / \ / /\ 11 /
  37900. // \/ 7 \/ / \ /
  37901. // ======= / 10 \/
  37902. // /\ 17 /\ =======
  37903. // / \ / \ \ 15 /\
  37904. // / 8 \/ 12 \ \ / \
  37905. // ============ \/ 6 \
  37906. // \ 18 /\ ============
  37907. // \ / \ \ 5 /\ 0 /
  37908. // \/ 13 \ \ / \ /
  37909. // ======= \/ 1 \/
  37910. // =============
  37911. // /\ 19 /\ 2 /\
  37912. // / \ / \ / \
  37913. // / 14 \/ 9 \/ 3 \
  37914. // ===================
  37915. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  37916. var ustep = 138 / 1024;
  37917. var vstep = 239 / 1024;
  37918. var uoffset = 60 / 1024;
  37919. var voffset = 26 / 1024;
  37920. // Second island should have margin, not to touch the first island
  37921. // avoid any borderline artefact in pixel rounding
  37922. var island_u_offset = -40 / 1024;
  37923. var island_v_offset = +20 / 1024;
  37924. // face is either island 0 or 1 :
  37925. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  37926. var island = [
  37927. 0, 0, 0, 0, 1,
  37928. 0, 0, 1, 1, 0,
  37929. 0, 0, 1, 1, 0,
  37930. 0, 1, 1, 1, 0 // 15 - 19
  37931. ];
  37932. var indices = new Array();
  37933. var positions = new Array();
  37934. var normals = new Array();
  37935. var uvs = new Array();
  37936. var current_indice = 0;
  37937. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  37938. var face_vertex_pos = new Array(3);
  37939. var face_vertex_uv = new Array(3);
  37940. var v012;
  37941. for (v012 = 0; v012 < 3; v012++) {
  37942. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  37943. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  37944. }
  37945. // create all with normals
  37946. for (var face = 0; face < 20; face++) {
  37947. // 3 vertex per face
  37948. for (v012 = 0; v012 < 3; v012++) {
  37949. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  37950. var v_id = ico_indices[3 * face + v012];
  37951. // vertex have 3D position (x,y,z)
  37952. 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]);
  37953. // Normalize to get normal, then scale to radius
  37954. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  37955. // uv Coordinates from vertex ID
  37956. 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);
  37957. }
  37958. // Subdivide the face (interpolate pos, norm, uv)
  37959. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  37960. // - norm is linear interpolation of vertex corner normal
  37961. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  37962. // - uv is linear interpolation
  37963. //
  37964. // Topology is as below for sub-divide by 2
  37965. // vertex shown as v0,v1,v2
  37966. // interp index is i1 to progress in range [v0,v1[
  37967. // interp index is i2 to progress in range [v0,v2[
  37968. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  37969. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  37970. //
  37971. //
  37972. // i2 v2
  37973. // ^ ^
  37974. // / / \
  37975. // / / \
  37976. // / / \
  37977. // / / (0,1) \
  37978. // / #---------\
  37979. // / / \ (0,0)'/ \
  37980. // / / \ / \
  37981. // / / \ / \
  37982. // / / (0,0) \ / (1,0) \
  37983. // / #---------#---------\
  37984. // v0 v1
  37985. //
  37986. // --------------------> i1
  37987. //
  37988. // interp of (i1,i2):
  37989. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  37990. // along i1 : lerp(x0,x1, i1/(S-i2))
  37991. //
  37992. // centroid of triangle is needed to get help normal computation
  37993. // (c1,c2) are used for centroid location
  37994. var interp_vertex = function (i1, i2, c1, c2) {
  37995. // vertex is interpolated from
  37996. // - face_vertex_pos[0..2]
  37997. // - face_vertex_uv[0..2]
  37998. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  37999. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  38000. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  38001. pos_interp.normalize();
  38002. var vertex_normal;
  38003. if (flat) {
  38004. // in flat mode, recalculate normal as face centroid normal
  38005. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  38006. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  38007. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  38008. }
  38009. else {
  38010. // in smooth mode, recalculate normal from each single vertex position
  38011. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  38012. }
  38013. // Vertex normal need correction due to X,Y,Z radius scaling
  38014. vertex_normal.x /= radiusX;
  38015. vertex_normal.y /= radiusY;
  38016. vertex_normal.z /= radiusZ;
  38017. vertex_normal.normalize();
  38018. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  38019. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  38020. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  38021. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  38022. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  38023. uvs.push(uv_interp.x, uv_interp.y);
  38024. // push each vertex has member of a face
  38025. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  38026. indices.push(current_indice);
  38027. current_indice++;
  38028. };
  38029. for (var i2 = 0; i2 < subdivisions; i2++) {
  38030. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  38031. // face : (i1,i2) for /\ :
  38032. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  38033. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  38034. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  38035. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  38036. if (i1 + i2 + 1 < subdivisions) {
  38037. // face : (i1,i2)' for \/ :
  38038. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  38039. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  38040. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  38041. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  38042. }
  38043. }
  38044. }
  38045. }
  38046. // Sides
  38047. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38048. // Result
  38049. var vertexData = new VertexData();
  38050. vertexData.indices = indices;
  38051. vertexData.positions = positions;
  38052. vertexData.normals = normals;
  38053. vertexData.uvs = uvs;
  38054. return vertexData;
  38055. };
  38056. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  38057. /**
  38058. * Creates the VertexData for a Polyhedron
  38059. * @param options an object used to set the following optional parameters for the polyhedron, required but can be empty
  38060. * * type provided types are:
  38061. * * 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  38062. * * 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)
  38063. * * size the size of the IcoSphere, optional default 1
  38064. * * sizeX allows stretching in the x direction, optional, default size
  38065. * * sizeY allows stretching in the y direction, optional, default size
  38066. * * sizeZ allows stretching in the z direction, optional, default size
  38067. * * 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
  38068. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  38069. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  38070. * * flat when true creates a flat shaded mesh, optional, default true
  38071. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  38072. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38073. * * 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)
  38074. * * 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)
  38075. * @returns the VertexData of the Polyhedron
  38076. */
  38077. VertexData.CreatePolyhedron = function (options) {
  38078. // provided polyhedron types :
  38079. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  38080. // 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)
  38081. var polyhedra = [];
  38082. 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]] };
  38083. 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]] };
  38084. polyhedra[2] = {
  38085. 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]],
  38086. 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]]
  38087. };
  38088. polyhedra[3] = {
  38089. 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]],
  38090. 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]]
  38091. };
  38092. polyhedra[4] = {
  38093. 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]],
  38094. 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]]
  38095. };
  38096. 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]] };
  38097. 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]] };
  38098. 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]] };
  38099. 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]] };
  38100. 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]] };
  38101. 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]] };
  38102. 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]] };
  38103. 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]] };
  38104. 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]] };
  38105. polyhedra[14] = {
  38106. 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]],
  38107. 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]]
  38108. };
  38109. var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  38110. var size = options.size;
  38111. var sizeX = options.sizeX || size || 1;
  38112. var sizeY = options.sizeY || size || 1;
  38113. var sizeZ = options.sizeZ || size || 1;
  38114. var data = options.custom || polyhedra[type];
  38115. var nbfaces = data.face.length;
  38116. var faceUV = options.faceUV || new Array(nbfaces);
  38117. var faceColors = options.faceColors;
  38118. var flat = (options.flat === undefined) ? true : options.flat;
  38119. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38120. var positions = new Array();
  38121. var indices = new Array();
  38122. var normals = new Array();
  38123. var uvs = new Array();
  38124. var colors = new Array();
  38125. var index = 0;
  38126. var faceIdx = 0; // face cursor in the array "indexes"
  38127. var indexes = new Array();
  38128. var i = 0;
  38129. var f = 0;
  38130. var u, v, ang, x, y, tmp;
  38131. // default face colors and UV if undefined
  38132. if (flat) {
  38133. for (f = 0; f < nbfaces; f++) {
  38134. if (faceColors && faceColors[f] === undefined) {
  38135. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  38136. }
  38137. if (faceUV && faceUV[f] === undefined) {
  38138. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  38139. }
  38140. }
  38141. }
  38142. if (!flat) {
  38143. for (i = 0; i < data.vertex.length; i++) {
  38144. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  38145. uvs.push(0, 0);
  38146. }
  38147. for (f = 0; f < nbfaces; f++) {
  38148. for (i = 0; i < data.face[f].length - 2; i++) {
  38149. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  38150. }
  38151. }
  38152. }
  38153. else {
  38154. for (f = 0; f < nbfaces; f++) {
  38155. var fl = data.face[f].length; // number of vertices of the current face
  38156. ang = 2 * Math.PI / fl;
  38157. x = 0.5 * Math.tan(ang / 2);
  38158. y = 0.5;
  38159. // positions, uvs, colors
  38160. for (i = 0; i < fl; i++) {
  38161. // positions
  38162. 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);
  38163. indexes.push(index);
  38164. index++;
  38165. // uvs
  38166. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  38167. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  38168. uvs.push(u, v);
  38169. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  38170. y = x * Math.sin(ang) + y * Math.cos(ang);
  38171. x = tmp;
  38172. // colors
  38173. if (faceColors) {
  38174. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  38175. }
  38176. }
  38177. // indices from indexes
  38178. for (i = 0; i < fl - 2; i++) {
  38179. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  38180. }
  38181. faceIdx += fl;
  38182. }
  38183. }
  38184. VertexData.ComputeNormals(positions, indices, normals);
  38185. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38186. var vertexData = new VertexData();
  38187. vertexData.positions = positions;
  38188. vertexData.indices = indices;
  38189. vertexData.normals = normals;
  38190. vertexData.uvs = uvs;
  38191. if (faceColors && flat) {
  38192. vertexData.colors = colors;
  38193. }
  38194. return vertexData;
  38195. };
  38196. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  38197. /**
  38198. * Creates the VertexData for a TorusKnot
  38199. * @param options an object used to set the following optional parameters for the TorusKnot, required but can be empty
  38200. * * radius the radius of the torus knot, optional, default 2
  38201. * * tube the thickness of the tube, optional, default 0.5
  38202. * * radialSegments the number of sides on each tube segments, optional, default 32
  38203. * * tubularSegments the number of tubes to decompose the knot into, optional, default 32
  38204. * * p the number of windings around the z axis, optional, default 2
  38205. * * q the number of windings around the x axis, optional, default 3
  38206. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38207. * * 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)
  38208. * * 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)
  38209. * @returns the VertexData of the Torus Knot
  38210. */
  38211. VertexData.CreateTorusKnot = function (options) {
  38212. var indices = new Array();
  38213. var positions = new Array();
  38214. var normals = new Array();
  38215. var uvs = new Array();
  38216. var radius = options.radius || 2;
  38217. var tube = options.tube || 0.5;
  38218. var radialSegments = options.radialSegments || 32;
  38219. var tubularSegments = options.tubularSegments || 32;
  38220. var p = options.p || 2;
  38221. var q = options.q || 3;
  38222. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38223. // Helper
  38224. var getPos = function (angle) {
  38225. var cu = Math.cos(angle);
  38226. var su = Math.sin(angle);
  38227. var quOverP = q / p * angle;
  38228. var cs = Math.cos(quOverP);
  38229. var tx = radius * (2 + cs) * 0.5 * cu;
  38230. var ty = radius * (2 + cs) * su * 0.5;
  38231. var tz = radius * Math.sin(quOverP) * 0.5;
  38232. return new BABYLON.Vector3(tx, ty, tz);
  38233. };
  38234. // Vertices
  38235. var i;
  38236. var j;
  38237. for (i = 0; i <= radialSegments; i++) {
  38238. var modI = i % radialSegments;
  38239. var u = modI / radialSegments * 2 * p * Math.PI;
  38240. var p1 = getPos(u);
  38241. var p2 = getPos(u + 0.01);
  38242. var tang = p2.subtract(p1);
  38243. var n = p2.add(p1);
  38244. var bitan = BABYLON.Vector3.Cross(tang, n);
  38245. n = BABYLON.Vector3.Cross(bitan, tang);
  38246. bitan.normalize();
  38247. n.normalize();
  38248. for (j = 0; j < tubularSegments; j++) {
  38249. var modJ = j % tubularSegments;
  38250. var v = modJ / tubularSegments * 2 * Math.PI;
  38251. var cx = -tube * Math.cos(v);
  38252. var cy = tube * Math.sin(v);
  38253. positions.push(p1.x + cx * n.x + cy * bitan.x);
  38254. positions.push(p1.y + cx * n.y + cy * bitan.y);
  38255. positions.push(p1.z + cx * n.z + cy * bitan.z);
  38256. uvs.push(i / radialSegments);
  38257. uvs.push(j / tubularSegments);
  38258. }
  38259. }
  38260. for (i = 0; i < radialSegments; i++) {
  38261. for (j = 0; j < tubularSegments; j++) {
  38262. var jNext = (j + 1) % tubularSegments;
  38263. var a = i * tubularSegments + j;
  38264. var b = (i + 1) * tubularSegments + j;
  38265. var c = (i + 1) * tubularSegments + jNext;
  38266. var d = i * tubularSegments + jNext;
  38267. indices.push(d);
  38268. indices.push(b);
  38269. indices.push(a);
  38270. indices.push(d);
  38271. indices.push(c);
  38272. indices.push(b);
  38273. }
  38274. }
  38275. // Normals
  38276. VertexData.ComputeNormals(positions, indices, normals);
  38277. // Sides
  38278. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38279. // Result
  38280. var vertexData = new VertexData();
  38281. vertexData.indices = indices;
  38282. vertexData.positions = positions;
  38283. vertexData.normals = normals;
  38284. vertexData.uvs = uvs;
  38285. return vertexData;
  38286. };
  38287. // Tools
  38288. /**
  38289. * Compute normals for given positions and indices
  38290. * @param positions an array of vertex positions, [...., x, y, z, ......]
  38291. * @param indices an array of indices in groups of three for each triangular facet, [...., i, j, k, ......]
  38292. * @param normals an array of vertex normals, [...., x, y, z, ......]
  38293. * @param options an object used to set the following optional parameters for the TorusKnot, optional
  38294. * * facetNormals : optional array of facet normals (vector3)
  38295. * * facetPositions : optional array of facet positions (vector3)
  38296. * * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  38297. * * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  38298. * * bInfo : optional bounding info, required for facetPartitioning computation
  38299. * * bbSize : optional bounding box size data, required for facetPartitioning computation
  38300. * * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  38301. * * useRightHandedSystem: optional boolean to for right handed system computation
  38302. * * depthSort : optional boolean to enable the facet depth sort computation
  38303. * * distanceTo : optional Vector3 to compute the facet depth from this location
  38304. * * depthSortedFacets : optional array of depthSortedFacets to store the facet distances from the reference location
  38305. */
  38306. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  38307. // temporary scalar variables
  38308. var index = 0; // facet index
  38309. var p1p2x = 0.0; // p1p2 vector x coordinate
  38310. var p1p2y = 0.0; // p1p2 vector y coordinate
  38311. var p1p2z = 0.0; // p1p2 vector z coordinate
  38312. var p3p2x = 0.0; // p3p2 vector x coordinate
  38313. var p3p2y = 0.0; // p3p2 vector y coordinate
  38314. var p3p2z = 0.0; // p3p2 vector z coordinate
  38315. var faceNormalx = 0.0; // facet normal x coordinate
  38316. var faceNormaly = 0.0; // facet normal y coordinate
  38317. var faceNormalz = 0.0; // facet normal z coordinate
  38318. var length = 0.0; // facet normal length before normalization
  38319. var v1x = 0; // vector1 x index in the positions array
  38320. var v1y = 0; // vector1 y index in the positions array
  38321. var v1z = 0; // vector1 z index in the positions array
  38322. var v2x = 0; // vector2 x index in the positions array
  38323. var v2y = 0; // vector2 y index in the positions array
  38324. var v2z = 0; // vector2 z index in the positions array
  38325. var v3x = 0; // vector3 x index in the positions array
  38326. var v3y = 0; // vector3 y index in the positions array
  38327. var v3z = 0; // vector3 z index in the positions array
  38328. var computeFacetNormals = false;
  38329. var computeFacetPositions = false;
  38330. var computeFacetPartitioning = false;
  38331. var computeDepthSort = false;
  38332. var faceNormalSign = 1;
  38333. var ratio = 0;
  38334. var distanceTo = null;
  38335. if (options) {
  38336. computeFacetNormals = (options.facetNormals) ? true : false;
  38337. computeFacetPositions = (options.facetPositions) ? true : false;
  38338. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  38339. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  38340. ratio = options.ratio || 0;
  38341. computeDepthSort = (options.depthSort) ? true : false;
  38342. distanceTo = (options.distanceTo);
  38343. if (computeDepthSort) {
  38344. if (distanceTo === undefined) {
  38345. distanceTo = BABYLON.Vector3.Zero();
  38346. }
  38347. var depthSortedFacets = options.depthSortedFacets;
  38348. }
  38349. }
  38350. // facetPartitioning reinit if needed
  38351. var xSubRatio = 0;
  38352. var ySubRatio = 0;
  38353. var zSubRatio = 0;
  38354. var subSq = 0;
  38355. if (computeFacetPartitioning && options && options.bbSize) {
  38356. var ox = 0; // X partitioning index for facet position
  38357. var oy = 0; // Y partinioning index for facet position
  38358. var oz = 0; // Z partinioning index for facet position
  38359. var b1x = 0; // X partitioning index for facet v1 vertex
  38360. var b1y = 0; // Y partitioning index for facet v1 vertex
  38361. var b1z = 0; // z partitioning index for facet v1 vertex
  38362. var b2x = 0; // X partitioning index for facet v2 vertex
  38363. var b2y = 0; // Y partitioning index for facet v2 vertex
  38364. var b2z = 0; // Z partitioning index for facet v2 vertex
  38365. var b3x = 0; // X partitioning index for facet v3 vertex
  38366. var b3y = 0; // Y partitioning index for facet v3 vertex
  38367. var b3z = 0; // Z partitioning index for facet v3 vertex
  38368. var block_idx_o = 0; // facet barycenter block index
  38369. var block_idx_v1 = 0; // v1 vertex block index
  38370. var block_idx_v2 = 0; // v2 vertex block index
  38371. var block_idx_v3 = 0; // v3 vertex block index
  38372. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  38373. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  38374. xSubRatio = options.subDiv.X * ratio / options.bbSize.x;
  38375. ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;
  38376. zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;
  38377. subSq = options.subDiv.max * options.subDiv.max;
  38378. options.facetPartitioning.length = 0;
  38379. }
  38380. // reset the normals
  38381. for (index = 0; index < positions.length; index++) {
  38382. normals[index] = 0.0;
  38383. }
  38384. // Loop : 1 indice triplet = 1 facet
  38385. var nbFaces = (indices.length / 3) | 0;
  38386. for (index = 0; index < nbFaces; index++) {
  38387. // get the indexes of the coordinates of each vertex of the facet
  38388. v1x = indices[index * 3] * 3;
  38389. v1y = v1x + 1;
  38390. v1z = v1x + 2;
  38391. v2x = indices[index * 3 + 1] * 3;
  38392. v2y = v2x + 1;
  38393. v2z = v2x + 2;
  38394. v3x = indices[index * 3 + 2] * 3;
  38395. v3y = v3x + 1;
  38396. v3z = v3x + 2;
  38397. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  38398. p1p2y = positions[v1y] - positions[v2y];
  38399. p1p2z = positions[v1z] - positions[v2z];
  38400. p3p2x = positions[v3x] - positions[v2x];
  38401. p3p2y = positions[v3y] - positions[v2y];
  38402. p3p2z = positions[v3z] - positions[v2z];
  38403. // compute the face normal with the cross product
  38404. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  38405. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  38406. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  38407. // normalize this normal and store it in the array facetData
  38408. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  38409. length = (length === 0) ? 1.0 : length;
  38410. faceNormalx /= length;
  38411. faceNormaly /= length;
  38412. faceNormalz /= length;
  38413. if (computeFacetNormals && options) {
  38414. options.facetNormals[index].x = faceNormalx;
  38415. options.facetNormals[index].y = faceNormaly;
  38416. options.facetNormals[index].z = faceNormalz;
  38417. }
  38418. if (computeFacetPositions && options) {
  38419. // compute and the facet barycenter coordinates in the array facetPositions
  38420. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  38421. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  38422. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  38423. }
  38424. if (computeFacetPartitioning && options) {
  38425. // store the facet indexes in arrays in the main facetPartitioning array :
  38426. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  38427. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
  38428. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
  38429. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
  38430. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38431. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38432. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38433. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38434. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38435. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38436. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38437. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38438. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38439. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  38440. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  38441. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  38442. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  38443. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  38444. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  38445. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  38446. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  38447. // push each facet index in each block containing the vertex
  38448. options.facetPartitioning[block_idx_v1].push(index);
  38449. if (block_idx_v2 != block_idx_v1) {
  38450. options.facetPartitioning[block_idx_v2].push(index);
  38451. }
  38452. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  38453. options.facetPartitioning[block_idx_v3].push(index);
  38454. }
  38455. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  38456. options.facetPartitioning[block_idx_o].push(index);
  38457. }
  38458. }
  38459. if (computeDepthSort && options && options.facetPositions) {
  38460. var dsf = depthSortedFacets[index];
  38461. dsf.ind = index * 3;
  38462. dsf.sqDistance = BABYLON.Vector3.DistanceSquared(options.facetPositions[index], distanceTo);
  38463. }
  38464. // compute the normals anyway
  38465. normals[v1x] += faceNormalx; // accumulate all the normals per face
  38466. normals[v1y] += faceNormaly;
  38467. normals[v1z] += faceNormalz;
  38468. normals[v2x] += faceNormalx;
  38469. normals[v2y] += faceNormaly;
  38470. normals[v2z] += faceNormalz;
  38471. normals[v3x] += faceNormalx;
  38472. normals[v3y] += faceNormaly;
  38473. normals[v3z] += faceNormalz;
  38474. }
  38475. // last normalization of each normal
  38476. for (index = 0; index < normals.length / 3; index++) {
  38477. faceNormalx = normals[index * 3];
  38478. faceNormaly = normals[index * 3 + 1];
  38479. faceNormalz = normals[index * 3 + 2];
  38480. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  38481. length = (length === 0) ? 1.0 : length;
  38482. faceNormalx /= length;
  38483. faceNormaly /= length;
  38484. faceNormalz /= length;
  38485. normals[index * 3] = faceNormalx;
  38486. normals[index * 3 + 1] = faceNormaly;
  38487. normals[index * 3 + 2] = faceNormalz;
  38488. }
  38489. };
  38490. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  38491. var li = indices.length;
  38492. var ln = normals.length;
  38493. var i;
  38494. var n;
  38495. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38496. switch (sideOrientation) {
  38497. case BABYLON.Mesh.FRONTSIDE:
  38498. // nothing changed
  38499. break;
  38500. case BABYLON.Mesh.BACKSIDE:
  38501. var tmp;
  38502. // indices
  38503. for (i = 0; i < li; i += 3) {
  38504. tmp = indices[i];
  38505. indices[i] = indices[i + 2];
  38506. indices[i + 2] = tmp;
  38507. }
  38508. // normals
  38509. for (n = 0; n < ln; n++) {
  38510. normals[n] = -normals[n];
  38511. }
  38512. break;
  38513. case BABYLON.Mesh.DOUBLESIDE:
  38514. // positions
  38515. var lp = positions.length;
  38516. var l = lp / 3;
  38517. for (var p = 0; p < lp; p++) {
  38518. positions[lp + p] = positions[p];
  38519. }
  38520. // indices
  38521. for (i = 0; i < li; i += 3) {
  38522. indices[i + li] = indices[i + 2] + l;
  38523. indices[i + 1 + li] = indices[i + 1] + l;
  38524. indices[i + 2 + li] = indices[i] + l;
  38525. }
  38526. // normals
  38527. for (n = 0; n < ln; n++) {
  38528. normals[ln + n] = -normals[n];
  38529. }
  38530. // uvs
  38531. var lu = uvs.length;
  38532. var u = 0;
  38533. for (u = 0; u < lu; u++) {
  38534. uvs[u + lu] = uvs[u];
  38535. }
  38536. frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  38537. backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  38538. u = 0;
  38539. for (i = 0; i < lu / 2; i++) {
  38540. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  38541. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  38542. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  38543. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  38544. u += 2;
  38545. }
  38546. break;
  38547. }
  38548. };
  38549. /**
  38550. * Applies VertexData created from the imported parameters to the geometry
  38551. * @param parsedVertexData the parsed data from an imported file
  38552. * @param geometry the geometry to apply the VertexData to
  38553. */
  38554. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  38555. var vertexData = new VertexData();
  38556. // positions
  38557. var positions = parsedVertexData.positions;
  38558. if (positions) {
  38559. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  38560. }
  38561. // normals
  38562. var normals = parsedVertexData.normals;
  38563. if (normals) {
  38564. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  38565. }
  38566. // tangents
  38567. var tangents = parsedVertexData.tangents;
  38568. if (tangents) {
  38569. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  38570. }
  38571. // uvs
  38572. var uvs = parsedVertexData.uvs;
  38573. if (uvs) {
  38574. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  38575. }
  38576. // uv2s
  38577. var uv2s = parsedVertexData.uv2s;
  38578. if (uv2s) {
  38579. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  38580. }
  38581. // uv3s
  38582. var uv3s = parsedVertexData.uv3s;
  38583. if (uv3s) {
  38584. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  38585. }
  38586. // uv4s
  38587. var uv4s = parsedVertexData.uv4s;
  38588. if (uv4s) {
  38589. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  38590. }
  38591. // uv5s
  38592. var uv5s = parsedVertexData.uv5s;
  38593. if (uv5s) {
  38594. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  38595. }
  38596. // uv6s
  38597. var uv6s = parsedVertexData.uv6s;
  38598. if (uv6s) {
  38599. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  38600. }
  38601. // colors
  38602. var colors = parsedVertexData.colors;
  38603. if (colors) {
  38604. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  38605. }
  38606. // matricesIndices
  38607. var matricesIndices = parsedVertexData.matricesIndices;
  38608. if (matricesIndices) {
  38609. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  38610. }
  38611. // matricesWeights
  38612. var matricesWeights = parsedVertexData.matricesWeights;
  38613. if (matricesWeights) {
  38614. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  38615. }
  38616. // indices
  38617. var indices = parsedVertexData.indices;
  38618. if (indices) {
  38619. vertexData.indices = indices;
  38620. }
  38621. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  38622. };
  38623. return VertexData;
  38624. }());
  38625. BABYLON.VertexData = VertexData;
  38626. })(BABYLON || (BABYLON = {}));
  38627. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  38628. var BABYLON;
  38629. (function (BABYLON) {
  38630. /**
  38631. * Class used to store geometry data (vertex buffers + index buffer)
  38632. */
  38633. var Geometry = /** @class */ (function () {
  38634. /**
  38635. * Creates a new geometry
  38636. * @param id defines the unique ID
  38637. * @param scene defines the hosting scene
  38638. * @param vertexData defines the {BABYLON.VertexData} used to get geometry data
  38639. * @param updatable defines if geometry must be updatable (false by default)
  38640. * @param mesh defines the mesh that will be associated with the geometry
  38641. */
  38642. function Geometry(id, scene, vertexData, updatable, mesh) {
  38643. if (updatable === void 0) { updatable = false; }
  38644. if (mesh === void 0) { mesh = null; }
  38645. /**
  38646. * Gets the delay loading state of the geometry (none by default which means not delayed)
  38647. */
  38648. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  38649. this._totalVertices = 0;
  38650. this._isDisposed = false;
  38651. this._indexBufferIsUpdatable = false;
  38652. this.id = id;
  38653. this._engine = scene.getEngine();
  38654. this._meshes = [];
  38655. this._scene = scene;
  38656. //Init vertex buffer cache
  38657. this._vertexBuffers = {};
  38658. this._indices = [];
  38659. this._updatable = updatable;
  38660. // vertexData
  38661. if (vertexData) {
  38662. this.setAllVerticesData(vertexData, updatable);
  38663. }
  38664. else {
  38665. this._totalVertices = 0;
  38666. this._indices = [];
  38667. }
  38668. if (this._engine.getCaps().vertexArrayObject) {
  38669. this._vertexArrayObjects = {};
  38670. }
  38671. // applyToMesh
  38672. if (mesh) {
  38673. if (mesh.getClassName() === "LinesMesh") {
  38674. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  38675. this._updateExtend();
  38676. }
  38677. this.applyToMesh(mesh);
  38678. mesh.computeWorldMatrix(true);
  38679. }
  38680. }
  38681. Object.defineProperty(Geometry.prototype, "boundingBias", {
  38682. /**
  38683. * 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
  38684. */
  38685. get: function () {
  38686. return this._boundingBias;
  38687. },
  38688. /**
  38689. * 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
  38690. */
  38691. set: function (value) {
  38692. if (this._boundingBias && this._boundingBias.equals(value)) {
  38693. return;
  38694. }
  38695. this._boundingBias = value.clone();
  38696. this._updateBoundingInfo(true, null);
  38697. },
  38698. enumerable: true,
  38699. configurable: true
  38700. });
  38701. /**
  38702. * Static function used to attach a new empty geometry to a mesh
  38703. * @param mesh defines the mesh to attach the geometry to
  38704. * @returns the new {BABYLON.Geometry}
  38705. */
  38706. Geometry.CreateGeometryForMesh = function (mesh) {
  38707. var geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
  38708. geometry.applyToMesh(mesh);
  38709. return geometry;
  38710. };
  38711. Object.defineProperty(Geometry.prototype, "extend", {
  38712. /**
  38713. * Gets the current extend of the geometry
  38714. */
  38715. get: function () {
  38716. return this._extend;
  38717. },
  38718. enumerable: true,
  38719. configurable: true
  38720. });
  38721. /**
  38722. * Gets the hosting scene
  38723. * @returns the hosting {BABYLON.Scene}
  38724. */
  38725. Geometry.prototype.getScene = function () {
  38726. return this._scene;
  38727. };
  38728. /**
  38729. * Gets the hosting engine
  38730. * @returns the hosting {BABYLON.Engine}
  38731. */
  38732. Geometry.prototype.getEngine = function () {
  38733. return this._engine;
  38734. };
  38735. /**
  38736. * Defines if the geometry is ready to use
  38737. * @returns true if the geometry is ready to be used
  38738. */
  38739. Geometry.prototype.isReady = function () {
  38740. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  38741. };
  38742. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  38743. /**
  38744. * Gets a value indicating that the geometry should not be serialized
  38745. */
  38746. get: function () {
  38747. for (var index = 0; index < this._meshes.length; index++) {
  38748. if (!this._meshes[index].doNotSerialize) {
  38749. return false;
  38750. }
  38751. }
  38752. return true;
  38753. },
  38754. enumerable: true,
  38755. configurable: true
  38756. });
  38757. /** @hidden */
  38758. Geometry.prototype._rebuild = function () {
  38759. if (this._vertexArrayObjects) {
  38760. this._vertexArrayObjects = {};
  38761. }
  38762. // Index buffer
  38763. if (this._meshes.length !== 0 && this._indices) {
  38764. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  38765. }
  38766. // Vertex buffers
  38767. for (var key in this._vertexBuffers) {
  38768. var vertexBuffer = this._vertexBuffers[key];
  38769. vertexBuffer._rebuild();
  38770. }
  38771. };
  38772. /**
  38773. * Affects all geometry data in one call
  38774. * @param vertexData defines the geometry data
  38775. * @param updatable defines if the geometry must be flagged as updatable (false as default)
  38776. */
  38777. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  38778. vertexData.applyToGeometry(this, updatable);
  38779. this.notifyUpdate();
  38780. };
  38781. /**
  38782. * Set specific vertex data
  38783. * @param kind defines the data kind (Position, normal, etc...)
  38784. * @param data defines the vertex data to use
  38785. * @param updatable defines if the vertex must be flagged as updatable (false as default)
  38786. * @param stride defines the stride to use (0 by default). This value is deduced from the kind value if not specified
  38787. */
  38788. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  38789. if (updatable === void 0) { updatable = false; }
  38790. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  38791. this.setVerticesBuffer(buffer);
  38792. };
  38793. /**
  38794. * Removes a specific vertex data
  38795. * @param kind defines the data kind (Position, normal, etc...)
  38796. */
  38797. Geometry.prototype.removeVerticesData = function (kind) {
  38798. if (this._vertexBuffers[kind]) {
  38799. this._vertexBuffers[kind].dispose();
  38800. delete this._vertexBuffers[kind];
  38801. }
  38802. };
  38803. /**
  38804. * Affect a vertex buffer to the geometry. the vertexBuffer.getKind() function is used to determine where to store the data
  38805. * @param buffer defines the vertex buffer to use
  38806. * @param totalVertices defines the total number of vertices for position kind (could be null)
  38807. */
  38808. Geometry.prototype.setVerticesBuffer = function (buffer, totalVertices) {
  38809. if (totalVertices === void 0) { totalVertices = null; }
  38810. var kind = buffer.getKind();
  38811. if (this._vertexBuffers[kind]) {
  38812. this._vertexBuffers[kind].dispose();
  38813. }
  38814. this._vertexBuffers[kind] = buffer;
  38815. if (kind === BABYLON.VertexBuffer.PositionKind) {
  38816. var data = buffer.getData();
  38817. if (totalVertices != null) {
  38818. this._totalVertices = totalVertices;
  38819. }
  38820. else {
  38821. if (data != null) {
  38822. this._totalVertices = data.length / (buffer.byteStride / 4);
  38823. }
  38824. }
  38825. this._updateExtend(data);
  38826. this._resetPointsArrayCache();
  38827. var meshes = this._meshes;
  38828. var numOfMeshes = meshes.length;
  38829. for (var index = 0; index < numOfMeshes; index++) {
  38830. var mesh = meshes[index];
  38831. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  38832. mesh._createGlobalSubMesh(false);
  38833. mesh.computeWorldMatrix(true);
  38834. }
  38835. }
  38836. this.notifyUpdate(kind);
  38837. if (this._vertexArrayObjects) {
  38838. this._disposeVertexArrayObjects();
  38839. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  38840. }
  38841. };
  38842. /**
  38843. * Update a specific vertex buffer
  38844. * This function will directly update the underlying WebGLBuffer according to the passed numeric array or Float32Array
  38845. * It will do nothing if the buffer is not updatable
  38846. * @param kind defines the data kind (Position, normal, etc...)
  38847. * @param data defines the data to use
  38848. * @param offset defines the offset in the target buffer where to store the data
  38849. * @param useBytes set to true if the offset is in bytes
  38850. */
  38851. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset, useBytes) {
  38852. if (useBytes === void 0) { useBytes = false; }
  38853. var vertexBuffer = this.getVertexBuffer(kind);
  38854. if (!vertexBuffer) {
  38855. return;
  38856. }
  38857. vertexBuffer.updateDirectly(data, offset, useBytes);
  38858. this.notifyUpdate(kind);
  38859. };
  38860. /**
  38861. * Update a specific vertex buffer
  38862. * This function will create a new buffer if the current one is not updatable
  38863. * @param kind defines the data kind (Position, normal, etc...)
  38864. * @param data defines the data to use
  38865. * @param updateExtends defines if the geometry extends must be recomputed (false by default)
  38866. */
  38867. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  38868. if (updateExtends === void 0) { updateExtends = false; }
  38869. var vertexBuffer = this.getVertexBuffer(kind);
  38870. if (!vertexBuffer) {
  38871. return;
  38872. }
  38873. vertexBuffer.update(data);
  38874. if (kind === BABYLON.VertexBuffer.PositionKind) {
  38875. this._updateBoundingInfo(updateExtends, data);
  38876. }
  38877. this.notifyUpdate(kind);
  38878. };
  38879. Geometry.prototype._updateBoundingInfo = function (updateExtends, data) {
  38880. if (updateExtends) {
  38881. this._updateExtend(data);
  38882. }
  38883. var meshes = this._meshes;
  38884. var numOfMeshes = meshes.length;
  38885. this._resetPointsArrayCache();
  38886. for (var index = 0; index < numOfMeshes; index++) {
  38887. var mesh = meshes[index];
  38888. if (updateExtends) {
  38889. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  38890. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  38891. var subMesh = mesh.subMeshes[subIndex];
  38892. subMesh.refreshBoundingInfo();
  38893. }
  38894. }
  38895. }
  38896. };
  38897. /** @hidden */
  38898. Geometry.prototype._bind = function (effect, indexToBind) {
  38899. if (!effect) {
  38900. return;
  38901. }
  38902. if (indexToBind === undefined) {
  38903. indexToBind = this._indexBuffer;
  38904. }
  38905. var vbs = this.getVertexBuffers();
  38906. if (!vbs) {
  38907. return;
  38908. }
  38909. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  38910. this._engine.bindBuffers(vbs, indexToBind, effect);
  38911. return;
  38912. }
  38913. // Using VAO
  38914. if (!this._vertexArrayObjects[effect.key]) {
  38915. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
  38916. }
  38917. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  38918. };
  38919. /**
  38920. * Gets total number of vertices
  38921. * @returns the total number of vertices
  38922. */
  38923. Geometry.prototype.getTotalVertices = function () {
  38924. if (!this.isReady()) {
  38925. return 0;
  38926. }
  38927. return this._totalVertices;
  38928. };
  38929. /**
  38930. * Gets a specific vertex data attached to this geometry. Float data is constructed if the vertex buffer data cannot be returned directly.
  38931. * @param kind defines the data kind (Position, normal, etc...)
  38932. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  38933. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  38934. * @returns a float array containing vertex data
  38935. */
  38936. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  38937. var vertexBuffer = this.getVertexBuffer(kind);
  38938. if (!vertexBuffer) {
  38939. return null;
  38940. }
  38941. var data = vertexBuffer.getData();
  38942. if (!data) {
  38943. return null;
  38944. }
  38945. var tightlyPackedByteStride = vertexBuffer.getSize() * BABYLON.VertexBuffer.GetTypeByteLength(vertexBuffer.type);
  38946. var count = this._totalVertices * vertexBuffer.getSize();
  38947. if (vertexBuffer.type !== BABYLON.VertexBuffer.FLOAT || vertexBuffer.byteStride !== tightlyPackedByteStride) {
  38948. var copy_1 = new Array(count);
  38949. vertexBuffer.forEach(count, function (value, index) {
  38950. copy_1[index] = value;
  38951. });
  38952. return copy_1;
  38953. }
  38954. if (!((data instanceof Array) || (data instanceof Float32Array)) || vertexBuffer.byteOffset !== 0 || data.length !== count) {
  38955. if (data instanceof Array) {
  38956. var offset = vertexBuffer.byteOffset / 4;
  38957. return BABYLON.Tools.Slice(data, offset, offset + count);
  38958. }
  38959. else if (data instanceof ArrayBuffer) {
  38960. return new Float32Array(data, vertexBuffer.byteOffset, count);
  38961. }
  38962. else {
  38963. var offset = data.byteOffset + vertexBuffer.byteOffset;
  38964. if (forceCopy || (copyWhenShared && this._meshes.length !== 1)) {
  38965. var result = new Float32Array(count);
  38966. var source = new Float32Array(data.buffer, offset, count);
  38967. result.set(source);
  38968. return result;
  38969. }
  38970. return new Float32Array(data.buffer, offset, count);
  38971. }
  38972. }
  38973. if (forceCopy || (copyWhenShared && this._meshes.length !== 1)) {
  38974. return BABYLON.Tools.Slice(data);
  38975. }
  38976. return data;
  38977. };
  38978. /**
  38979. * Returns a boolean defining if the vertex data for the requested `kind` is updatable
  38980. * @param kind defines the data kind (Position, normal, etc...)
  38981. * @returns true if the vertex buffer with the specified kind is updatable
  38982. */
  38983. Geometry.prototype.isVertexBufferUpdatable = function (kind) {
  38984. var vb = this._vertexBuffers[kind];
  38985. if (!vb) {
  38986. return false;
  38987. }
  38988. return vb.isUpdatable();
  38989. };
  38990. /**
  38991. * Gets a specific vertex buffer
  38992. * @param kind defines the data kind (Position, normal, etc...)
  38993. * @returns a {BABYLON.VertexBuffer}
  38994. */
  38995. Geometry.prototype.getVertexBuffer = function (kind) {
  38996. if (!this.isReady()) {
  38997. return null;
  38998. }
  38999. return this._vertexBuffers[kind];
  39000. };
  39001. /**
  39002. * Returns all vertex buffers
  39003. * @return an object holding all vertex buffers indexed by kind
  39004. */
  39005. Geometry.prototype.getVertexBuffers = function () {
  39006. if (!this.isReady()) {
  39007. return null;
  39008. }
  39009. return this._vertexBuffers;
  39010. };
  39011. /**
  39012. * Gets a boolean indicating if specific vertex buffer is present
  39013. * @param kind defines the data kind (Position, normal, etc...)
  39014. * @returns true if data is present
  39015. */
  39016. Geometry.prototype.isVerticesDataPresent = function (kind) {
  39017. if (!this._vertexBuffers) {
  39018. if (this._delayInfo) {
  39019. return this._delayInfo.indexOf(kind) !== -1;
  39020. }
  39021. return false;
  39022. }
  39023. return this._vertexBuffers[kind] !== undefined;
  39024. };
  39025. /**
  39026. * Gets a list of all attached data kinds (Position, normal, etc...)
  39027. * @returns a list of string containing all kinds
  39028. */
  39029. Geometry.prototype.getVerticesDataKinds = function () {
  39030. var result = [];
  39031. var kind;
  39032. if (!this._vertexBuffers && this._delayInfo) {
  39033. for (kind in this._delayInfo) {
  39034. result.push(kind);
  39035. }
  39036. }
  39037. else {
  39038. for (kind in this._vertexBuffers) {
  39039. result.push(kind);
  39040. }
  39041. }
  39042. return result;
  39043. };
  39044. /**
  39045. * Update index buffer
  39046. * @param indices defines the indices to store in the index buffer
  39047. * @param offset defines the offset in the target buffer where to store the data
  39048. */
  39049. Geometry.prototype.updateIndices = function (indices, offset) {
  39050. if (!this._indexBuffer) {
  39051. return;
  39052. }
  39053. if (!this._indexBufferIsUpdatable) {
  39054. this.setIndices(indices, null, true);
  39055. }
  39056. else {
  39057. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  39058. }
  39059. };
  39060. /**
  39061. * Creates a new index buffer
  39062. * @param indices defines the indices to store in the index buffer
  39063. * @param totalVertices defines the total number of vertices (could be null)
  39064. * @param updatable defines if the index buffer must be flagged as updatable (false by default)
  39065. */
  39066. Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
  39067. if (totalVertices === void 0) { totalVertices = null; }
  39068. if (updatable === void 0) { updatable = false; }
  39069. if (this._indexBuffer) {
  39070. this._engine._releaseBuffer(this._indexBuffer);
  39071. }
  39072. this._disposeVertexArrayObjects();
  39073. this._indices = indices;
  39074. this._indexBufferIsUpdatable = updatable;
  39075. if (this._meshes.length !== 0 && this._indices) {
  39076. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  39077. }
  39078. if (totalVertices != undefined) { // including null and undefined
  39079. this._totalVertices = totalVertices;
  39080. }
  39081. var meshes = this._meshes;
  39082. var numOfMeshes = meshes.length;
  39083. for (var index = 0; index < numOfMeshes; index++) {
  39084. meshes[index]._createGlobalSubMesh(true);
  39085. }
  39086. this.notifyUpdate();
  39087. };
  39088. /**
  39089. * Return the total number of indices
  39090. * @returns the total number of indices
  39091. */
  39092. Geometry.prototype.getTotalIndices = function () {
  39093. if (!this.isReady()) {
  39094. return 0;
  39095. }
  39096. return this._indices.length;
  39097. };
  39098. /**
  39099. * Gets the index buffer array
  39100. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  39101. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  39102. * @returns the index buffer array
  39103. */
  39104. Geometry.prototype.getIndices = function (copyWhenShared, forceCopy) {
  39105. if (!this.isReady()) {
  39106. return null;
  39107. }
  39108. var orig = this._indices;
  39109. if (!forceCopy && (!copyWhenShared || this._meshes.length === 1)) {
  39110. return orig;
  39111. }
  39112. else {
  39113. var len = orig.length;
  39114. var copy = [];
  39115. for (var i = 0; i < len; i++) {
  39116. copy.push(orig[i]);
  39117. }
  39118. return copy;
  39119. }
  39120. };
  39121. /**
  39122. * Gets the index buffer
  39123. * @return the index buffer
  39124. */
  39125. Geometry.prototype.getIndexBuffer = function () {
  39126. if (!this.isReady()) {
  39127. return null;
  39128. }
  39129. return this._indexBuffer;
  39130. };
  39131. /** @hidden */
  39132. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  39133. if (effect === void 0) { effect = null; }
  39134. if (!effect || !this._vertexArrayObjects) {
  39135. return;
  39136. }
  39137. if (this._vertexArrayObjects[effect.key]) {
  39138. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  39139. delete this._vertexArrayObjects[effect.key];
  39140. }
  39141. };
  39142. /**
  39143. * Release the associated resources for a specific mesh
  39144. * @param mesh defines the source mesh
  39145. * @param shouldDispose defines if the geometry must be disposed if there is no more mesh pointing to it
  39146. */
  39147. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  39148. var meshes = this._meshes;
  39149. var index = meshes.indexOf(mesh);
  39150. if (index === -1) {
  39151. return;
  39152. }
  39153. meshes.splice(index, 1);
  39154. mesh._geometry = null;
  39155. if (meshes.length === 0 && shouldDispose) {
  39156. this.dispose();
  39157. }
  39158. };
  39159. /**
  39160. * Apply current geometry to a given mesh
  39161. * @param mesh defines the mesh to apply geometry to
  39162. */
  39163. Geometry.prototype.applyToMesh = function (mesh) {
  39164. if (mesh._geometry === this) {
  39165. return;
  39166. }
  39167. var previousGeometry = mesh._geometry;
  39168. if (previousGeometry) {
  39169. previousGeometry.releaseForMesh(mesh);
  39170. }
  39171. var meshes = this._meshes;
  39172. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  39173. mesh._geometry = this;
  39174. this._scene.pushGeometry(this);
  39175. meshes.push(mesh);
  39176. if (this.isReady()) {
  39177. this._applyToMesh(mesh);
  39178. }
  39179. else {
  39180. mesh._boundingInfo = this._boundingInfo;
  39181. }
  39182. };
  39183. Geometry.prototype._updateExtend = function (data) {
  39184. if (data === void 0) { data = null; }
  39185. if (!data) {
  39186. data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  39187. }
  39188. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, 3);
  39189. };
  39190. Geometry.prototype._applyToMesh = function (mesh) {
  39191. var numOfMeshes = this._meshes.length;
  39192. // vertexBuffers
  39193. for (var kind in this._vertexBuffers) {
  39194. if (numOfMeshes === 1) {
  39195. this._vertexBuffers[kind].create();
  39196. }
  39197. var buffer = this._vertexBuffers[kind].getBuffer();
  39198. if (buffer)
  39199. buffer.references = numOfMeshes;
  39200. if (kind === BABYLON.VertexBuffer.PositionKind) {
  39201. if (!this._extend) {
  39202. this._updateExtend();
  39203. }
  39204. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39205. mesh._createGlobalSubMesh(false);
  39206. //bounding info was just created again, world matrix should be applied again.
  39207. mesh._updateBoundingInfo();
  39208. }
  39209. }
  39210. // indexBuffer
  39211. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  39212. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  39213. }
  39214. if (this._indexBuffer) {
  39215. this._indexBuffer.references = numOfMeshes;
  39216. }
  39217. };
  39218. Geometry.prototype.notifyUpdate = function (kind) {
  39219. if (this.onGeometryUpdated) {
  39220. this.onGeometryUpdated(this, kind);
  39221. }
  39222. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  39223. var mesh = _a[_i];
  39224. mesh._markSubMeshesAsAttributesDirty();
  39225. }
  39226. };
  39227. /**
  39228. * Load the geometry if it was flagged as delay loaded
  39229. * @param scene defines the hosting scene
  39230. * @param onLoaded defines a callback called when the geometry is loaded
  39231. */
  39232. Geometry.prototype.load = function (scene, onLoaded) {
  39233. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  39234. return;
  39235. }
  39236. if (this.isReady()) {
  39237. if (onLoaded) {
  39238. onLoaded();
  39239. }
  39240. return;
  39241. }
  39242. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  39243. this._queueLoad(scene, onLoaded);
  39244. };
  39245. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  39246. var _this = this;
  39247. if (!this.delayLoadingFile) {
  39248. return;
  39249. }
  39250. scene._addPendingData(this);
  39251. scene._loadFile(this.delayLoadingFile, function (data) {
  39252. if (!_this._delayLoadingFunction) {
  39253. return;
  39254. }
  39255. _this._delayLoadingFunction(JSON.parse(data), _this);
  39256. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  39257. _this._delayInfo = [];
  39258. scene._removePendingData(_this);
  39259. var meshes = _this._meshes;
  39260. var numOfMeshes = meshes.length;
  39261. for (var index = 0; index < numOfMeshes; index++) {
  39262. _this._applyToMesh(meshes[index]);
  39263. }
  39264. if (onLoaded) {
  39265. onLoaded();
  39266. }
  39267. }, undefined, true);
  39268. };
  39269. /**
  39270. * Invert the geometry to move from a right handed system to a left handed one.
  39271. */
  39272. Geometry.prototype.toLeftHanded = function () {
  39273. // Flip faces
  39274. var tIndices = this.getIndices(false);
  39275. if (tIndices != null && tIndices.length > 0) {
  39276. for (var i = 0; i < tIndices.length; i += 3) {
  39277. var tTemp = tIndices[i + 0];
  39278. tIndices[i + 0] = tIndices[i + 2];
  39279. tIndices[i + 2] = tTemp;
  39280. }
  39281. this.setIndices(tIndices);
  39282. }
  39283. // Negate position.z
  39284. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  39285. if (tPositions != null && tPositions.length > 0) {
  39286. for (var i = 0; i < tPositions.length; i += 3) {
  39287. tPositions[i + 2] = -tPositions[i + 2];
  39288. }
  39289. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  39290. }
  39291. // Negate normal.z
  39292. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  39293. if (tNormals != null && tNormals.length > 0) {
  39294. for (var i = 0; i < tNormals.length; i += 3) {
  39295. tNormals[i + 2] = -tNormals[i + 2];
  39296. }
  39297. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  39298. }
  39299. };
  39300. // Cache
  39301. /** @hidden */
  39302. Geometry.prototype._resetPointsArrayCache = function () {
  39303. this._positions = null;
  39304. };
  39305. /** @hidden */
  39306. Geometry.prototype._generatePointsArray = function () {
  39307. if (this._positions)
  39308. return true;
  39309. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  39310. if (!data || data.length === 0) {
  39311. return false;
  39312. }
  39313. this._positions = [];
  39314. for (var index = 0; index < data.length; index += 3) {
  39315. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  39316. }
  39317. return true;
  39318. };
  39319. /**
  39320. * Gets a value indicating if the geometry is disposed
  39321. * @returns true if the geometry was disposed
  39322. */
  39323. Geometry.prototype.isDisposed = function () {
  39324. return this._isDisposed;
  39325. };
  39326. Geometry.prototype._disposeVertexArrayObjects = function () {
  39327. if (this._vertexArrayObjects) {
  39328. for (var kind in this._vertexArrayObjects) {
  39329. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  39330. }
  39331. this._vertexArrayObjects = {};
  39332. }
  39333. };
  39334. /**
  39335. * Free all associated resources
  39336. */
  39337. Geometry.prototype.dispose = function () {
  39338. var meshes = this._meshes;
  39339. var numOfMeshes = meshes.length;
  39340. var index;
  39341. for (index = 0; index < numOfMeshes; index++) {
  39342. this.releaseForMesh(meshes[index]);
  39343. }
  39344. this._meshes = [];
  39345. this._disposeVertexArrayObjects();
  39346. for (var kind in this._vertexBuffers) {
  39347. this._vertexBuffers[kind].dispose();
  39348. }
  39349. this._vertexBuffers = {};
  39350. this._totalVertices = 0;
  39351. if (this._indexBuffer) {
  39352. this._engine._releaseBuffer(this._indexBuffer);
  39353. }
  39354. this._indexBuffer = null;
  39355. this._indices = [];
  39356. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  39357. this.delayLoadingFile = null;
  39358. this._delayLoadingFunction = null;
  39359. this._delayInfo = [];
  39360. this._boundingInfo = null;
  39361. this._scene.removeGeometry(this);
  39362. this._isDisposed = true;
  39363. };
  39364. /**
  39365. * Clone the current geometry into a new geometry
  39366. * @param id defines the unique ID of the new geometry
  39367. * @returns a new geometry object
  39368. */
  39369. Geometry.prototype.copy = function (id) {
  39370. var vertexData = new BABYLON.VertexData();
  39371. vertexData.indices = [];
  39372. var indices = this.getIndices();
  39373. if (indices) {
  39374. for (var index = 0; index < indices.length; index++) {
  39375. vertexData.indices.push(indices[index]);
  39376. }
  39377. }
  39378. var updatable = false;
  39379. var stopChecking = false;
  39380. var kind;
  39381. for (kind in this._vertexBuffers) {
  39382. // using slice() to make a copy of the array and not just reference it
  39383. var data = this.getVerticesData(kind);
  39384. if (data instanceof Float32Array) {
  39385. vertexData.set(new Float32Array(data), kind);
  39386. }
  39387. else {
  39388. vertexData.set(data.slice(0), kind);
  39389. }
  39390. if (!stopChecking) {
  39391. var vb = this.getVertexBuffer(kind);
  39392. if (vb) {
  39393. updatable = vb.isUpdatable();
  39394. stopChecking = !updatable;
  39395. }
  39396. }
  39397. }
  39398. var geometry = new Geometry(id, this._scene, vertexData, updatable);
  39399. geometry.delayLoadState = this.delayLoadState;
  39400. geometry.delayLoadingFile = this.delayLoadingFile;
  39401. geometry._delayLoadingFunction = this._delayLoadingFunction;
  39402. for (kind in this._delayInfo) {
  39403. geometry._delayInfo = geometry._delayInfo || [];
  39404. geometry._delayInfo.push(kind);
  39405. }
  39406. // Bounding info
  39407. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39408. return geometry;
  39409. };
  39410. /**
  39411. * Serialize the current geometry info (and not the vertices data) into a JSON object
  39412. * @return a JSON representation of the current geometry data (without the vertices data)
  39413. */
  39414. Geometry.prototype.serialize = function () {
  39415. var serializationObject = {};
  39416. serializationObject.id = this.id;
  39417. serializationObject.updatable = this._updatable;
  39418. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  39419. serializationObject.tags = BABYLON.Tags.GetTags(this);
  39420. }
  39421. return serializationObject;
  39422. };
  39423. Geometry.prototype.toNumberArray = function (origin) {
  39424. if (Array.isArray(origin)) {
  39425. return origin;
  39426. }
  39427. else {
  39428. return Array.prototype.slice.call(origin);
  39429. }
  39430. };
  39431. /**
  39432. * Serialize all vertices data into a JSON oject
  39433. * @returns a JSON representation of the current geometry data
  39434. */
  39435. Geometry.prototype.serializeVerticeData = function () {
  39436. var serializationObject = this.serialize();
  39437. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  39438. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  39439. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  39440. serializationObject.positions._updatable = true;
  39441. }
  39442. }
  39443. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  39444. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  39445. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  39446. serializationObject.normals._updatable = true;
  39447. }
  39448. }
  39449. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  39450. serializationObject.tangets = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  39451. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.TangentKind)) {
  39452. serializationObject.tangets._updatable = true;
  39453. }
  39454. }
  39455. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  39456. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  39457. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {
  39458. serializationObject.uvs._updatable = true;
  39459. }
  39460. }
  39461. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  39462. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  39463. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {
  39464. serializationObject.uv2s._updatable = true;
  39465. }
  39466. }
  39467. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  39468. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  39469. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {
  39470. serializationObject.uv3s._updatable = true;
  39471. }
  39472. }
  39473. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  39474. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  39475. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {
  39476. serializationObject.uv4s._updatable = true;
  39477. }
  39478. }
  39479. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  39480. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  39481. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {
  39482. serializationObject.uv5s._updatable = true;
  39483. }
  39484. }
  39485. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  39486. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  39487. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {
  39488. serializationObject.uv6s._updatable = true;
  39489. }
  39490. }
  39491. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  39492. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  39493. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {
  39494. serializationObject.colors._updatable = true;
  39495. }
  39496. }
  39497. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  39498. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  39499. serializationObject.matricesIndices._isExpanded = true;
  39500. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  39501. serializationObject.matricesIndices._updatable = true;
  39502. }
  39503. }
  39504. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  39505. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  39506. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  39507. serializationObject.matricesWeights._updatable = true;
  39508. }
  39509. }
  39510. serializationObject.indices = this.toNumberArray(this.getIndices());
  39511. return serializationObject;
  39512. };
  39513. // Statics
  39514. /**
  39515. * Extracts a clone of a mesh geometry
  39516. * @param mesh defines the source mesh
  39517. * @param id defines the unique ID of the new geometry object
  39518. * @returns the new geometry object
  39519. */
  39520. Geometry.ExtractFromMesh = function (mesh, id) {
  39521. var geometry = mesh._geometry;
  39522. if (!geometry) {
  39523. return null;
  39524. }
  39525. return geometry.copy(id);
  39526. };
  39527. /**
  39528. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  39529. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  39530. * Be aware Math.random() could cause collisions, but:
  39531. * "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"
  39532. * @returns a string containing a new GUID
  39533. */
  39534. Geometry.RandomId = function () {
  39535. return BABYLON.Tools.RandomId();
  39536. };
  39537. /** @hidden */
  39538. Geometry._ImportGeometry = function (parsedGeometry, mesh) {
  39539. var scene = mesh.getScene();
  39540. // Geometry
  39541. var geometryId = parsedGeometry.geometryId;
  39542. if (geometryId) {
  39543. var geometry = scene.getGeometryByID(geometryId);
  39544. if (geometry) {
  39545. geometry.applyToMesh(mesh);
  39546. }
  39547. }
  39548. else if (parsedGeometry instanceof ArrayBuffer) {
  39549. var binaryInfo = mesh._binaryInfo;
  39550. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  39551. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  39552. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  39553. }
  39554. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  39555. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  39556. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  39557. }
  39558. if (binaryInfo.tangetsAttrDesc && binaryInfo.tangetsAttrDesc.count > 0) {
  39559. var tangentsData = new Float32Array(parsedGeometry, binaryInfo.tangetsAttrDesc.offset, binaryInfo.tangetsAttrDesc.count);
  39560. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, tangentsData, false);
  39561. }
  39562. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  39563. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  39564. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  39565. }
  39566. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  39567. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  39568. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  39569. }
  39570. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  39571. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  39572. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  39573. }
  39574. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  39575. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  39576. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  39577. }
  39578. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  39579. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  39580. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  39581. }
  39582. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  39583. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  39584. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  39585. }
  39586. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  39587. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  39588. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  39589. }
  39590. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  39591. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  39592. var floatIndices = [];
  39593. for (var i = 0; i < matricesIndicesData.length; i++) {
  39594. var index = matricesIndicesData[i];
  39595. floatIndices.push(index & 0x000000FF);
  39596. floatIndices.push((index & 0x0000FF00) >> 8);
  39597. floatIndices.push((index & 0x00FF0000) >> 16);
  39598. floatIndices.push(index >> 24);
  39599. }
  39600. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  39601. }
  39602. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  39603. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  39604. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  39605. }
  39606. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  39607. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  39608. mesh.setIndices(indicesData, null);
  39609. }
  39610. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  39611. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  39612. mesh.subMeshes = [];
  39613. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  39614. var materialIndex = subMeshesData[(i * 5) + 0];
  39615. var verticesStart = subMeshesData[(i * 5) + 1];
  39616. var verticesCount = subMeshesData[(i * 5) + 2];
  39617. var indexStart = subMeshesData[(i * 5) + 3];
  39618. var indexCount = subMeshesData[(i * 5) + 4];
  39619. BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  39620. }
  39621. }
  39622. }
  39623. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  39624. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  39625. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  39626. if (parsedGeometry.tangents) {
  39627. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, parsedGeometry.tangents, parsedGeometry.tangents._updatable);
  39628. }
  39629. if (parsedGeometry.uvs) {
  39630. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  39631. }
  39632. if (parsedGeometry.uvs2) {
  39633. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  39634. }
  39635. if (parsedGeometry.uvs3) {
  39636. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  39637. }
  39638. if (parsedGeometry.uvs4) {
  39639. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  39640. }
  39641. if (parsedGeometry.uvs5) {
  39642. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  39643. }
  39644. if (parsedGeometry.uvs6) {
  39645. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  39646. }
  39647. if (parsedGeometry.colors) {
  39648. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  39649. }
  39650. if (parsedGeometry.matricesIndices) {
  39651. if (!parsedGeometry.matricesIndices._isExpanded) {
  39652. var floatIndices = [];
  39653. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  39654. var matricesIndex = parsedGeometry.matricesIndices[i];
  39655. floatIndices.push(matricesIndex & 0x000000FF);
  39656. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  39657. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  39658. floatIndices.push(matricesIndex >> 24);
  39659. }
  39660. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  39661. }
  39662. else {
  39663. delete parsedGeometry.matricesIndices._isExpanded;
  39664. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  39665. }
  39666. }
  39667. if (parsedGeometry.matricesIndicesExtra) {
  39668. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  39669. var floatIndices = [];
  39670. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  39671. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  39672. floatIndices.push(matricesIndex & 0x000000FF);
  39673. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  39674. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  39675. floatIndices.push(matricesIndex >> 24);
  39676. }
  39677. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  39678. }
  39679. else {
  39680. delete parsedGeometry.matricesIndices._isExpanded;
  39681. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  39682. }
  39683. }
  39684. if (parsedGeometry.matricesWeights) {
  39685. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  39686. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  39687. }
  39688. if (parsedGeometry.matricesWeightsExtra) {
  39689. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  39690. }
  39691. mesh.setIndices(parsedGeometry.indices, null);
  39692. }
  39693. // SubMeshes
  39694. if (parsedGeometry.subMeshes) {
  39695. mesh.subMeshes = [];
  39696. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  39697. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  39698. BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  39699. }
  39700. }
  39701. // Flat shading
  39702. if (mesh._shouldGenerateFlatShading) {
  39703. mesh.convertToFlatShadedMesh();
  39704. delete mesh._shouldGenerateFlatShading;
  39705. }
  39706. // Update
  39707. mesh.computeWorldMatrix(true);
  39708. scene.onMeshImportedObservable.notifyObservers(mesh);
  39709. };
  39710. Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
  39711. var epsilon = 1e-3;
  39712. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  39713. return;
  39714. }
  39715. var noInfluenceBoneIndex = 0.0;
  39716. if (parsedGeometry.skeletonId > -1) {
  39717. var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  39718. if (!skeleton) {
  39719. return;
  39720. }
  39721. noInfluenceBoneIndex = skeleton.bones.length;
  39722. }
  39723. else {
  39724. return;
  39725. }
  39726. var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  39727. var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  39728. var matricesWeights = parsedGeometry.matricesWeights;
  39729. var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  39730. var influencers = parsedGeometry.numBoneInfluencer;
  39731. var size = matricesWeights.length;
  39732. for (var i = 0; i < size; i += 4) {
  39733. var weight = 0.0;
  39734. var firstZeroWeight = -1;
  39735. for (var j = 0; j < 4; j++) {
  39736. var w = matricesWeights[i + j];
  39737. weight += w;
  39738. if (w < epsilon && firstZeroWeight < 0) {
  39739. firstZeroWeight = j;
  39740. }
  39741. }
  39742. if (matricesWeightsExtra) {
  39743. for (var j = 0; j < 4; j++) {
  39744. var w = matricesWeightsExtra[i + j];
  39745. weight += w;
  39746. if (w < epsilon && firstZeroWeight < 0) {
  39747. firstZeroWeight = j + 4;
  39748. }
  39749. }
  39750. }
  39751. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  39752. firstZeroWeight = influencers - 1;
  39753. }
  39754. if (weight > epsilon) {
  39755. var mweight = 1.0 / weight;
  39756. for (var j = 0; j < 4; j++) {
  39757. matricesWeights[i + j] *= mweight;
  39758. }
  39759. if (matricesWeightsExtra) {
  39760. for (var j = 0; j < 4; j++) {
  39761. matricesWeightsExtra[i + j] *= mweight;
  39762. }
  39763. }
  39764. }
  39765. else {
  39766. if (firstZeroWeight >= 4) {
  39767. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  39768. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  39769. }
  39770. else {
  39771. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  39772. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  39773. }
  39774. }
  39775. }
  39776. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  39777. if (parsedGeometry.matricesWeightsExtra) {
  39778. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  39779. }
  39780. };
  39781. /**
  39782. * Create a new geometry from persisted data (Using .babylon file format)
  39783. * @param parsedVertexData defines the persisted data
  39784. * @param scene defines the hosting scene
  39785. * @param rootUrl defines the root url to use to load assets (like delayed data)
  39786. * @returns the new geometry object
  39787. */
  39788. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  39789. if (scene.getGeometryByID(parsedVertexData.id)) {
  39790. return null; // null since geometry could be something else than a box...
  39791. }
  39792. var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
  39793. if (BABYLON.Tags) {
  39794. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  39795. }
  39796. if (parsedVertexData.delayLoadingFile) {
  39797. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  39798. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  39799. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  39800. geometry._delayInfo = [];
  39801. if (parsedVertexData.hasUVs) {
  39802. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  39803. }
  39804. if (parsedVertexData.hasUVs2) {
  39805. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  39806. }
  39807. if (parsedVertexData.hasUVs3) {
  39808. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  39809. }
  39810. if (parsedVertexData.hasUVs4) {
  39811. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  39812. }
  39813. if (parsedVertexData.hasUVs5) {
  39814. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  39815. }
  39816. if (parsedVertexData.hasUVs6) {
  39817. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  39818. }
  39819. if (parsedVertexData.hasColors) {
  39820. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  39821. }
  39822. if (parsedVertexData.hasMatricesIndices) {
  39823. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  39824. }
  39825. if (parsedVertexData.hasMatricesWeights) {
  39826. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  39827. }
  39828. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  39829. }
  39830. else {
  39831. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  39832. }
  39833. scene.pushGeometry(geometry, true);
  39834. return geometry;
  39835. };
  39836. return Geometry;
  39837. }());
  39838. BABYLON.Geometry = Geometry;
  39839. // Primitives
  39840. /// Abstract class
  39841. /**
  39842. * Abstract class used to provide common services for all typed geometries
  39843. * @hidden
  39844. */
  39845. var _PrimitiveGeometry = /** @class */ (function (_super) {
  39846. __extends(_PrimitiveGeometry, _super);
  39847. /**
  39848. * Creates a new typed geometry
  39849. * @param id defines the unique ID of the geometry
  39850. * @param scene defines the hosting scene
  39851. * @param _canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39852. * @param mesh defines the hosting mesh (can be null)
  39853. */
  39854. function _PrimitiveGeometry(id, scene, _canBeRegenerated, mesh) {
  39855. if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }
  39856. if (mesh === void 0) { mesh = null; }
  39857. var _this = _super.call(this, id, scene, undefined, false, mesh) || this;
  39858. _this._canBeRegenerated = _canBeRegenerated;
  39859. _this._beingRegenerated = true;
  39860. _this.regenerate();
  39861. _this._beingRegenerated = false;
  39862. return _this;
  39863. }
  39864. /**
  39865. * Gets a value indicating if the geometry supports being regenerated with new parameters (false by default)
  39866. * @returns true if the geometry can be regenerated
  39867. */
  39868. _PrimitiveGeometry.prototype.canBeRegenerated = function () {
  39869. return this._canBeRegenerated;
  39870. };
  39871. /**
  39872. * If the geometry supports regeneration, the function will recreates the geometry with updated parameter values
  39873. */
  39874. _PrimitiveGeometry.prototype.regenerate = function () {
  39875. if (!this._canBeRegenerated) {
  39876. return;
  39877. }
  39878. this._beingRegenerated = true;
  39879. this.setAllVerticesData(this._regenerateVertexData(), false);
  39880. this._beingRegenerated = false;
  39881. };
  39882. /**
  39883. * Clone the geometry
  39884. * @param id defines the unique ID of the new geometry
  39885. * @returns the new geometry
  39886. */
  39887. _PrimitiveGeometry.prototype.asNewGeometry = function (id) {
  39888. return _super.prototype.copy.call(this, id);
  39889. };
  39890. // overrides
  39891. _PrimitiveGeometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  39892. if (!this._beingRegenerated) {
  39893. return;
  39894. }
  39895. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  39896. };
  39897. _PrimitiveGeometry.prototype.setVerticesData = function (kind, data, updatable) {
  39898. if (!this._beingRegenerated) {
  39899. return;
  39900. }
  39901. _super.prototype.setVerticesData.call(this, kind, data, false);
  39902. };
  39903. // to override
  39904. /** @hidden */
  39905. _PrimitiveGeometry.prototype._regenerateVertexData = function () {
  39906. throw new Error("Abstract method");
  39907. };
  39908. _PrimitiveGeometry.prototype.copy = function (id) {
  39909. throw new Error("Must be overriden in sub-classes.");
  39910. };
  39911. _PrimitiveGeometry.prototype.serialize = function () {
  39912. var serializationObject = _super.prototype.serialize.call(this);
  39913. serializationObject.canBeRegenerated = this.canBeRegenerated();
  39914. return serializationObject;
  39915. };
  39916. return _PrimitiveGeometry;
  39917. }(Geometry));
  39918. BABYLON._PrimitiveGeometry = _PrimitiveGeometry;
  39919. /**
  39920. * Creates a ribbon geometry
  39921. * @description See http://doc.babylonjs.com/how_to/ribbon_tutorial, http://doc.babylonjs.com/resources/maths_make_ribbons
  39922. */
  39923. var RibbonGeometry = /** @class */ (function (_super) {
  39924. __extends(RibbonGeometry, _super);
  39925. /**
  39926. * Creates a ribbon geometry
  39927. * @param id defines the unique ID of the geometry
  39928. * @param scene defines the hosting scene
  39929. * @param pathArray defines the array of paths to use
  39930. * @param closeArray defines if the last path and the first path must be joined
  39931. * @param closePath defines if the last and first points of each path in your pathArray must be joined
  39932. * @param offset defines the offset between points
  39933. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39934. * @param mesh defines the hosting mesh (can be null)
  39935. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39936. */
  39937. function RibbonGeometry(id, scene,
  39938. /**
  39939. * Defines the array of paths to use
  39940. */
  39941. pathArray,
  39942. /**
  39943. * Defines if the last and first points of each path in your pathArray must be joined
  39944. */
  39945. closeArray,
  39946. /**
  39947. * Defines if the last and first points of each path in your pathArray must be joined
  39948. */
  39949. closePath,
  39950. /**
  39951. * Defines the offset between points
  39952. */
  39953. offset, canBeRegenerated, mesh,
  39954. /**
  39955. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39956. */
  39957. side) {
  39958. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39959. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39960. _this.pathArray = pathArray;
  39961. _this.closeArray = closeArray;
  39962. _this.closePath = closePath;
  39963. _this.offset = offset;
  39964. _this.side = side;
  39965. return _this;
  39966. }
  39967. /** @hidden */
  39968. RibbonGeometry.prototype._regenerateVertexData = function () {
  39969. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  39970. };
  39971. RibbonGeometry.prototype.copy = function (id) {
  39972. return new RibbonGeometry(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
  39973. };
  39974. return RibbonGeometry;
  39975. }(_PrimitiveGeometry));
  39976. BABYLON.RibbonGeometry = RibbonGeometry;
  39977. /**
  39978. * Creates a box geometry
  39979. * @description see http://doc.babylonjs.com/how_to/set_shapes#box
  39980. */
  39981. var BoxGeometry = /** @class */ (function (_super) {
  39982. __extends(BoxGeometry, _super);
  39983. /**
  39984. * Creates a box geometry
  39985. * @param id defines the unique ID of the geometry
  39986. * @param scene defines the hosting scene
  39987. * @param size defines the zise of the box (width, height and depth are the same)
  39988. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39989. * @param mesh defines the hosting mesh (can be null)
  39990. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39991. */
  39992. function BoxGeometry(id, scene,
  39993. /**
  39994. * Defines the zise of the box (width, height and depth are the same)
  39995. */
  39996. size, canBeRegenerated, mesh,
  39997. /**
  39998. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39999. */
  40000. side) {
  40001. if (mesh === void 0) { mesh = null; }
  40002. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40003. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40004. _this.size = size;
  40005. _this.side = side;
  40006. return _this;
  40007. }
  40008. /** @hidden */
  40009. BoxGeometry.prototype._regenerateVertexData = function () {
  40010. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  40011. };
  40012. BoxGeometry.prototype.copy = function (id) {
  40013. return new BoxGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
  40014. };
  40015. BoxGeometry.prototype.serialize = function () {
  40016. var serializationObject = _super.prototype.serialize.call(this);
  40017. serializationObject.size = this.size;
  40018. return serializationObject;
  40019. };
  40020. BoxGeometry.Parse = function (parsedBox, scene) {
  40021. if (scene.getGeometryByID(parsedBox.id)) {
  40022. return null; // null since geometry could be something else than a box...
  40023. }
  40024. var box = new BoxGeometry(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  40025. if (BABYLON.Tags) {
  40026. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  40027. }
  40028. scene.pushGeometry(box, true);
  40029. return box;
  40030. };
  40031. return BoxGeometry;
  40032. }(_PrimitiveGeometry));
  40033. BABYLON.BoxGeometry = BoxGeometry;
  40034. /**
  40035. * Creates a sphere geometry
  40036. * @description see http://doc.babylonjs.com/how_to/set_shapes#sphere
  40037. */
  40038. var SphereGeometry = /** @class */ (function (_super) {
  40039. __extends(SphereGeometry, _super);
  40040. /**
  40041. * Create a new sphere geometry
  40042. * @param id defines the unique ID of the geometry
  40043. * @param scene defines the hosting scene
  40044. * @param segments defines the number of segments to use to create the sphere
  40045. * @param diameter defines the diameter of the sphere
  40046. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40047. * @param mesh defines the hosting mesh (can be null)
  40048. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40049. */
  40050. function SphereGeometry(id, scene,
  40051. /**
  40052. * Defines the number of segments to use to create the sphere
  40053. */
  40054. segments,
  40055. /**
  40056. * Defines the diameter of the sphere
  40057. */
  40058. diameter, canBeRegenerated, mesh,
  40059. /**
  40060. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40061. */
  40062. side) {
  40063. if (mesh === void 0) { mesh = null; }
  40064. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40065. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40066. _this.segments = segments;
  40067. _this.diameter = diameter;
  40068. _this.side = side;
  40069. return _this;
  40070. }
  40071. /** @hidden */
  40072. SphereGeometry.prototype._regenerateVertexData = function () {
  40073. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  40074. };
  40075. SphereGeometry.prototype.copy = function (id) {
  40076. return new SphereGeometry(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  40077. };
  40078. SphereGeometry.prototype.serialize = function () {
  40079. var serializationObject = _super.prototype.serialize.call(this);
  40080. serializationObject.segments = this.segments;
  40081. serializationObject.diameter = this.diameter;
  40082. return serializationObject;
  40083. };
  40084. SphereGeometry.Parse = function (parsedSphere, scene) {
  40085. if (scene.getGeometryByID(parsedSphere.id)) {
  40086. return null; // null since geometry could be something else than a sphere...
  40087. }
  40088. var sphere = new SphereGeometry(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  40089. if (BABYLON.Tags) {
  40090. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  40091. }
  40092. scene.pushGeometry(sphere, true);
  40093. return sphere;
  40094. };
  40095. return SphereGeometry;
  40096. }(_PrimitiveGeometry));
  40097. BABYLON.SphereGeometry = SphereGeometry;
  40098. /**
  40099. * Creates a disc geometry
  40100. * @description see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  40101. */
  40102. var DiscGeometry = /** @class */ (function (_super) {
  40103. __extends(DiscGeometry, _super);
  40104. /**
  40105. * Creates a new disc geometry
  40106. * @param id defines the unique ID of the geometry
  40107. * @param scene defines the hosting scene
  40108. * @param radius defines the radius of the disc
  40109. * @param tessellation defines the tesselation factor to apply to the disc
  40110. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40111. * @param mesh defines the hosting mesh (can be null)
  40112. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40113. */
  40114. function DiscGeometry(id, scene,
  40115. /**
  40116. * Defines the radius of the disc
  40117. */
  40118. radius,
  40119. /**
  40120. * Defines the tesselation factor to apply to the disc
  40121. */
  40122. tessellation, canBeRegenerated, mesh,
  40123. /**
  40124. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40125. */
  40126. side) {
  40127. if (mesh === void 0) { mesh = null; }
  40128. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40129. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40130. _this.radius = radius;
  40131. _this.tessellation = tessellation;
  40132. _this.side = side;
  40133. return _this;
  40134. }
  40135. /** @hidden */
  40136. DiscGeometry.prototype._regenerateVertexData = function () {
  40137. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  40138. };
  40139. DiscGeometry.prototype.copy = function (id) {
  40140. return new DiscGeometry(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  40141. };
  40142. return DiscGeometry;
  40143. }(_PrimitiveGeometry));
  40144. BABYLON.DiscGeometry = DiscGeometry;
  40145. /**
  40146. * Creates a new cylinder geometry
  40147. * @description see http://doc.babylonjs.com/how_to/set_shapes#cylinder-or-cone
  40148. */
  40149. var CylinderGeometry = /** @class */ (function (_super) {
  40150. __extends(CylinderGeometry, _super);
  40151. /**
  40152. * Creates a new cylinder geometry
  40153. * @param id defines the unique ID of the geometry
  40154. * @param scene defines the hosting scene
  40155. * @param height defines the height of the cylinder
  40156. * @param diameterTop defines the diameter of the cylinder's top cap
  40157. * @param diameterBottom defines the diameter of the cylinder's bottom cap
  40158. * @param tessellation defines the tessellation factor to apply to the cylinder (number of radial sides)
  40159. * @param subdivisions defines the number of subdivisions to apply to the cylinder (number of rings) (1 by default)
  40160. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40161. * @param mesh defines the hosting mesh (can be null)
  40162. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40163. */
  40164. function CylinderGeometry(id, scene,
  40165. /**
  40166. * Defines the height of the cylinder
  40167. */
  40168. height,
  40169. /**
  40170. * Defines the diameter of the cylinder's top cap
  40171. */
  40172. diameterTop,
  40173. /**
  40174. * Defines the diameter of the cylinder's bottom cap
  40175. */
  40176. diameterBottom,
  40177. /**
  40178. * Defines the tessellation factor to apply to the cylinder
  40179. */
  40180. tessellation,
  40181. /**
  40182. * Defines the number of subdivisions to apply to the cylinder (1 by default)
  40183. */
  40184. subdivisions, canBeRegenerated, mesh,
  40185. /**
  40186. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40187. */
  40188. side) {
  40189. if (subdivisions === void 0) { subdivisions = 1; }
  40190. if (mesh === void 0) { mesh = null; }
  40191. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40192. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40193. _this.height = height;
  40194. _this.diameterTop = diameterTop;
  40195. _this.diameterBottom = diameterBottom;
  40196. _this.tessellation = tessellation;
  40197. _this.subdivisions = subdivisions;
  40198. _this.side = side;
  40199. return _this;
  40200. }
  40201. /** @hidden */
  40202. CylinderGeometry.prototype._regenerateVertexData = function () {
  40203. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  40204. };
  40205. CylinderGeometry.prototype.copy = function (id) {
  40206. return new CylinderGeometry(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  40207. };
  40208. CylinderGeometry.prototype.serialize = function () {
  40209. var serializationObject = _super.prototype.serialize.call(this);
  40210. serializationObject.height = this.height;
  40211. serializationObject.diameterTop = this.diameterTop;
  40212. serializationObject.diameterBottom = this.diameterBottom;
  40213. serializationObject.tessellation = this.tessellation;
  40214. return serializationObject;
  40215. };
  40216. CylinderGeometry.Parse = function (parsedCylinder, scene) {
  40217. if (scene.getGeometryByID(parsedCylinder.id)) {
  40218. return null; // null since geometry could be something else than a cylinder...
  40219. }
  40220. var cylinder = new CylinderGeometry(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  40221. if (BABYLON.Tags) {
  40222. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  40223. }
  40224. scene.pushGeometry(cylinder, true);
  40225. return cylinder;
  40226. };
  40227. return CylinderGeometry;
  40228. }(_PrimitiveGeometry));
  40229. BABYLON.CylinderGeometry = CylinderGeometry;
  40230. /**
  40231. * Creates a new torus geometry
  40232. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus
  40233. */
  40234. var TorusGeometry = /** @class */ (function (_super) {
  40235. __extends(TorusGeometry, _super);
  40236. /**
  40237. * Creates a new torus geometry
  40238. * @param id defines the unique ID of the geometry
  40239. * @param scene defines the hosting scene
  40240. * @param diameter defines the diameter of the torus
  40241. * @param thickness defines the thickness of the torus (ie. internal diameter)
  40242. * @param tessellation defines the tesselation factor to apply to the torus (number of segments along the circle)
  40243. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40244. * @param mesh defines the hosting mesh (can be null)
  40245. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40246. */
  40247. function TorusGeometry(id, scene,
  40248. /**
  40249. * Defines the diameter of the torus
  40250. */
  40251. diameter,
  40252. /**
  40253. * Defines the thickness of the torus (ie. internal diameter)
  40254. */
  40255. thickness,
  40256. /**
  40257. * Defines the tesselation factor to apply to the torus
  40258. */
  40259. tessellation, canBeRegenerated, mesh,
  40260. /**
  40261. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40262. */
  40263. side) {
  40264. if (mesh === void 0) { mesh = null; }
  40265. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40266. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40267. _this.diameter = diameter;
  40268. _this.thickness = thickness;
  40269. _this.tessellation = tessellation;
  40270. _this.side = side;
  40271. return _this;
  40272. }
  40273. /** @hidden */
  40274. TorusGeometry.prototype._regenerateVertexData = function () {
  40275. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  40276. };
  40277. TorusGeometry.prototype.copy = function (id) {
  40278. return new TorusGeometry(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  40279. };
  40280. TorusGeometry.prototype.serialize = function () {
  40281. var serializationObject = _super.prototype.serialize.call(this);
  40282. serializationObject.diameter = this.diameter;
  40283. serializationObject.thickness = this.thickness;
  40284. serializationObject.tessellation = this.tessellation;
  40285. return serializationObject;
  40286. };
  40287. TorusGeometry.Parse = function (parsedTorus, scene) {
  40288. if (scene.getGeometryByID(parsedTorus.id)) {
  40289. return null; // null since geometry could be something else than a torus...
  40290. }
  40291. var torus = new TorusGeometry(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  40292. if (BABYLON.Tags) {
  40293. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  40294. }
  40295. scene.pushGeometry(torus, true);
  40296. return torus;
  40297. };
  40298. return TorusGeometry;
  40299. }(_PrimitiveGeometry));
  40300. BABYLON.TorusGeometry = TorusGeometry;
  40301. /**
  40302. * Creates a new ground geometry
  40303. * @description see http://doc.babylonjs.com/how_to/set_shapes#ground
  40304. */
  40305. var GroundGeometry = /** @class */ (function (_super) {
  40306. __extends(GroundGeometry, _super);
  40307. /**
  40308. * Creates a new ground geometry
  40309. * @param id defines the unique ID of the geometry
  40310. * @param scene defines the hosting scene
  40311. * @param width defines the width of the ground
  40312. * @param height defines the height of the ground
  40313. * @param subdivisions defines the subdivisions to apply to the ground
  40314. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40315. * @param mesh defines the hosting mesh (can be null)
  40316. */
  40317. function GroundGeometry(id, scene,
  40318. /**
  40319. * Defines the width of the ground
  40320. */
  40321. width,
  40322. /**
  40323. * Defines the height of the ground
  40324. */
  40325. height,
  40326. /**
  40327. * Defines the subdivisions to apply to the ground
  40328. */
  40329. subdivisions, canBeRegenerated, mesh) {
  40330. if (mesh === void 0) { mesh = null; }
  40331. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40332. _this.width = width;
  40333. _this.height = height;
  40334. _this.subdivisions = subdivisions;
  40335. return _this;
  40336. }
  40337. /** @hidden */
  40338. GroundGeometry.prototype._regenerateVertexData = function () {
  40339. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  40340. };
  40341. GroundGeometry.prototype.copy = function (id) {
  40342. return new GroundGeometry(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  40343. };
  40344. GroundGeometry.prototype.serialize = function () {
  40345. var serializationObject = _super.prototype.serialize.call(this);
  40346. serializationObject.width = this.width;
  40347. serializationObject.height = this.height;
  40348. serializationObject.subdivisions = this.subdivisions;
  40349. return serializationObject;
  40350. };
  40351. GroundGeometry.Parse = function (parsedGround, scene) {
  40352. if (scene.getGeometryByID(parsedGround.id)) {
  40353. return null; // null since geometry could be something else than a ground...
  40354. }
  40355. var ground = new GroundGeometry(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  40356. if (BABYLON.Tags) {
  40357. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  40358. }
  40359. scene.pushGeometry(ground, true);
  40360. return ground;
  40361. };
  40362. return GroundGeometry;
  40363. }(_PrimitiveGeometry));
  40364. BABYLON.GroundGeometry = GroundGeometry;
  40365. /**
  40366. * Creates a tiled ground geometry
  40367. * @description see http://doc.babylonjs.com/how_to/set_shapes#tiled-ground
  40368. */
  40369. var TiledGroundGeometry = /** @class */ (function (_super) {
  40370. __extends(TiledGroundGeometry, _super);
  40371. /**
  40372. * Creates a tiled ground geometry
  40373. * @param id defines the unique ID of the geometry
  40374. * @param scene defines the hosting scene
  40375. * @param xmin defines the minimum value on X axis
  40376. * @param zmin defines the minimum value on Z axis
  40377. * @param xmax defines the maximum value on X axis
  40378. * @param zmax defines the maximum value on Z axis
  40379. * @param subdivisions defines the subdivisions to apply to the ground (number of subdivisions (tiles) on the height and the width of the map)
  40380. * @param precision defines the precision to use when computing the tiles
  40381. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40382. * @param mesh defines the hosting mesh (can be null)
  40383. */
  40384. function TiledGroundGeometry(id, scene,
  40385. /**
  40386. * Defines the minimum value on X axis
  40387. */
  40388. xmin,
  40389. /**
  40390. * Defines the minimum value on Z axis
  40391. */
  40392. zmin,
  40393. /**
  40394. * Defines the maximum value on X axis
  40395. */
  40396. xmax,
  40397. /**
  40398. * Defines the maximum value on Z axis
  40399. */
  40400. zmax,
  40401. /**
  40402. * Defines the subdivisions to apply to the ground
  40403. */
  40404. subdivisions,
  40405. /**
  40406. * Defines the precision to use when computing the tiles
  40407. */
  40408. precision, canBeRegenerated, mesh) {
  40409. if (mesh === void 0) { mesh = null; }
  40410. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40411. _this.xmin = xmin;
  40412. _this.zmin = zmin;
  40413. _this.xmax = xmax;
  40414. _this.zmax = zmax;
  40415. _this.subdivisions = subdivisions;
  40416. _this.precision = precision;
  40417. return _this;
  40418. }
  40419. /** @hidden */
  40420. TiledGroundGeometry.prototype._regenerateVertexData = function () {
  40421. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  40422. };
  40423. TiledGroundGeometry.prototype.copy = function (id) {
  40424. return new TiledGroundGeometry(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  40425. };
  40426. return TiledGroundGeometry;
  40427. }(_PrimitiveGeometry));
  40428. BABYLON.TiledGroundGeometry = TiledGroundGeometry;
  40429. /**
  40430. * Creates a plane geometry
  40431. * @description see http://doc.babylonjs.com/how_to/set_shapes#plane
  40432. */
  40433. var PlaneGeometry = /** @class */ (function (_super) {
  40434. __extends(PlaneGeometry, _super);
  40435. /**
  40436. * Creates a plane geometry
  40437. * @param id defines the unique ID of the geometry
  40438. * @param scene defines the hosting scene
  40439. * @param size defines the size of the plane (width === height)
  40440. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40441. * @param mesh defines the hosting mesh (can be null)
  40442. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40443. */
  40444. function PlaneGeometry(id, scene,
  40445. /**
  40446. * Defines the size of the plane (width === height)
  40447. */
  40448. size, canBeRegenerated, mesh,
  40449. /**
  40450. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40451. */
  40452. side) {
  40453. if (mesh === void 0) { mesh = null; }
  40454. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40455. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40456. _this.size = size;
  40457. _this.side = side;
  40458. return _this;
  40459. }
  40460. /** @hidden */
  40461. PlaneGeometry.prototype._regenerateVertexData = function () {
  40462. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  40463. };
  40464. PlaneGeometry.prototype.copy = function (id) {
  40465. return new PlaneGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  40466. };
  40467. PlaneGeometry.prototype.serialize = function () {
  40468. var serializationObject = _super.prototype.serialize.call(this);
  40469. serializationObject.size = this.size;
  40470. return serializationObject;
  40471. };
  40472. PlaneGeometry.Parse = function (parsedPlane, scene) {
  40473. if (scene.getGeometryByID(parsedPlane.id)) {
  40474. return null; // null since geometry could be something else than a ground...
  40475. }
  40476. var plane = new PlaneGeometry(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  40477. if (BABYLON.Tags) {
  40478. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  40479. }
  40480. scene.pushGeometry(plane, true);
  40481. return plane;
  40482. };
  40483. return PlaneGeometry;
  40484. }(_PrimitiveGeometry));
  40485. BABYLON.PlaneGeometry = PlaneGeometry;
  40486. /**
  40487. * Creates a torus knot geometry
  40488. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus-knot
  40489. */
  40490. var TorusKnotGeometry = /** @class */ (function (_super) {
  40491. __extends(TorusKnotGeometry, _super);
  40492. /**
  40493. * Creates a torus knot geometry
  40494. * @param id defines the unique ID of the geometry
  40495. * @param scene defines the hosting scene
  40496. * @param radius defines the radius of the torus knot
  40497. * @param tube defines the thickness of the torus knot tube
  40498. * @param radialSegments defines the number of radial segments
  40499. * @param tubularSegments defines the number of tubular segments
  40500. * @param p defines the first number of windings
  40501. * @param q defines the second number of windings
  40502. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40503. * @param mesh defines the hosting mesh (can be null)
  40504. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40505. */
  40506. function TorusKnotGeometry(id, scene,
  40507. /**
  40508. * Defines the radius of the torus knot
  40509. */
  40510. radius,
  40511. /**
  40512. * Defines the thickness of the torus knot tube
  40513. */
  40514. tube,
  40515. /**
  40516. * Defines the number of radial segments
  40517. */
  40518. radialSegments,
  40519. /**
  40520. * Defines the number of tubular segments
  40521. */
  40522. tubularSegments,
  40523. /**
  40524. * Defines the first number of windings
  40525. */
  40526. p,
  40527. /**
  40528. * Defines the second number of windings
  40529. */
  40530. q, canBeRegenerated, mesh,
  40531. /**
  40532. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40533. */
  40534. side) {
  40535. if (mesh === void 0) { mesh = null; }
  40536. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40537. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40538. _this.radius = radius;
  40539. _this.tube = tube;
  40540. _this.radialSegments = radialSegments;
  40541. _this.tubularSegments = tubularSegments;
  40542. _this.p = p;
  40543. _this.q = q;
  40544. _this.side = side;
  40545. return _this;
  40546. }
  40547. /** @hidden */
  40548. TorusKnotGeometry.prototype._regenerateVertexData = function () {
  40549. 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 });
  40550. };
  40551. TorusKnotGeometry.prototype.copy = function (id) {
  40552. return new TorusKnotGeometry(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  40553. };
  40554. TorusKnotGeometry.prototype.serialize = function () {
  40555. var serializationObject = _super.prototype.serialize.call(this);
  40556. serializationObject.radius = this.radius;
  40557. serializationObject.tube = this.tube;
  40558. serializationObject.radialSegments = this.radialSegments;
  40559. serializationObject.tubularSegments = this.tubularSegments;
  40560. serializationObject.p = this.p;
  40561. serializationObject.q = this.q;
  40562. return serializationObject;
  40563. };
  40564. ;
  40565. TorusKnotGeometry.Parse = function (parsedTorusKnot, scene) {
  40566. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  40567. return null; // null since geometry could be something else than a ground...
  40568. }
  40569. var torusKnot = new TorusKnotGeometry(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  40570. if (BABYLON.Tags) {
  40571. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  40572. }
  40573. scene.pushGeometry(torusKnot, true);
  40574. return torusKnot;
  40575. };
  40576. return TorusKnotGeometry;
  40577. }(_PrimitiveGeometry));
  40578. BABYLON.TorusKnotGeometry = TorusKnotGeometry;
  40579. //}
  40580. })(BABYLON || (BABYLON = {}));
  40581. //# sourceMappingURL=babylon.geometry.js.map
  40582. var BABYLON;
  40583. (function (BABYLON) {
  40584. /**
  40585. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  40586. */
  40587. var PerformanceMonitor = /** @class */ (function () {
  40588. /**
  40589. * constructor
  40590. * @param frameSampleSize The number of samples required to saturate the sliding window
  40591. */
  40592. function PerformanceMonitor(frameSampleSize) {
  40593. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  40594. this._enabled = true;
  40595. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  40596. }
  40597. /**
  40598. * Samples current frame
  40599. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  40600. */
  40601. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  40602. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  40603. if (!this._enabled)
  40604. return;
  40605. if (this._lastFrameTimeMs != null) {
  40606. var dt = timeMs - this._lastFrameTimeMs;
  40607. this._rollingFrameTime.add(dt);
  40608. }
  40609. this._lastFrameTimeMs = timeMs;
  40610. };
  40611. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  40612. /**
  40613. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  40614. * @return Average frame time in milliseconds
  40615. */
  40616. get: function () {
  40617. return this._rollingFrameTime.average;
  40618. },
  40619. enumerable: true,
  40620. configurable: true
  40621. });
  40622. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  40623. /**
  40624. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  40625. * @return Frame time variance in milliseconds squared
  40626. */
  40627. get: function () {
  40628. return this._rollingFrameTime.variance;
  40629. },
  40630. enumerable: true,
  40631. configurable: true
  40632. });
  40633. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  40634. /**
  40635. * Returns the frame time of the most recent frame
  40636. * @return Frame time in milliseconds
  40637. */
  40638. get: function () {
  40639. return this._rollingFrameTime.history(0);
  40640. },
  40641. enumerable: true,
  40642. configurable: true
  40643. });
  40644. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  40645. /**
  40646. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  40647. * @return Framerate in frames per second
  40648. */
  40649. get: function () {
  40650. return 1000.0 / this._rollingFrameTime.average;
  40651. },
  40652. enumerable: true,
  40653. configurable: true
  40654. });
  40655. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  40656. /**
  40657. * Returns the average framerate in frames per second using the most recent frame time
  40658. * @return Framerate in frames per second
  40659. */
  40660. get: function () {
  40661. var history = this._rollingFrameTime.history(0);
  40662. if (history === 0) {
  40663. return 0;
  40664. }
  40665. return 1000.0 / history;
  40666. },
  40667. enumerable: true,
  40668. configurable: true
  40669. });
  40670. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  40671. /**
  40672. * Returns true if enough samples have been taken to completely fill the sliding window
  40673. * @return true if saturated
  40674. */
  40675. get: function () {
  40676. return this._rollingFrameTime.isSaturated();
  40677. },
  40678. enumerable: true,
  40679. configurable: true
  40680. });
  40681. /**
  40682. * Enables contributions to the sliding window sample set
  40683. */
  40684. PerformanceMonitor.prototype.enable = function () {
  40685. this._enabled = true;
  40686. };
  40687. /**
  40688. * Disables contributions to the sliding window sample set
  40689. * Samples will not be interpolated over the disabled period
  40690. */
  40691. PerformanceMonitor.prototype.disable = function () {
  40692. this._enabled = false;
  40693. //clear last sample to avoid interpolating over the disabled period when next enabled
  40694. this._lastFrameTimeMs = null;
  40695. };
  40696. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  40697. /**
  40698. * Returns true if sampling is enabled
  40699. * @return true if enabled
  40700. */
  40701. get: function () {
  40702. return this._enabled;
  40703. },
  40704. enumerable: true,
  40705. configurable: true
  40706. });
  40707. /**
  40708. * Resets performance monitor
  40709. */
  40710. PerformanceMonitor.prototype.reset = function () {
  40711. //clear last sample to avoid interpolating over the disabled period when next enabled
  40712. this._lastFrameTimeMs = null;
  40713. //wipe record
  40714. this._rollingFrameTime.reset();
  40715. };
  40716. return PerformanceMonitor;
  40717. }());
  40718. BABYLON.PerformanceMonitor = PerformanceMonitor;
  40719. /**
  40720. * RollingAverage
  40721. *
  40722. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  40723. */
  40724. var RollingAverage = /** @class */ (function () {
  40725. /**
  40726. * constructor
  40727. * @param length The number of samples required to saturate the sliding window
  40728. */
  40729. function RollingAverage(length) {
  40730. this._samples = new Array(length);
  40731. this.reset();
  40732. }
  40733. /**
  40734. * Adds a sample to the sample set
  40735. * @param v The sample value
  40736. */
  40737. RollingAverage.prototype.add = function (v) {
  40738. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  40739. var delta;
  40740. //we need to check if we've already wrapped round
  40741. if (this.isSaturated()) {
  40742. //remove bottom of stack from mean
  40743. var bottomValue = this._samples[this._pos];
  40744. delta = bottomValue - this.average;
  40745. this.average -= delta / (this._sampleCount - 1);
  40746. this._m2 -= delta * (bottomValue - this.average);
  40747. }
  40748. else {
  40749. this._sampleCount++;
  40750. }
  40751. //add new value to mean
  40752. delta = v - this.average;
  40753. this.average += delta / (this._sampleCount);
  40754. this._m2 += delta * (v - this.average);
  40755. //set the new variance
  40756. this.variance = this._m2 / (this._sampleCount - 1);
  40757. this._samples[this._pos] = v;
  40758. this._pos++;
  40759. this._pos %= this._samples.length; //positive wrap around
  40760. };
  40761. /**
  40762. * Returns previously added values or null if outside of history or outside the sliding window domain
  40763. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  40764. * @return Value previously recorded with add() or null if outside of range
  40765. */
  40766. RollingAverage.prototype.history = function (i) {
  40767. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  40768. return 0;
  40769. }
  40770. var i0 = this._wrapPosition(this._pos - 1.0);
  40771. return this._samples[this._wrapPosition(i0 - i)];
  40772. };
  40773. /**
  40774. * Returns true if enough samples have been taken to completely fill the sliding window
  40775. * @return true if sample-set saturated
  40776. */
  40777. RollingAverage.prototype.isSaturated = function () {
  40778. return this._sampleCount >= this._samples.length;
  40779. };
  40780. /**
  40781. * Resets the rolling average (equivalent to 0 samples taken so far)
  40782. */
  40783. RollingAverage.prototype.reset = function () {
  40784. this.average = 0;
  40785. this.variance = 0;
  40786. this._sampleCount = 0;
  40787. this._pos = 0;
  40788. this._m2 = 0;
  40789. };
  40790. /**
  40791. * Wraps a value around the sample range boundaries
  40792. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  40793. * @return Wrapped position in sample range
  40794. */
  40795. RollingAverage.prototype._wrapPosition = function (i) {
  40796. var max = this._samples.length;
  40797. return ((i % max) + max) % max;
  40798. };
  40799. return RollingAverage;
  40800. }());
  40801. BABYLON.RollingAverage = RollingAverage;
  40802. })(BABYLON || (BABYLON = {}));
  40803. //# sourceMappingURL=babylon.performanceMonitor.js.map
  40804. var BABYLON;
  40805. (function (BABYLON) {
  40806. /**
  40807. * "Static Class" containing the most commonly used helper while dealing with material for
  40808. * rendering purpose.
  40809. *
  40810. * It contains the basic tools to help defining defines, binding uniform for the common part of the materials.
  40811. *
  40812. * This works by convention in BabylonJS but is meant to be use only with shader following the in place naming rules and conventions.
  40813. */
  40814. var MaterialHelper = /** @class */ (function () {
  40815. function MaterialHelper() {
  40816. }
  40817. /**
  40818. * Bind the current view position to an effect.
  40819. * @param effect The effect to be bound
  40820. * @param scene The scene the eyes position is used from
  40821. */
  40822. MaterialHelper.BindEyePosition = function (effect, scene) {
  40823. if (scene._forcedViewPosition) {
  40824. effect.setVector3("vEyePosition", scene._forcedViewPosition);
  40825. return;
  40826. }
  40827. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  40828. };
  40829. /**
  40830. * Helps preparing the defines values about the UVs in used in the effect.
  40831. * UVs are shared as much as we can accross chanels in the shaders.
  40832. * @param texture The texture we are preparing the UVs for
  40833. * @param defines The defines to update
  40834. * @param key The chanel key "diffuse", "specular"... used in the shader
  40835. */
  40836. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  40837. defines._needUVs = true;
  40838. defines[key] = true;
  40839. if (texture.getTextureMatrix().isIdentity(true)) {
  40840. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  40841. if (texture.coordinatesIndex === 0) {
  40842. defines["MAINUV1"] = true;
  40843. }
  40844. else {
  40845. defines["MAINUV2"] = true;
  40846. }
  40847. }
  40848. else {
  40849. defines[key + "DIRECTUV"] = 0;
  40850. }
  40851. };
  40852. /**
  40853. * Binds a texture matrix value to its corrsponding uniform
  40854. * @param texture The texture to bind the matrix for
  40855. * @param uniformBuffer The uniform buffer receivin the data
  40856. * @param key The chanel key "diffuse", "specular"... used in the shader
  40857. */
  40858. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  40859. var matrix = texture.getTextureMatrix();
  40860. if (!matrix.isIdentity(true)) {
  40861. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  40862. }
  40863. };
  40864. /**
  40865. * Helper used to prepare the list of defines associated with misc. values for shader compilation
  40866. * @param mesh defines the current mesh
  40867. * @param scene defines the current scene
  40868. * @param useLogarithmicDepth defines if logarithmic depth has to be turned on
  40869. * @param pointsCloud defines if point cloud rendering has to be turned on
  40870. * @param fogEnabled defines if fog has to be turned on
  40871. * @param alphaTest defines if alpha testing has to be turned on
  40872. * @param defines defines the current list of defines
  40873. */
  40874. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, alphaTest, defines) {
  40875. if (defines._areMiscDirty) {
  40876. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  40877. defines["POINTSIZE"] = pointsCloud;
  40878. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  40879. defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
  40880. defines["ALPHATEST"] = alphaTest;
  40881. }
  40882. };
  40883. /**
  40884. * Helper used to prepare the list of defines associated with frame values for shader compilation
  40885. * @param scene defines the current scene
  40886. * @param engine defines the current engine
  40887. * @param defines specifies the list of active defines
  40888. * @param useInstances defines if instances have to be turned on
  40889. * @param useClipPlane defines if clip plane have to be turned on
  40890. */
  40891. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, useClipPlane) {
  40892. if (useClipPlane === void 0) { useClipPlane = null; }
  40893. var changed = false;
  40894. var useClipPlane1 = false;
  40895. var useClipPlane2 = false;
  40896. var useClipPlane3 = false;
  40897. var useClipPlane4 = false;
  40898. useClipPlane1 = useClipPlane == null ? (scene.clipPlane !== undefined && scene.clipPlane !== null) : useClipPlane;
  40899. useClipPlane2 = useClipPlane == null ? (scene.clipPlane2 !== undefined && scene.clipPlane2 !== null) : useClipPlane;
  40900. useClipPlane3 = useClipPlane == null ? (scene.clipPlane3 !== undefined && scene.clipPlane3 !== null) : useClipPlane;
  40901. useClipPlane4 = useClipPlane == null ? (scene.clipPlane4 !== undefined && scene.clipPlane4 !== null) : useClipPlane;
  40902. if (defines["CLIPPLANE"] !== useClipPlane1) {
  40903. defines["CLIPPLANE"] = useClipPlane1;
  40904. changed = true;
  40905. }
  40906. if (defines["CLIPPLANE2"] !== useClipPlane2) {
  40907. defines["CLIPPLANE2"] = useClipPlane2;
  40908. changed = true;
  40909. }
  40910. if (defines["CLIPPLANE3"] !== useClipPlane3) {
  40911. defines["CLIPPLANE3"] = useClipPlane3;
  40912. changed = true;
  40913. }
  40914. if (defines["CLIPPLANE4"] !== useClipPlane4) {
  40915. defines["CLIPPLANE4"] = useClipPlane4;
  40916. changed = true;
  40917. }
  40918. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  40919. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  40920. changed = true;
  40921. }
  40922. if (defines["INSTANCES"] !== useInstances) {
  40923. defines["INSTANCES"] = useInstances;
  40924. changed = true;
  40925. }
  40926. if (changed) {
  40927. defines.markAsUnprocessed();
  40928. }
  40929. };
  40930. /**
  40931. * Prepares the defines used in the shader depending on the attributes data available in the mesh
  40932. * @param mesh The mesh containing the geometry data we will draw
  40933. * @param defines The defines to update
  40934. * @param useVertexColor Precise whether vertex colors should be used or not (override mesh info)
  40935. * @param useBones Precise whether bones should be used or not (override mesh info)
  40936. * @param useMorphTargets Precise whether morph targets should be used or not (override mesh info)
  40937. * @param useVertexAlpha Precise whether vertex alpha should be used or not (override mesh info)
  40938. * @returns false if defines are considered not dirty and have not been checked
  40939. */
  40940. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets, useVertexAlpha) {
  40941. if (useMorphTargets === void 0) { useMorphTargets = false; }
  40942. if (useVertexAlpha === void 0) { useVertexAlpha = true; }
  40943. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  40944. return false;
  40945. }
  40946. defines._normals = defines._needNormals;
  40947. defines._uvs = defines._needUVs;
  40948. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  40949. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  40950. defines["TANGENT"] = true;
  40951. }
  40952. if (defines._needUVs) {
  40953. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  40954. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  40955. }
  40956. else {
  40957. defines["UV1"] = false;
  40958. defines["UV2"] = false;
  40959. }
  40960. if (useVertexColor) {
  40961. var hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  40962. defines["VERTEXCOLOR"] = hasVertexColors;
  40963. defines["VERTEXALPHA"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha;
  40964. }
  40965. if (useBones) {
  40966. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  40967. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  40968. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  40969. }
  40970. else {
  40971. defines["NUM_BONE_INFLUENCERS"] = 0;
  40972. defines["BonesPerMesh"] = 0;
  40973. }
  40974. }
  40975. if (useMorphTargets) {
  40976. var manager = mesh.morphTargetManager;
  40977. if (manager) {
  40978. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  40979. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  40980. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  40981. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  40982. }
  40983. else {
  40984. defines["MORPHTARGETS_TANGENT"] = false;
  40985. defines["MORPHTARGETS_NORMAL"] = false;
  40986. defines["MORPHTARGETS"] = false;
  40987. defines["NUM_MORPH_INFLUENCERS"] = 0;
  40988. }
  40989. }
  40990. return true;
  40991. };
  40992. /**
  40993. * Prepares the defines related to the light information passed in parameter
  40994. * @param scene The scene we are intending to draw
  40995. * @param mesh The mesh the effect is compiling for
  40996. * @param defines The defines to update
  40997. * @param specularSupported Specifies whether specular is supported or not (override lights data)
  40998. * @param maxSimultaneousLights Specfies how manuy lights can be added to the effect at max
  40999. * @param disableLighting Specifies whether the lighting is disabled (override scene and light)
  41000. * @returns true if normals will be required for the rest of the effect
  41001. */
  41002. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  41003. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  41004. if (disableLighting === void 0) { disableLighting = false; }
  41005. if (!defines._areLightsDirty) {
  41006. return defines._needNormals;
  41007. }
  41008. var lightIndex = 0;
  41009. var needNormals = false;
  41010. var needRebuild = false;
  41011. var lightmapMode = false;
  41012. var shadowEnabled = false;
  41013. var specularEnabled = false;
  41014. if (scene.lightsEnabled && !disableLighting) {
  41015. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  41016. var light = _a[_i];
  41017. needNormals = true;
  41018. if (defines["LIGHT" + lightIndex] === undefined) {
  41019. needRebuild = true;
  41020. }
  41021. defines["LIGHT" + lightIndex] = true;
  41022. defines["SPOTLIGHT" + lightIndex] = false;
  41023. defines["HEMILIGHT" + lightIndex] = false;
  41024. defines["POINTLIGHT" + lightIndex] = false;
  41025. defines["DIRLIGHT" + lightIndex] = false;
  41026. light.prepareLightSpecificDefines(defines, lightIndex);
  41027. // FallOff.
  41028. defines["LIGHT_FALLOFF_PHYSICAL" + lightIndex] = false;
  41029. defines["LIGHT_FALLOFF_GLTF" + lightIndex] = false;
  41030. defines["LIGHT_FALLOFF_STANDARD" + lightIndex] = false;
  41031. switch (light.falloffType) {
  41032. case BABYLON.Light.FALLOFF_GLTF:
  41033. defines["LIGHT_FALLOFF_GLTF" + lightIndex] = true;
  41034. break;
  41035. case BABYLON.Light.FALLOFF_PHYSICAL:
  41036. defines["LIGHT_FALLOFF_PHYSICAL" + lightIndex] = true;
  41037. break;
  41038. case BABYLON.Light.FALLOFF_STANDARD:
  41039. defines["LIGHT_FALLOFF_STANDARD" + lightIndex] = true;
  41040. break;
  41041. }
  41042. // Specular
  41043. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  41044. specularEnabled = true;
  41045. }
  41046. // Shadows
  41047. defines["SHADOW" + lightIndex] = false;
  41048. defines["SHADOWPCF" + lightIndex] = false;
  41049. defines["SHADOWPCSS" + lightIndex] = false;
  41050. defines["SHADOWPOISSON" + lightIndex] = false;
  41051. defines["SHADOWESM" + lightIndex] = false;
  41052. defines["SHADOWCUBE" + lightIndex] = false;
  41053. defines["SHADOWLOWQUALITY" + lightIndex] = false;
  41054. defines["SHADOWMEDIUMQUALITY" + lightIndex] = false;
  41055. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  41056. var shadowGenerator = light.getShadowGenerator();
  41057. if (shadowGenerator) {
  41058. var shadowMap = shadowGenerator.getShadowMap();
  41059. if (shadowMap) {
  41060. if (shadowMap.renderList && shadowMap.renderList.length > 0) {
  41061. shadowEnabled = true;
  41062. shadowGenerator.prepareDefines(defines, lightIndex);
  41063. }
  41064. }
  41065. }
  41066. }
  41067. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  41068. lightmapMode = true;
  41069. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  41070. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  41071. }
  41072. else {
  41073. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  41074. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  41075. }
  41076. lightIndex++;
  41077. if (lightIndex === maxSimultaneousLights)
  41078. break;
  41079. }
  41080. }
  41081. defines["SPECULARTERM"] = specularEnabled;
  41082. defines["SHADOWS"] = shadowEnabled;
  41083. // Resetting all other lights if any
  41084. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  41085. if (defines["LIGHT" + index] !== undefined) {
  41086. defines["LIGHT" + index] = false;
  41087. defines["HEMILIGHT" + lightIndex] = false;
  41088. defines["POINTLIGHT" + lightIndex] = false;
  41089. defines["DIRLIGHT" + lightIndex] = false;
  41090. defines["SPOTLIGHT" + lightIndex] = false;
  41091. defines["SHADOW" + lightIndex] = false;
  41092. }
  41093. }
  41094. var caps = scene.getEngine().getCaps();
  41095. if (defines["SHADOWFLOAT"] === undefined) {
  41096. needRebuild = true;
  41097. }
  41098. defines["SHADOWFLOAT"] = shadowEnabled &&
  41099. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  41100. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  41101. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  41102. if (needRebuild) {
  41103. defines.rebuild();
  41104. }
  41105. return needNormals;
  41106. };
  41107. /**
  41108. * Prepares the uniforms and samplers list to be used in the effect. This can automatically remove from the list uniforms
  41109. * that won t be acctive due to defines being turned off.
  41110. * @param uniformsListOrOptions The uniform names to prepare or an EffectCreationOptions containing the liist and extra information
  41111. * @param samplersList The samplers list
  41112. * @param defines The defines helping in the list generation
  41113. * @param maxSimultaneousLights The maximum number of simultanous light allowed in the effect
  41114. */
  41115. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  41116. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  41117. var uniformsList;
  41118. var uniformBuffersList = null;
  41119. if (uniformsListOrOptions.uniformsNames) {
  41120. var options = uniformsListOrOptions;
  41121. uniformsList = options.uniformsNames;
  41122. uniformBuffersList = options.uniformBuffersNames;
  41123. samplersList = options.samplers;
  41124. defines = options.defines;
  41125. maxSimultaneousLights = options.maxSimultaneousLights;
  41126. }
  41127. else {
  41128. uniformsList = uniformsListOrOptions;
  41129. if (!samplersList) {
  41130. samplersList = [];
  41131. }
  41132. }
  41133. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  41134. if (!defines["LIGHT" + lightIndex]) {
  41135. break;
  41136. }
  41137. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightFalloff" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  41138. if (uniformBuffersList) {
  41139. uniformBuffersList.push("Light" + lightIndex);
  41140. }
  41141. samplersList.push("shadowSampler" + lightIndex);
  41142. samplersList.push("depthSampler" + lightIndex);
  41143. if (defines["PROJECTEDLIGHTTEXTURE" + lightIndex]) {
  41144. samplersList.push("projectionLightSampler" + lightIndex);
  41145. uniformsList.push("textureProjectionMatrix" + lightIndex);
  41146. }
  41147. }
  41148. if (defines["NUM_MORPH_INFLUENCERS"]) {
  41149. uniformsList.push("morphTargetInfluences");
  41150. }
  41151. };
  41152. /**
  41153. * This helps decreasing rank by rank the shadow quality (0 being the highest rank and quality)
  41154. * @param defines The defines to update while falling back
  41155. * @param fallbacks The authorized effect fallbacks
  41156. * @param maxSimultaneousLights The maximum number of lights allowed
  41157. * @param rank the current rank of the Effect
  41158. * @returns The newly affected rank
  41159. */
  41160. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights, rank) {
  41161. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  41162. if (rank === void 0) { rank = 0; }
  41163. var lightFallbackRank = 0;
  41164. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  41165. if (!defines["LIGHT" + lightIndex]) {
  41166. break;
  41167. }
  41168. if (lightIndex > 0) {
  41169. lightFallbackRank = rank + lightIndex;
  41170. fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
  41171. }
  41172. if (!defines["SHADOWS"]) {
  41173. if (defines["SHADOW" + lightIndex]) {
  41174. fallbacks.addFallback(rank, "SHADOW" + lightIndex);
  41175. }
  41176. if (defines["SHADOWPCF" + lightIndex]) {
  41177. fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
  41178. }
  41179. if (defines["SHADOWPCSS" + lightIndex]) {
  41180. fallbacks.addFallback(rank, "SHADOWPCSS" + lightIndex);
  41181. }
  41182. if (defines["SHADOWPOISSON" + lightIndex]) {
  41183. fallbacks.addFallback(rank, "SHADOWPOISSON" + lightIndex);
  41184. }
  41185. if (defines["SHADOWESM" + lightIndex]) {
  41186. fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
  41187. }
  41188. }
  41189. }
  41190. return lightFallbackRank++;
  41191. };
  41192. /**
  41193. * Prepares the list of attributes required for morph targets according to the effect defines.
  41194. * @param attribs The current list of supported attribs
  41195. * @param mesh The mesh to prepare the morph targets attributes for
  41196. * @param defines The current Defines of the effect
  41197. */
  41198. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  41199. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  41200. if (influencers > 0 && BABYLON.Engine.LastCreatedEngine) {
  41201. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  41202. var manager = mesh.morphTargetManager;
  41203. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  41204. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  41205. for (var index = 0; index < influencers; index++) {
  41206. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  41207. if (normal) {
  41208. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  41209. }
  41210. if (tangent) {
  41211. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  41212. }
  41213. if (attribs.length > maxAttributesCount) {
  41214. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  41215. }
  41216. }
  41217. }
  41218. };
  41219. /**
  41220. * Prepares the list of attributes required for bones according to the effect defines.
  41221. * @param attribs The current list of supported attribs
  41222. * @param mesh The mesh to prepare the bones attributes for
  41223. * @param defines The current Defines of the effect
  41224. * @param fallbacks The current efffect fallback strategy
  41225. */
  41226. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  41227. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  41228. fallbacks.addCPUSkinningFallback(0, mesh);
  41229. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  41230. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  41231. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  41232. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  41233. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  41234. }
  41235. }
  41236. };
  41237. /**
  41238. * Prepares the list of attributes required for instances according to the effect defines.
  41239. * @param attribs The current list of supported attribs
  41240. * @param defines The current Defines of the effect
  41241. */
  41242. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  41243. if (defines["INSTANCES"]) {
  41244. attribs.push("world0");
  41245. attribs.push("world1");
  41246. attribs.push("world2");
  41247. attribs.push("world3");
  41248. }
  41249. };
  41250. /**
  41251. * Binds the light shadow information to the effect for the given mesh.
  41252. * @param light The light containing the generator
  41253. * @param scene The scene the lights belongs to
  41254. * @param mesh The mesh we are binding the information to render
  41255. * @param lightIndex The light index in the effect used to render the mesh
  41256. * @param effect The effect we are binding the data to
  41257. */
  41258. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  41259. if (light.shadowEnabled && mesh.receiveShadows) {
  41260. var shadowGenerator = light.getShadowGenerator();
  41261. if (shadowGenerator) {
  41262. shadowGenerator.bindShadowLight(lightIndex, effect);
  41263. }
  41264. }
  41265. };
  41266. /**
  41267. * Binds the light information to the effect.
  41268. * @param light The light containing the generator
  41269. * @param effect The effect we are binding the data to
  41270. * @param lightIndex The light index in the effect used to render
  41271. */
  41272. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  41273. light.transferToEffect(effect, lightIndex + "");
  41274. };
  41275. /**
  41276. * Binds the lights information from the scene to the effect for the given mesh.
  41277. * @param scene The scene the lights belongs to
  41278. * @param mesh The mesh we are binding the information to render
  41279. * @param effect The effect we are binding the data to
  41280. * @param defines The generated defines for the effect
  41281. * @param maxSimultaneousLights The maximum number of light that can be bound to the effect
  41282. * @param usePhysicalLightFalloff Specifies whether the light falloff is defined physically or not
  41283. */
  41284. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  41285. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  41286. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  41287. var len = Math.min(mesh._lightSources.length, maxSimultaneousLights);
  41288. for (var i = 0; i < len; i++) {
  41289. var light = mesh._lightSources[i];
  41290. var iAsString = i.toString();
  41291. var scaledIntensity = light.getScaledIntensity();
  41292. light._uniformBuffer.bindToEffect(effect, "Light" + i);
  41293. MaterialHelper.BindLightProperties(light, effect, i);
  41294. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  41295. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, iAsString);
  41296. if (defines["SPECULARTERM"]) {
  41297. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  41298. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], iAsString);
  41299. }
  41300. // Shadows
  41301. if (scene.shadowsEnabled) {
  41302. this.BindLightShadow(light, scene, mesh, iAsString, effect);
  41303. }
  41304. light._uniformBuffer.update();
  41305. }
  41306. };
  41307. /**
  41308. * Binds the fog information from the scene to the effect for the given mesh.
  41309. * @param scene The scene the lights belongs to
  41310. * @param mesh The mesh we are binding the information to render
  41311. * @param effect The effect we are binding the data to
  41312. * @param linearSpace Defines if the fog effect is applied in linear space
  41313. */
  41314. MaterialHelper.BindFogParameters = function (scene, mesh, effect, linearSpace) {
  41315. if (linearSpace === void 0) { linearSpace = false; }
  41316. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  41317. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  41318. // Convert fog color to linear space if used in a linear space computed shader.
  41319. if (linearSpace) {
  41320. scene.fogColor.toLinearSpaceToRef(this._tempFogColor);
  41321. effect.setColor3("vFogColor", this._tempFogColor);
  41322. }
  41323. else {
  41324. effect.setColor3("vFogColor", scene.fogColor);
  41325. }
  41326. }
  41327. };
  41328. /**
  41329. * Binds the bones information from the mesh to the effect.
  41330. * @param mesh The mesh we are binding the information to render
  41331. * @param effect The effect we are binding the data to
  41332. */
  41333. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  41334. if (!effect || !mesh) {
  41335. return;
  41336. }
  41337. if (mesh.computeBonesUsingShaders && effect._bonesComputationForcedToCPU) {
  41338. mesh.computeBonesUsingShaders = false;
  41339. }
  41340. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  41341. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  41342. if (matrices) {
  41343. effect.setMatrices("mBones", matrices);
  41344. }
  41345. }
  41346. };
  41347. /**
  41348. * Binds the morph targets information from the mesh to the effect.
  41349. * @param abstractMesh The mesh we are binding the information to render
  41350. * @param effect The effect we are binding the data to
  41351. */
  41352. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  41353. var manager = abstractMesh.morphTargetManager;
  41354. if (!abstractMesh || !manager) {
  41355. return;
  41356. }
  41357. effect.setFloatArray("morphTargetInfluences", manager.influences);
  41358. };
  41359. /**
  41360. * Binds the logarithmic depth information from the scene to the effect for the given defines.
  41361. * @param defines The generated defines used in the effect
  41362. * @param effect The effect we are binding the data to
  41363. * @param scene The scene we are willing to render with logarithmic scale for
  41364. */
  41365. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  41366. if (defines["LOGARITHMICDEPTH"]) {
  41367. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  41368. }
  41369. };
  41370. /**
  41371. * Binds the clip plane information from the scene to the effect.
  41372. * @param scene The scene the clip plane information are extracted from
  41373. * @param effect The effect we are binding the data to
  41374. */
  41375. MaterialHelper.BindClipPlane = function (effect, scene) {
  41376. if (scene.clipPlane) {
  41377. var clipPlane = scene.clipPlane;
  41378. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  41379. }
  41380. if (scene.clipPlane2) {
  41381. var clipPlane = scene.clipPlane2;
  41382. effect.setFloat4("vClipPlane2", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  41383. }
  41384. if (scene.clipPlane3) {
  41385. var clipPlane = scene.clipPlane3;
  41386. effect.setFloat4("vClipPlane3", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  41387. }
  41388. if (scene.clipPlane4) {
  41389. var clipPlane = scene.clipPlane4;
  41390. effect.setFloat4("vClipPlane4", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  41391. }
  41392. };
  41393. MaterialHelper._tempFogColor = BABYLON.Color3.Black();
  41394. return MaterialHelper;
  41395. }());
  41396. BABYLON.MaterialHelper = MaterialHelper;
  41397. })(BABYLON || (BABYLON = {}));
  41398. //# sourceMappingURL=babylon.materialHelper.js.map
  41399. var BABYLON;
  41400. (function (BABYLON) {
  41401. var PushMaterial = /** @class */ (function (_super) {
  41402. __extends(PushMaterial, _super);
  41403. function PushMaterial(name, scene) {
  41404. var _this = _super.call(this, name, scene) || this;
  41405. _this._normalMatrix = new BABYLON.Matrix();
  41406. _this.storeEffectOnSubMeshes = true;
  41407. return _this;
  41408. }
  41409. PushMaterial.prototype.getEffect = function () {
  41410. return this._activeEffect;
  41411. };
  41412. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  41413. if (!mesh) {
  41414. return false;
  41415. }
  41416. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  41417. return true;
  41418. }
  41419. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  41420. };
  41421. /**
  41422. * Binds the given world matrix to the active effect
  41423. *
  41424. * @param world the matrix to bind
  41425. */
  41426. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  41427. this._activeEffect.setMatrix("world", world);
  41428. };
  41429. /**
  41430. * Binds the given normal matrix to the active effect
  41431. *
  41432. * @param normalMatrix the matrix to bind
  41433. */
  41434. PushMaterial.prototype.bindOnlyNormalMatrix = function (normalMatrix) {
  41435. this._activeEffect.setMatrix("normalMatrix", normalMatrix);
  41436. };
  41437. PushMaterial.prototype.bind = function (world, mesh) {
  41438. if (!mesh) {
  41439. return;
  41440. }
  41441. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  41442. };
  41443. PushMaterial.prototype._afterBind = function (mesh, effect) {
  41444. if (effect === void 0) { effect = null; }
  41445. _super.prototype._afterBind.call(this, mesh);
  41446. this.getScene()._cachedEffect = effect;
  41447. };
  41448. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  41449. if (visibility === void 0) { visibility = 1; }
  41450. return scene.isCachedMaterialInvalid(this, effect, visibility);
  41451. };
  41452. return PushMaterial;
  41453. }(BABYLON.Material));
  41454. BABYLON.PushMaterial = PushMaterial;
  41455. })(BABYLON || (BABYLON = {}));
  41456. //# sourceMappingURL=babylon.pushMaterial.js.map
  41457. var BABYLON;
  41458. (function (BABYLON) {
  41459. /** @hidden */
  41460. var StandardMaterialDefines = /** @class */ (function (_super) {
  41461. __extends(StandardMaterialDefines, _super);
  41462. function StandardMaterialDefines() {
  41463. var _this = _super.call(this) || this;
  41464. _this.MAINUV1 = false;
  41465. _this.MAINUV2 = false;
  41466. _this.DIFFUSE = false;
  41467. _this.DIFFUSEDIRECTUV = 0;
  41468. _this.AMBIENT = false;
  41469. _this.AMBIENTDIRECTUV = 0;
  41470. _this.OPACITY = false;
  41471. _this.OPACITYDIRECTUV = 0;
  41472. _this.OPACITYRGB = false;
  41473. _this.REFLECTION = false;
  41474. _this.EMISSIVE = false;
  41475. _this.EMISSIVEDIRECTUV = 0;
  41476. _this.SPECULAR = false;
  41477. _this.SPECULARDIRECTUV = 0;
  41478. _this.BUMP = false;
  41479. _this.BUMPDIRECTUV = 0;
  41480. _this.PARALLAX = false;
  41481. _this.PARALLAXOCCLUSION = false;
  41482. _this.SPECULAROVERALPHA = false;
  41483. _this.CLIPPLANE = false;
  41484. _this.CLIPPLANE2 = false;
  41485. _this.CLIPPLANE3 = false;
  41486. _this.CLIPPLANE4 = false;
  41487. _this.ALPHATEST = false;
  41488. _this.DEPTHPREPASS = false;
  41489. _this.ALPHAFROMDIFFUSE = false;
  41490. _this.POINTSIZE = false;
  41491. _this.FOG = false;
  41492. _this.SPECULARTERM = false;
  41493. _this.DIFFUSEFRESNEL = false;
  41494. _this.OPACITYFRESNEL = false;
  41495. _this.REFLECTIONFRESNEL = false;
  41496. _this.REFRACTIONFRESNEL = false;
  41497. _this.EMISSIVEFRESNEL = false;
  41498. _this.FRESNEL = false;
  41499. _this.NORMAL = false;
  41500. _this.UV1 = false;
  41501. _this.UV2 = false;
  41502. _this.VERTEXCOLOR = false;
  41503. _this.VERTEXALPHA = false;
  41504. _this.NUM_BONE_INFLUENCERS = 0;
  41505. _this.BonesPerMesh = 0;
  41506. _this.INSTANCES = false;
  41507. _this.GLOSSINESS = false;
  41508. _this.ROUGHNESS = false;
  41509. _this.EMISSIVEASILLUMINATION = false;
  41510. _this.LINKEMISSIVEWITHDIFFUSE = false;
  41511. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  41512. _this.LIGHTMAP = false;
  41513. _this.LIGHTMAPDIRECTUV = 0;
  41514. _this.OBJECTSPACE_NORMALMAP = false;
  41515. _this.USELIGHTMAPASSHADOWMAP = false;
  41516. _this.REFLECTIONMAP_3D = false;
  41517. _this.REFLECTIONMAP_SPHERICAL = false;
  41518. _this.REFLECTIONMAP_PLANAR = false;
  41519. _this.REFLECTIONMAP_CUBIC = false;
  41520. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  41521. _this.REFLECTIONMAP_PROJECTION = false;
  41522. _this.REFLECTIONMAP_SKYBOX = false;
  41523. _this.REFLECTIONMAP_SKYBOX_TRANSFORMED = false;
  41524. _this.REFLECTIONMAP_EXPLICIT = false;
  41525. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  41526. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  41527. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  41528. _this.INVERTCUBICMAP = false;
  41529. _this.LOGARITHMICDEPTH = false;
  41530. _this.REFRACTION = false;
  41531. _this.REFRACTIONMAP_3D = false;
  41532. _this.REFLECTIONOVERALPHA = false;
  41533. _this.TWOSIDEDLIGHTING = false;
  41534. _this.SHADOWFLOAT = false;
  41535. _this.MORPHTARGETS = false;
  41536. _this.MORPHTARGETS_NORMAL = false;
  41537. _this.MORPHTARGETS_TANGENT = false;
  41538. _this.NUM_MORPH_INFLUENCERS = 0;
  41539. _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH
  41540. _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7
  41541. _this.IMAGEPROCESSING = false;
  41542. _this.VIGNETTE = false;
  41543. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  41544. _this.VIGNETTEBLENDMODEOPAQUE = false;
  41545. _this.TONEMAPPING = false;
  41546. _this.TONEMAPPING_ACES = false;
  41547. _this.CONTRAST = false;
  41548. _this.COLORCURVES = false;
  41549. _this.COLORGRADING = false;
  41550. _this.COLORGRADING3D = false;
  41551. _this.SAMPLER3DGREENDEPTH = false;
  41552. _this.SAMPLER3DBGRMAP = false;
  41553. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  41554. /**
  41555. * If the reflection texture on this material is in linear color space
  41556. * @hidden
  41557. */
  41558. _this.IS_REFLECTION_LINEAR = false;
  41559. /**
  41560. * If the refraction texture on this material is in linear color space
  41561. * @hidden
  41562. */
  41563. _this.IS_REFRACTION_LINEAR = false;
  41564. _this.EXPOSURE = false;
  41565. _this.rebuild();
  41566. return _this;
  41567. }
  41568. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  41569. var modes = [
  41570. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  41571. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  41572. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  41573. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  41574. ];
  41575. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  41576. var mode = modes_1[_i];
  41577. this[mode] = (mode === modeToEnable);
  41578. }
  41579. };
  41580. return StandardMaterialDefines;
  41581. }(BABYLON.MaterialDefines));
  41582. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  41583. var StandardMaterial = /** @class */ (function (_super) {
  41584. __extends(StandardMaterial, _super);
  41585. function StandardMaterial(name, scene) {
  41586. var _this = _super.call(this, name, scene) || this;
  41587. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  41588. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  41589. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  41590. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  41591. _this.specularPower = 64;
  41592. _this._useAlphaFromDiffuseTexture = false;
  41593. _this._useEmissiveAsIllumination = false;
  41594. _this._linkEmissiveWithDiffuse = false;
  41595. _this._useSpecularOverAlpha = false;
  41596. _this._useReflectionOverAlpha = false;
  41597. _this._disableLighting = false;
  41598. _this._useObjectSpaceNormalMap = false;
  41599. _this._useParallax = false;
  41600. _this._useParallaxOcclusion = false;
  41601. _this.parallaxScaleBias = 0.05;
  41602. _this._roughness = 0;
  41603. _this.indexOfRefraction = 0.98;
  41604. _this.invertRefractionY = true;
  41605. /**
  41606. * Defines the alpha limits in alpha test mode
  41607. */
  41608. _this.alphaCutOff = 0.4;
  41609. _this._useLightmapAsShadowmap = false;
  41610. _this._useReflectionFresnelFromSpecular = false;
  41611. _this._useGlossinessFromSpecularMapAlpha = false;
  41612. _this._maxSimultaneousLights = 4;
  41613. /**
  41614. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  41615. */
  41616. _this._invertNormalMapX = false;
  41617. /**
  41618. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  41619. */
  41620. _this._invertNormalMapY = false;
  41621. /**
  41622. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  41623. */
  41624. _this._twoSidedLighting = false;
  41625. _this._renderTargets = new BABYLON.SmartArray(16);
  41626. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  41627. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  41628. // Setup the default processing configuration to the scene.
  41629. _this._attachImageProcessingConfiguration(null);
  41630. _this.getRenderTargetTextures = function () {
  41631. _this._renderTargets.reset();
  41632. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  41633. _this._renderTargets.push(_this._reflectionTexture);
  41634. }
  41635. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  41636. _this._renderTargets.push(_this._refractionTexture);
  41637. }
  41638. return _this._renderTargets;
  41639. };
  41640. return _this;
  41641. }
  41642. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  41643. /**
  41644. * Gets the image processing configuration used either in this material.
  41645. */
  41646. get: function () {
  41647. return this._imageProcessingConfiguration;
  41648. },
  41649. /**
  41650. * Sets the Default image processing configuration used either in the this material.
  41651. *
  41652. * If sets to null, the scene one is in use.
  41653. */
  41654. set: function (value) {
  41655. this._attachImageProcessingConfiguration(value);
  41656. // Ensure the effect will be rebuilt.
  41657. this._markAllSubMeshesAsTexturesDirty();
  41658. },
  41659. enumerable: true,
  41660. configurable: true
  41661. });
  41662. /**
  41663. * Attaches a new image processing configuration to the Standard Material.
  41664. * @param configuration
  41665. */
  41666. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  41667. var _this = this;
  41668. if (configuration === this._imageProcessingConfiguration) {
  41669. return;
  41670. }
  41671. // Detaches observer.
  41672. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  41673. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  41674. }
  41675. // Pick the scene configuration if needed.
  41676. if (!configuration) {
  41677. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  41678. }
  41679. else {
  41680. this._imageProcessingConfiguration = configuration;
  41681. }
  41682. // Attaches observer.
  41683. if (this._imageProcessingConfiguration) {
  41684. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  41685. _this._markAllSubMeshesAsImageProcessingDirty();
  41686. });
  41687. }
  41688. };
  41689. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  41690. /**
  41691. * Gets wether the color curves effect is enabled.
  41692. */
  41693. get: function () {
  41694. return this.imageProcessingConfiguration.colorCurvesEnabled;
  41695. },
  41696. /**
  41697. * Sets wether the color curves effect is enabled.
  41698. */
  41699. set: function (value) {
  41700. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  41701. },
  41702. enumerable: true,
  41703. configurable: true
  41704. });
  41705. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  41706. /**
  41707. * Gets wether the color grading effect is enabled.
  41708. */
  41709. get: function () {
  41710. return this.imageProcessingConfiguration.colorGradingEnabled;
  41711. },
  41712. /**
  41713. * Gets wether the color grading effect is enabled.
  41714. */
  41715. set: function (value) {
  41716. this.imageProcessingConfiguration.colorGradingEnabled = value;
  41717. },
  41718. enumerable: true,
  41719. configurable: true
  41720. });
  41721. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  41722. /**
  41723. * Gets wether tonemapping is enabled or not.
  41724. */
  41725. get: function () {
  41726. return this._imageProcessingConfiguration.toneMappingEnabled;
  41727. },
  41728. /**
  41729. * Sets wether tonemapping is enabled or not
  41730. */
  41731. set: function (value) {
  41732. this._imageProcessingConfiguration.toneMappingEnabled = value;
  41733. },
  41734. enumerable: true,
  41735. configurable: true
  41736. });
  41737. ;
  41738. ;
  41739. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  41740. /**
  41741. * The camera exposure used on this material.
  41742. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  41743. * This corresponds to a photographic exposure.
  41744. */
  41745. get: function () {
  41746. return this._imageProcessingConfiguration.exposure;
  41747. },
  41748. /**
  41749. * The camera exposure used on this material.
  41750. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  41751. * This corresponds to a photographic exposure.
  41752. */
  41753. set: function (value) {
  41754. this._imageProcessingConfiguration.exposure = value;
  41755. },
  41756. enumerable: true,
  41757. configurable: true
  41758. });
  41759. ;
  41760. ;
  41761. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  41762. /**
  41763. * Gets The camera contrast used on this material.
  41764. */
  41765. get: function () {
  41766. return this._imageProcessingConfiguration.contrast;
  41767. },
  41768. /**
  41769. * Sets The camera contrast used on this material.
  41770. */
  41771. set: function (value) {
  41772. this._imageProcessingConfiguration.contrast = value;
  41773. },
  41774. enumerable: true,
  41775. configurable: true
  41776. });
  41777. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  41778. /**
  41779. * Gets the Color Grading 2D Lookup Texture.
  41780. */
  41781. get: function () {
  41782. return this._imageProcessingConfiguration.colorGradingTexture;
  41783. },
  41784. /**
  41785. * Sets the Color Grading 2D Lookup Texture.
  41786. */
  41787. set: function (value) {
  41788. this._imageProcessingConfiguration.colorGradingTexture = value;
  41789. },
  41790. enumerable: true,
  41791. configurable: true
  41792. });
  41793. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  41794. /**
  41795. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  41796. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  41797. * 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;
  41798. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  41799. */
  41800. get: function () {
  41801. return this._imageProcessingConfiguration.colorCurves;
  41802. },
  41803. /**
  41804. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  41805. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  41806. * 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;
  41807. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  41808. */
  41809. set: function (value) {
  41810. this._imageProcessingConfiguration.colorCurves = value;
  41811. },
  41812. enumerable: true,
  41813. configurable: true
  41814. });
  41815. Object.defineProperty(StandardMaterial.prototype, "hasRenderTargetTextures", {
  41816. /**
  41817. * Gets a boolean indicating that current material needs to register RTT
  41818. */
  41819. get: function () {
  41820. if (StandardMaterial.ReflectionTextureEnabled && this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  41821. return true;
  41822. }
  41823. if (StandardMaterial.RefractionTextureEnabled && this._refractionTexture && this._refractionTexture.isRenderTarget) {
  41824. return true;
  41825. }
  41826. return false;
  41827. },
  41828. enumerable: true,
  41829. configurable: true
  41830. });
  41831. StandardMaterial.prototype.getClassName = function () {
  41832. return "StandardMaterial";
  41833. };
  41834. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  41835. get: function () {
  41836. return this._useLogarithmicDepth;
  41837. },
  41838. set: function (value) {
  41839. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  41840. this._markAllSubMeshesAsMiscDirty();
  41841. },
  41842. enumerable: true,
  41843. configurable: true
  41844. });
  41845. StandardMaterial.prototype.needAlphaBlending = function () {
  41846. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  41847. };
  41848. StandardMaterial.prototype.needAlphaTesting = function () {
  41849. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  41850. };
  41851. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  41852. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  41853. };
  41854. StandardMaterial.prototype.getAlphaTestTexture = function () {
  41855. return this._diffuseTexture;
  41856. };
  41857. /**
  41858. * Child classes can use it to update shaders
  41859. */
  41860. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  41861. if (useInstances === void 0) { useInstances = false; }
  41862. if (subMesh.effect && this.isFrozen) {
  41863. if (this._wasPreviouslyReady) {
  41864. return true;
  41865. }
  41866. }
  41867. if (!subMesh._materialDefines) {
  41868. subMesh._materialDefines = new StandardMaterialDefines();
  41869. }
  41870. var scene = this.getScene();
  41871. var defines = subMesh._materialDefines;
  41872. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  41873. if (defines._renderId === scene.getRenderId()) {
  41874. return true;
  41875. }
  41876. }
  41877. var engine = scene.getEngine();
  41878. // Lights
  41879. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  41880. // Textures
  41881. if (defines._areTexturesDirty) {
  41882. defines._needUVs = false;
  41883. defines.MAINUV1 = false;
  41884. defines.MAINUV2 = false;
  41885. if (scene.texturesEnabled) {
  41886. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  41887. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  41888. return false;
  41889. }
  41890. else {
  41891. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  41892. }
  41893. }
  41894. else {
  41895. defines.DIFFUSE = false;
  41896. }
  41897. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  41898. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  41899. return false;
  41900. }
  41901. else {
  41902. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  41903. }
  41904. }
  41905. else {
  41906. defines.AMBIENT = false;
  41907. }
  41908. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  41909. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  41910. return false;
  41911. }
  41912. else {
  41913. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  41914. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  41915. }
  41916. }
  41917. else {
  41918. defines.OPACITY = false;
  41919. }
  41920. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  41921. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  41922. return false;
  41923. }
  41924. else {
  41925. defines._needNormals = true;
  41926. defines.REFLECTION = true;
  41927. defines.ROUGHNESS = (this._roughness > 0);
  41928. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  41929. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  41930. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  41931. switch (this._reflectionTexture.coordinatesMode) {
  41932. case BABYLON.Texture.EXPLICIT_MODE:
  41933. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  41934. break;
  41935. case BABYLON.Texture.PLANAR_MODE:
  41936. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  41937. break;
  41938. case BABYLON.Texture.PROJECTION_MODE:
  41939. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  41940. break;
  41941. case BABYLON.Texture.SKYBOX_MODE:
  41942. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  41943. defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = !this._reflectionTexture.getReflectionTextureMatrix().isIdentity();
  41944. break;
  41945. case BABYLON.Texture.SPHERICAL_MODE:
  41946. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  41947. break;
  41948. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  41949. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  41950. break;
  41951. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  41952. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  41953. break;
  41954. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  41955. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  41956. break;
  41957. case BABYLON.Texture.CUBIC_MODE:
  41958. case BABYLON.Texture.INVCUBIC_MODE:
  41959. default:
  41960. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  41961. break;
  41962. }
  41963. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = this._reflectionTexture.boundingBoxSize ? true : false;
  41964. }
  41965. }
  41966. else {
  41967. defines.REFLECTION = false;
  41968. }
  41969. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  41970. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  41971. return false;
  41972. }
  41973. else {
  41974. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  41975. }
  41976. }
  41977. else {
  41978. defines.EMISSIVE = false;
  41979. }
  41980. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  41981. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  41982. return false;
  41983. }
  41984. else {
  41985. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  41986. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  41987. }
  41988. }
  41989. else {
  41990. defines.LIGHTMAP = false;
  41991. }
  41992. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  41993. if (!this._specularTexture.isReadyOrNotBlocking()) {
  41994. return false;
  41995. }
  41996. else {
  41997. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  41998. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  41999. }
  42000. }
  42001. else {
  42002. defines.SPECULAR = false;
  42003. }
  42004. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  42005. // Bump texure can not be not blocking.
  42006. if (!this._bumpTexture.isReady()) {
  42007. return false;
  42008. }
  42009. else {
  42010. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  42011. defines.PARALLAX = this._useParallax;
  42012. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  42013. }
  42014. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  42015. }
  42016. else {
  42017. defines.BUMP = false;
  42018. }
  42019. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  42020. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  42021. return false;
  42022. }
  42023. else {
  42024. defines._needUVs = true;
  42025. defines.REFRACTION = true;
  42026. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  42027. }
  42028. }
  42029. else {
  42030. defines.REFRACTION = false;
  42031. }
  42032. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  42033. }
  42034. else {
  42035. defines.DIFFUSE = false;
  42036. defines.AMBIENT = false;
  42037. defines.OPACITY = false;
  42038. defines.REFLECTION = false;
  42039. defines.EMISSIVE = false;
  42040. defines.LIGHTMAP = false;
  42041. defines.BUMP = false;
  42042. defines.REFRACTION = false;
  42043. }
  42044. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  42045. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  42046. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  42047. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  42048. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  42049. }
  42050. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  42051. if (!this._imageProcessingConfiguration.isReady()) {
  42052. return false;
  42053. }
  42054. this._imageProcessingConfiguration.prepareDefines(defines);
  42055. defines.IS_REFLECTION_LINEAR = (this.reflectionTexture != null && !this.reflectionTexture.gammaSpace);
  42056. defines.IS_REFRACTION_LINEAR = (this.refractionTexture != null && !this.refractionTexture.gammaSpace);
  42057. }
  42058. if (defines._areFresnelDirty) {
  42059. if (StandardMaterial.FresnelEnabled) {
  42060. // Fresnel
  42061. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  42062. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  42063. this._reflectionFresnelParameters) {
  42064. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  42065. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  42066. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  42067. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  42068. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  42069. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  42070. defines._needNormals = true;
  42071. defines.FRESNEL = true;
  42072. }
  42073. }
  42074. else {
  42075. defines.FRESNEL = false;
  42076. }
  42077. }
  42078. // Misc.
  42079. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  42080. // Attribs
  42081. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  42082. // Values that need to be evaluated on every frame
  42083. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  42084. // Get correct effect
  42085. if (defines.isDirty) {
  42086. defines.markAsProcessed();
  42087. scene.resetCachedMaterial();
  42088. // Fallbacks
  42089. var fallbacks = new BABYLON.EffectFallbacks();
  42090. if (defines.REFLECTION) {
  42091. fallbacks.addFallback(0, "REFLECTION");
  42092. }
  42093. if (defines.SPECULAR) {
  42094. fallbacks.addFallback(0, "SPECULAR");
  42095. }
  42096. if (defines.BUMP) {
  42097. fallbacks.addFallback(0, "BUMP");
  42098. }
  42099. if (defines.PARALLAX) {
  42100. fallbacks.addFallback(1, "PARALLAX");
  42101. }
  42102. if (defines.PARALLAXOCCLUSION) {
  42103. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  42104. }
  42105. if (defines.SPECULAROVERALPHA) {
  42106. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  42107. }
  42108. if (defines.FOG) {
  42109. fallbacks.addFallback(1, "FOG");
  42110. }
  42111. if (defines.POINTSIZE) {
  42112. fallbacks.addFallback(0, "POINTSIZE");
  42113. }
  42114. if (defines.LOGARITHMICDEPTH) {
  42115. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  42116. }
  42117. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  42118. if (defines.SPECULARTERM) {
  42119. fallbacks.addFallback(0, "SPECULARTERM");
  42120. }
  42121. if (defines.DIFFUSEFRESNEL) {
  42122. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  42123. }
  42124. if (defines.OPACITYFRESNEL) {
  42125. fallbacks.addFallback(2, "OPACITYFRESNEL");
  42126. }
  42127. if (defines.REFLECTIONFRESNEL) {
  42128. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  42129. }
  42130. if (defines.EMISSIVEFRESNEL) {
  42131. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  42132. }
  42133. if (defines.FRESNEL) {
  42134. fallbacks.addFallback(4, "FRESNEL");
  42135. }
  42136. //Attributes
  42137. var attribs = [BABYLON.VertexBuffer.PositionKind];
  42138. if (defines.NORMAL) {
  42139. attribs.push(BABYLON.VertexBuffer.NormalKind);
  42140. }
  42141. if (defines.UV1) {
  42142. attribs.push(BABYLON.VertexBuffer.UVKind);
  42143. }
  42144. if (defines.UV2) {
  42145. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  42146. }
  42147. if (defines.VERTEXCOLOR) {
  42148. attribs.push(BABYLON.VertexBuffer.ColorKind);
  42149. }
  42150. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  42151. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  42152. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  42153. var shaderName = "default";
  42154. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  42155. "vFogInfos", "vFogColor", "pointSize",
  42156. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  42157. "mBones",
  42158. "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "normalMatrix", "lightmapMatrix", "refractionMatrix",
  42159. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  42160. "vReflectionPosition", "vReflectionSize",
  42161. "logarithmicDepthConstant", "vTangentSpaceParams", "alphaCutOff"
  42162. ];
  42163. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  42164. var uniformBuffers = ["Material", "Scene"];
  42165. if (BABYLON.ImageProcessingConfiguration) {
  42166. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  42167. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  42168. }
  42169. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  42170. uniformsNames: uniforms,
  42171. uniformBuffersNames: uniformBuffers,
  42172. samplers: samplers,
  42173. defines: defines,
  42174. maxSimultaneousLights: this._maxSimultaneousLights
  42175. });
  42176. if (this.customShaderNameResolve) {
  42177. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  42178. }
  42179. var join = defines.toString();
  42180. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  42181. attributes: attribs,
  42182. uniformsNames: uniforms,
  42183. uniformBuffersNames: uniformBuffers,
  42184. samplers: samplers,
  42185. defines: join,
  42186. fallbacks: fallbacks,
  42187. onCompiled: this.onCompiled,
  42188. onError: this.onError,
  42189. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  42190. }, engine), defines);
  42191. this.buildUniformLayout();
  42192. }
  42193. if (!subMesh.effect || !subMesh.effect.isReady()) {
  42194. return false;
  42195. }
  42196. defines._renderId = scene.getRenderId();
  42197. this._wasPreviouslyReady = true;
  42198. return true;
  42199. };
  42200. StandardMaterial.prototype.buildUniformLayout = function () {
  42201. // Order is important !
  42202. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  42203. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  42204. this._uniformBuffer.addUniform("opacityParts", 4);
  42205. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  42206. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  42207. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  42208. this._uniformBuffer.addUniform("refractionRightColor", 4);
  42209. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  42210. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  42211. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  42212. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  42213. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  42214. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  42215. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  42216. this._uniformBuffer.addUniform("vReflectionSize", 3);
  42217. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  42218. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  42219. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  42220. this._uniformBuffer.addUniform("vBumpInfos", 3);
  42221. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  42222. this._uniformBuffer.addUniform("ambientMatrix", 16);
  42223. this._uniformBuffer.addUniform("opacityMatrix", 16);
  42224. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  42225. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  42226. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  42227. this._uniformBuffer.addUniform("specularMatrix", 16);
  42228. this._uniformBuffer.addUniform("bumpMatrix", 16);
  42229. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  42230. this._uniformBuffer.addUniform("refractionMatrix", 16);
  42231. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  42232. this._uniformBuffer.addUniform("vSpecularColor", 4);
  42233. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  42234. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  42235. this._uniformBuffer.addUniform("pointSize", 1);
  42236. this._uniformBuffer.create();
  42237. };
  42238. StandardMaterial.prototype.unbind = function () {
  42239. if (this._activeEffect) {
  42240. var needFlag = false;
  42241. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  42242. this._activeEffect.setTexture("reflection2DSampler", null);
  42243. needFlag = true;
  42244. }
  42245. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  42246. this._activeEffect.setTexture("refraction2DSampler", null);
  42247. needFlag = true;
  42248. }
  42249. if (needFlag) {
  42250. this._markAllSubMeshesAsTexturesDirty();
  42251. }
  42252. }
  42253. _super.prototype.unbind.call(this);
  42254. };
  42255. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  42256. var scene = this.getScene();
  42257. var defines = subMesh._materialDefines;
  42258. if (!defines) {
  42259. return;
  42260. }
  42261. var effect = subMesh.effect;
  42262. if (!effect) {
  42263. return;
  42264. }
  42265. this._activeEffect = effect;
  42266. // Matrices
  42267. this.bindOnlyWorldMatrix(world);
  42268. // Normal Matrix
  42269. if (defines.OBJECTSPACE_NORMALMAP) {
  42270. world.toNormalMatrix(this._normalMatrix);
  42271. this.bindOnlyNormalMatrix(this._normalMatrix);
  42272. }
  42273. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  42274. // Bones
  42275. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  42276. if (mustRebind) {
  42277. this._uniformBuffer.bindToEffect(effect, "Material");
  42278. this.bindViewProjection(effect);
  42279. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  42280. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  42281. // Fresnel
  42282. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  42283. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  42284. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  42285. }
  42286. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  42287. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  42288. }
  42289. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  42290. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  42291. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  42292. }
  42293. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  42294. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  42295. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  42296. }
  42297. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  42298. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  42299. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  42300. }
  42301. }
  42302. // Textures
  42303. if (scene.texturesEnabled) {
  42304. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  42305. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  42306. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  42307. if (this._diffuseTexture.hasAlpha) {
  42308. effect.setFloat("alphaCutOff", this.alphaCutOff);
  42309. }
  42310. }
  42311. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  42312. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  42313. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  42314. }
  42315. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  42316. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  42317. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  42318. }
  42319. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  42320. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  42321. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  42322. if (this._reflectionTexture.boundingBoxSize) {
  42323. var cubeTexture = this._reflectionTexture;
  42324. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  42325. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  42326. }
  42327. }
  42328. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  42329. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  42330. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  42331. }
  42332. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  42333. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  42334. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  42335. }
  42336. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  42337. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  42338. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  42339. }
  42340. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  42341. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  42342. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  42343. if (scene._mirroredCameraPosition) {
  42344. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  42345. }
  42346. else {
  42347. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  42348. }
  42349. }
  42350. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  42351. var depth = 1.0;
  42352. if (!this._refractionTexture.isCube) {
  42353. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  42354. if (this._refractionTexture.depth) {
  42355. depth = this._refractionTexture.depth;
  42356. }
  42357. }
  42358. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  42359. }
  42360. }
  42361. // Point size
  42362. if (this.pointsCloud) {
  42363. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  42364. }
  42365. if (defines.SPECULARTERM) {
  42366. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  42367. }
  42368. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  42369. // Diffuse
  42370. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  42371. }
  42372. // Textures
  42373. if (scene.texturesEnabled) {
  42374. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  42375. effect.setTexture("diffuseSampler", this._diffuseTexture);
  42376. }
  42377. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  42378. effect.setTexture("ambientSampler", this._ambientTexture);
  42379. }
  42380. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  42381. effect.setTexture("opacitySampler", this._opacityTexture);
  42382. }
  42383. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  42384. if (this._reflectionTexture.isCube) {
  42385. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  42386. }
  42387. else {
  42388. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  42389. }
  42390. }
  42391. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  42392. effect.setTexture("emissiveSampler", this._emissiveTexture);
  42393. }
  42394. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  42395. effect.setTexture("lightmapSampler", this._lightmapTexture);
  42396. }
  42397. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  42398. effect.setTexture("specularSampler", this._specularTexture);
  42399. }
  42400. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  42401. effect.setTexture("bumpSampler", this._bumpTexture);
  42402. }
  42403. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  42404. var depth = 1.0;
  42405. if (this._refractionTexture.isCube) {
  42406. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  42407. }
  42408. else {
  42409. effect.setTexture("refraction2DSampler", this._refractionTexture);
  42410. }
  42411. }
  42412. }
  42413. // Clip plane
  42414. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  42415. // Colors
  42416. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  42417. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  42418. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  42419. }
  42420. if (mustRebind || !this.isFrozen) {
  42421. // Lights
  42422. if (scene.lightsEnabled && !this._disableLighting) {
  42423. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  42424. }
  42425. // View
  42426. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  42427. this.bindView(effect);
  42428. }
  42429. // Fog
  42430. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  42431. // Morph targets
  42432. if (defines.NUM_MORPH_INFLUENCERS) {
  42433. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  42434. }
  42435. // Log. depth
  42436. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  42437. // image processing
  42438. if (this._imageProcessingConfiguration && !this._imageProcessingConfiguration.applyByPostProcess) {
  42439. this._imageProcessingConfiguration.bind(this._activeEffect);
  42440. }
  42441. }
  42442. this._uniformBuffer.update();
  42443. this._afterBind(mesh, this._activeEffect);
  42444. };
  42445. StandardMaterial.prototype.getAnimatables = function () {
  42446. var results = [];
  42447. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  42448. results.push(this._diffuseTexture);
  42449. }
  42450. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  42451. results.push(this._ambientTexture);
  42452. }
  42453. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  42454. results.push(this._opacityTexture);
  42455. }
  42456. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  42457. results.push(this._reflectionTexture);
  42458. }
  42459. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  42460. results.push(this._emissiveTexture);
  42461. }
  42462. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  42463. results.push(this._specularTexture);
  42464. }
  42465. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  42466. results.push(this._bumpTexture);
  42467. }
  42468. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  42469. results.push(this._lightmapTexture);
  42470. }
  42471. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  42472. results.push(this._refractionTexture);
  42473. }
  42474. return results;
  42475. };
  42476. StandardMaterial.prototype.getActiveTextures = function () {
  42477. var activeTextures = _super.prototype.getActiveTextures.call(this);
  42478. if (this._diffuseTexture) {
  42479. activeTextures.push(this._diffuseTexture);
  42480. }
  42481. if (this._ambientTexture) {
  42482. activeTextures.push(this._ambientTexture);
  42483. }
  42484. if (this._opacityTexture) {
  42485. activeTextures.push(this._opacityTexture);
  42486. }
  42487. if (this._reflectionTexture) {
  42488. activeTextures.push(this._reflectionTexture);
  42489. }
  42490. if (this._emissiveTexture) {
  42491. activeTextures.push(this._emissiveTexture);
  42492. }
  42493. if (this._specularTexture) {
  42494. activeTextures.push(this._specularTexture);
  42495. }
  42496. if (this._bumpTexture) {
  42497. activeTextures.push(this._bumpTexture);
  42498. }
  42499. if (this._lightmapTexture) {
  42500. activeTextures.push(this._lightmapTexture);
  42501. }
  42502. if (this._refractionTexture) {
  42503. activeTextures.push(this._refractionTexture);
  42504. }
  42505. return activeTextures;
  42506. };
  42507. StandardMaterial.prototype.hasTexture = function (texture) {
  42508. if (_super.prototype.hasTexture.call(this, texture)) {
  42509. return true;
  42510. }
  42511. if (this._diffuseTexture === texture) {
  42512. return true;
  42513. }
  42514. if (this._ambientTexture === texture) {
  42515. return true;
  42516. }
  42517. if (this._opacityTexture === texture) {
  42518. return true;
  42519. }
  42520. if (this._reflectionTexture === texture) {
  42521. return true;
  42522. }
  42523. if (this._emissiveTexture === texture) {
  42524. return true;
  42525. }
  42526. if (this._specularTexture === texture) {
  42527. return true;
  42528. }
  42529. if (this._bumpTexture === texture) {
  42530. return true;
  42531. }
  42532. if (this._lightmapTexture === texture) {
  42533. return true;
  42534. }
  42535. if (this._refractionTexture === texture) {
  42536. return true;
  42537. }
  42538. return false;
  42539. };
  42540. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  42541. if (forceDisposeTextures) {
  42542. if (this._diffuseTexture) {
  42543. this._diffuseTexture.dispose();
  42544. }
  42545. if (this._ambientTexture) {
  42546. this._ambientTexture.dispose();
  42547. }
  42548. if (this._opacityTexture) {
  42549. this._opacityTexture.dispose();
  42550. }
  42551. if (this._reflectionTexture) {
  42552. this._reflectionTexture.dispose();
  42553. }
  42554. if (this._emissiveTexture) {
  42555. this._emissiveTexture.dispose();
  42556. }
  42557. if (this._specularTexture) {
  42558. this._specularTexture.dispose();
  42559. }
  42560. if (this._bumpTexture) {
  42561. this._bumpTexture.dispose();
  42562. }
  42563. if (this._lightmapTexture) {
  42564. this._lightmapTexture.dispose();
  42565. }
  42566. if (this._refractionTexture) {
  42567. this._refractionTexture.dispose();
  42568. }
  42569. }
  42570. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  42571. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  42572. }
  42573. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  42574. };
  42575. StandardMaterial.prototype.clone = function (name) {
  42576. var _this = this;
  42577. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  42578. result.name = name;
  42579. result.id = name;
  42580. return result;
  42581. };
  42582. StandardMaterial.prototype.serialize = function () {
  42583. return BABYLON.SerializationHelper.Serialize(this);
  42584. };
  42585. // Statics
  42586. StandardMaterial.Parse = function (source, scene, rootUrl) {
  42587. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  42588. };
  42589. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  42590. get: function () {
  42591. return StandardMaterial._DiffuseTextureEnabled;
  42592. },
  42593. set: function (value) {
  42594. if (StandardMaterial._DiffuseTextureEnabled === value) {
  42595. return;
  42596. }
  42597. StandardMaterial._DiffuseTextureEnabled = value;
  42598. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42599. },
  42600. enumerable: true,
  42601. configurable: true
  42602. });
  42603. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  42604. get: function () {
  42605. return StandardMaterial._AmbientTextureEnabled;
  42606. },
  42607. set: function (value) {
  42608. if (StandardMaterial._AmbientTextureEnabled === value) {
  42609. return;
  42610. }
  42611. StandardMaterial._AmbientTextureEnabled = value;
  42612. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42613. },
  42614. enumerable: true,
  42615. configurable: true
  42616. });
  42617. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  42618. get: function () {
  42619. return StandardMaterial._OpacityTextureEnabled;
  42620. },
  42621. set: function (value) {
  42622. if (StandardMaterial._OpacityTextureEnabled === value) {
  42623. return;
  42624. }
  42625. StandardMaterial._OpacityTextureEnabled = value;
  42626. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42627. },
  42628. enumerable: true,
  42629. configurable: true
  42630. });
  42631. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  42632. get: function () {
  42633. return StandardMaterial._ReflectionTextureEnabled;
  42634. },
  42635. set: function (value) {
  42636. if (StandardMaterial._ReflectionTextureEnabled === value) {
  42637. return;
  42638. }
  42639. StandardMaterial._ReflectionTextureEnabled = value;
  42640. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42641. },
  42642. enumerable: true,
  42643. configurable: true
  42644. });
  42645. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  42646. get: function () {
  42647. return StandardMaterial._EmissiveTextureEnabled;
  42648. },
  42649. set: function (value) {
  42650. if (StandardMaterial._EmissiveTextureEnabled === value) {
  42651. return;
  42652. }
  42653. StandardMaterial._EmissiveTextureEnabled = value;
  42654. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42655. },
  42656. enumerable: true,
  42657. configurable: true
  42658. });
  42659. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  42660. get: function () {
  42661. return StandardMaterial._SpecularTextureEnabled;
  42662. },
  42663. set: function (value) {
  42664. if (StandardMaterial._SpecularTextureEnabled === value) {
  42665. return;
  42666. }
  42667. StandardMaterial._SpecularTextureEnabled = value;
  42668. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42669. },
  42670. enumerable: true,
  42671. configurable: true
  42672. });
  42673. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  42674. get: function () {
  42675. return StandardMaterial._BumpTextureEnabled;
  42676. },
  42677. set: function (value) {
  42678. if (StandardMaterial._BumpTextureEnabled === value) {
  42679. return;
  42680. }
  42681. StandardMaterial._BumpTextureEnabled = value;
  42682. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42683. },
  42684. enumerable: true,
  42685. configurable: true
  42686. });
  42687. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  42688. get: function () {
  42689. return StandardMaterial._LightmapTextureEnabled;
  42690. },
  42691. set: function (value) {
  42692. if (StandardMaterial._LightmapTextureEnabled === value) {
  42693. return;
  42694. }
  42695. StandardMaterial._LightmapTextureEnabled = value;
  42696. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42697. },
  42698. enumerable: true,
  42699. configurable: true
  42700. });
  42701. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  42702. get: function () {
  42703. return StandardMaterial._RefractionTextureEnabled;
  42704. },
  42705. set: function (value) {
  42706. if (StandardMaterial._RefractionTextureEnabled === value) {
  42707. return;
  42708. }
  42709. StandardMaterial._RefractionTextureEnabled = value;
  42710. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42711. },
  42712. enumerable: true,
  42713. configurable: true
  42714. });
  42715. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  42716. get: function () {
  42717. return StandardMaterial._ColorGradingTextureEnabled;
  42718. },
  42719. set: function (value) {
  42720. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  42721. return;
  42722. }
  42723. StandardMaterial._ColorGradingTextureEnabled = value;
  42724. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42725. },
  42726. enumerable: true,
  42727. configurable: true
  42728. });
  42729. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  42730. get: function () {
  42731. return StandardMaterial._FresnelEnabled;
  42732. },
  42733. set: function (value) {
  42734. if (StandardMaterial._FresnelEnabled === value) {
  42735. return;
  42736. }
  42737. StandardMaterial._FresnelEnabled = value;
  42738. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  42739. },
  42740. enumerable: true,
  42741. configurable: true
  42742. });
  42743. // Flags used to enable or disable a type of texture for all Standard Materials
  42744. StandardMaterial._DiffuseTextureEnabled = true;
  42745. StandardMaterial._AmbientTextureEnabled = true;
  42746. StandardMaterial._OpacityTextureEnabled = true;
  42747. StandardMaterial._ReflectionTextureEnabled = true;
  42748. StandardMaterial._EmissiveTextureEnabled = true;
  42749. StandardMaterial._SpecularTextureEnabled = true;
  42750. StandardMaterial._BumpTextureEnabled = true;
  42751. StandardMaterial._LightmapTextureEnabled = true;
  42752. StandardMaterial._RefractionTextureEnabled = true;
  42753. StandardMaterial._ColorGradingTextureEnabled = true;
  42754. StandardMaterial._FresnelEnabled = true;
  42755. __decorate([
  42756. BABYLON.serializeAsTexture("diffuseTexture")
  42757. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  42758. __decorate([
  42759. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  42760. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  42761. __decorate([
  42762. BABYLON.serializeAsTexture("ambientTexture")
  42763. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  42764. __decorate([
  42765. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42766. ], StandardMaterial.prototype, "ambientTexture", void 0);
  42767. __decorate([
  42768. BABYLON.serializeAsTexture("opacityTexture")
  42769. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  42770. __decorate([
  42771. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  42772. ], StandardMaterial.prototype, "opacityTexture", void 0);
  42773. __decorate([
  42774. BABYLON.serializeAsTexture("reflectionTexture")
  42775. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  42776. __decorate([
  42777. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42778. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  42779. __decorate([
  42780. BABYLON.serializeAsTexture("emissiveTexture")
  42781. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  42782. __decorate([
  42783. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42784. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  42785. __decorate([
  42786. BABYLON.serializeAsTexture("specularTexture")
  42787. ], StandardMaterial.prototype, "_specularTexture", void 0);
  42788. __decorate([
  42789. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42790. ], StandardMaterial.prototype, "specularTexture", void 0);
  42791. __decorate([
  42792. BABYLON.serializeAsTexture("bumpTexture")
  42793. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  42794. __decorate([
  42795. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42796. ], StandardMaterial.prototype, "bumpTexture", void 0);
  42797. __decorate([
  42798. BABYLON.serializeAsTexture("lightmapTexture")
  42799. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  42800. __decorate([
  42801. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42802. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  42803. __decorate([
  42804. BABYLON.serializeAsTexture("refractionTexture")
  42805. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  42806. __decorate([
  42807. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42808. ], StandardMaterial.prototype, "refractionTexture", void 0);
  42809. __decorate([
  42810. BABYLON.serializeAsColor3("ambient")
  42811. ], StandardMaterial.prototype, "ambientColor", void 0);
  42812. __decorate([
  42813. BABYLON.serializeAsColor3("diffuse")
  42814. ], StandardMaterial.prototype, "diffuseColor", void 0);
  42815. __decorate([
  42816. BABYLON.serializeAsColor3("specular")
  42817. ], StandardMaterial.prototype, "specularColor", void 0);
  42818. __decorate([
  42819. BABYLON.serializeAsColor3("emissive")
  42820. ], StandardMaterial.prototype, "emissiveColor", void 0);
  42821. __decorate([
  42822. BABYLON.serialize()
  42823. ], StandardMaterial.prototype, "specularPower", void 0);
  42824. __decorate([
  42825. BABYLON.serialize("useAlphaFromDiffuseTexture")
  42826. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  42827. __decorate([
  42828. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42829. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  42830. __decorate([
  42831. BABYLON.serialize("useEmissiveAsIllumination")
  42832. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  42833. __decorate([
  42834. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42835. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  42836. __decorate([
  42837. BABYLON.serialize("linkEmissiveWithDiffuse")
  42838. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  42839. __decorate([
  42840. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42841. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  42842. __decorate([
  42843. BABYLON.serialize("useSpecularOverAlpha")
  42844. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  42845. __decorate([
  42846. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42847. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  42848. __decorate([
  42849. BABYLON.serialize("useReflectionOverAlpha")
  42850. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  42851. __decorate([
  42852. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42853. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  42854. __decorate([
  42855. BABYLON.serialize("disableLighting")
  42856. ], StandardMaterial.prototype, "_disableLighting", void 0);
  42857. __decorate([
  42858. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  42859. ], StandardMaterial.prototype, "disableLighting", void 0);
  42860. __decorate([
  42861. BABYLON.serialize("useObjectSpaceNormalMap")
  42862. ], StandardMaterial.prototype, "_useObjectSpaceNormalMap", void 0);
  42863. __decorate([
  42864. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42865. ], StandardMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  42866. __decorate([
  42867. BABYLON.serialize("useParallax")
  42868. ], StandardMaterial.prototype, "_useParallax", void 0);
  42869. __decorate([
  42870. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42871. ], StandardMaterial.prototype, "useParallax", void 0);
  42872. __decorate([
  42873. BABYLON.serialize("useParallaxOcclusion")
  42874. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  42875. __decorate([
  42876. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42877. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  42878. __decorate([
  42879. BABYLON.serialize()
  42880. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  42881. __decorate([
  42882. BABYLON.serialize("roughness")
  42883. ], StandardMaterial.prototype, "_roughness", void 0);
  42884. __decorate([
  42885. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42886. ], StandardMaterial.prototype, "roughness", void 0);
  42887. __decorate([
  42888. BABYLON.serialize()
  42889. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  42890. __decorate([
  42891. BABYLON.serialize()
  42892. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  42893. __decorate([
  42894. BABYLON.serialize()
  42895. ], StandardMaterial.prototype, "alphaCutOff", void 0);
  42896. __decorate([
  42897. BABYLON.serialize("useLightmapAsShadowmap")
  42898. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  42899. __decorate([
  42900. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42901. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  42902. __decorate([
  42903. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  42904. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  42905. __decorate([
  42906. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  42907. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  42908. __decorate([
  42909. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  42910. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  42911. __decorate([
  42912. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelAndMiscDirty")
  42913. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  42914. __decorate([
  42915. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  42916. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  42917. __decorate([
  42918. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  42919. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  42920. __decorate([
  42921. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  42922. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  42923. __decorate([
  42924. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  42925. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  42926. __decorate([
  42927. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  42928. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  42929. __decorate([
  42930. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  42931. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  42932. __decorate([
  42933. BABYLON.serialize("useReflectionFresnelFromSpecular")
  42934. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  42935. __decorate([
  42936. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  42937. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  42938. __decorate([
  42939. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  42940. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  42941. __decorate([
  42942. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42943. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  42944. __decorate([
  42945. BABYLON.serialize("maxSimultaneousLights")
  42946. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  42947. __decorate([
  42948. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  42949. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  42950. __decorate([
  42951. BABYLON.serialize("invertNormalMapX")
  42952. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  42953. __decorate([
  42954. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42955. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  42956. __decorate([
  42957. BABYLON.serialize("invertNormalMapY")
  42958. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  42959. __decorate([
  42960. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42961. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  42962. __decorate([
  42963. BABYLON.serialize("twoSidedLighting")
  42964. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  42965. __decorate([
  42966. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42967. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  42968. __decorate([
  42969. BABYLON.serialize()
  42970. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  42971. return StandardMaterial;
  42972. }(BABYLON.PushMaterial));
  42973. BABYLON.StandardMaterial = StandardMaterial;
  42974. })(BABYLON || (BABYLON = {}));
  42975. //# sourceMappingURL=babylon.standardMaterial.js.map
  42976. var BABYLON;
  42977. (function (BABYLON) {
  42978. /**
  42979. * Class representing spherical polynomial coefficients to the 3rd degree
  42980. */
  42981. var SphericalPolynomial = /** @class */ (function () {
  42982. function SphericalPolynomial() {
  42983. /**
  42984. * The x coefficients of the spherical polynomial
  42985. */
  42986. this.x = BABYLON.Vector3.Zero();
  42987. /**
  42988. * The y coefficients of the spherical polynomial
  42989. */
  42990. this.y = BABYLON.Vector3.Zero();
  42991. /**
  42992. * The z coefficients of the spherical polynomial
  42993. */
  42994. this.z = BABYLON.Vector3.Zero();
  42995. /**
  42996. * The xx coefficients of the spherical polynomial
  42997. */
  42998. this.xx = BABYLON.Vector3.Zero();
  42999. /**
  43000. * The yy coefficients of the spherical polynomial
  43001. */
  43002. this.yy = BABYLON.Vector3.Zero();
  43003. /**
  43004. * The zz coefficients of the spherical polynomial
  43005. */
  43006. this.zz = BABYLON.Vector3.Zero();
  43007. /**
  43008. * The xy coefficients of the spherical polynomial
  43009. */
  43010. this.xy = BABYLON.Vector3.Zero();
  43011. /**
  43012. * The yz coefficients of the spherical polynomial
  43013. */
  43014. this.yz = BABYLON.Vector3.Zero();
  43015. /**
  43016. * The zx coefficients of the spherical polynomial
  43017. */
  43018. this.zx = BABYLON.Vector3.Zero();
  43019. }
  43020. /**
  43021. * Adds an ambient color to the spherical polynomial
  43022. * @param color the color to add
  43023. */
  43024. SphericalPolynomial.prototype.addAmbient = function (color) {
  43025. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  43026. this.xx = this.xx.add(colorVector);
  43027. this.yy = this.yy.add(colorVector);
  43028. this.zz = this.zz.add(colorVector);
  43029. };
  43030. /**
  43031. * Scales the spherical polynomial by the given amount
  43032. * @param scale the amount to scale
  43033. */
  43034. SphericalPolynomial.prototype.scale = function (scale) {
  43035. this.x = this.x.scale(scale);
  43036. this.y = this.y.scale(scale);
  43037. this.z = this.z.scale(scale);
  43038. this.xx = this.xx.scale(scale);
  43039. this.yy = this.yy.scale(scale);
  43040. this.zz = this.zz.scale(scale);
  43041. this.yz = this.yz.scale(scale);
  43042. this.zx = this.zx.scale(scale);
  43043. this.xy = this.xy.scale(scale);
  43044. };
  43045. /**
  43046. * Gets the spherical polynomial from harmonics
  43047. * @param harmonics the spherical harmonics
  43048. * @returns the spherical polynomial
  43049. */
  43050. SphericalPolynomial.FromHarmonics = function (harmonics) {
  43051. var result = new SphericalPolynomial();
  43052. result.x = harmonics.l11.scale(1.02333);
  43053. result.y = harmonics.l1_1.scale(1.02333);
  43054. result.z = harmonics.l10.scale(1.02333);
  43055. result.xx = harmonics.l00.scale(0.886277).subtract(harmonics.l20.scale(0.247708)).add(harmonics.lL22.scale(0.429043));
  43056. result.yy = harmonics.l00.scale(0.886277).subtract(harmonics.l20.scale(0.247708)).subtract(harmonics.lL22.scale(0.429043));
  43057. result.zz = harmonics.l00.scale(0.886277).add(harmonics.l20.scale(0.495417));
  43058. result.yz = harmonics.l2_1.scale(0.858086);
  43059. result.zx = harmonics.l21.scale(0.858086);
  43060. result.xy = harmonics.l2_2.scale(0.858086);
  43061. result.scale(1.0 / Math.PI);
  43062. return result;
  43063. };
  43064. /**
  43065. * Constructs a spherical polynomial from an array.
  43066. * @param data defines the 9x3 coefficients (x, y, z, xx, yy, zz, yz, zx, xy)
  43067. * @returns the spherical polynomial
  43068. */
  43069. SphericalPolynomial.FromArray = function (data) {
  43070. var sp = new SphericalPolynomial();
  43071. BABYLON.Vector3.FromArrayToRef(data[0], 0, sp.x);
  43072. BABYLON.Vector3.FromArrayToRef(data[1], 0, sp.y);
  43073. BABYLON.Vector3.FromArrayToRef(data[2], 0, sp.z);
  43074. BABYLON.Vector3.FromArrayToRef(data[3], 0, sp.xx);
  43075. BABYLON.Vector3.FromArrayToRef(data[4], 0, sp.yy);
  43076. BABYLON.Vector3.FromArrayToRef(data[5], 0, sp.zz);
  43077. BABYLON.Vector3.FromArrayToRef(data[6], 0, sp.yz);
  43078. BABYLON.Vector3.FromArrayToRef(data[7], 0, sp.zx);
  43079. BABYLON.Vector3.FromArrayToRef(data[8], 0, sp.xy);
  43080. return sp;
  43081. };
  43082. return SphericalPolynomial;
  43083. }());
  43084. BABYLON.SphericalPolynomial = SphericalPolynomial;
  43085. /**
  43086. * Class representing spherical harmonics coefficients to the 3rd degree
  43087. */
  43088. var SphericalHarmonics = /** @class */ (function () {
  43089. function SphericalHarmonics() {
  43090. /**
  43091. * The l0,0 coefficients of the spherical harmonics
  43092. */
  43093. this.l00 = BABYLON.Vector3.Zero();
  43094. /**
  43095. * The l1,-1 coefficients of the spherical harmonics
  43096. */
  43097. this.l1_1 = BABYLON.Vector3.Zero();
  43098. /**
  43099. * The l1,0 coefficients of the spherical harmonics
  43100. */
  43101. this.l10 = BABYLON.Vector3.Zero();
  43102. /**
  43103. * The l1,1 coefficients of the spherical harmonics
  43104. */
  43105. this.l11 = BABYLON.Vector3.Zero();
  43106. /**
  43107. * The l2,-2 coefficients of the spherical harmonics
  43108. */
  43109. this.l2_2 = BABYLON.Vector3.Zero();
  43110. /**
  43111. * The l2,-1 coefficients of the spherical harmonics
  43112. */
  43113. this.l2_1 = BABYLON.Vector3.Zero();
  43114. /**
  43115. * The l2,0 coefficients of the spherical harmonics
  43116. */
  43117. this.l20 = BABYLON.Vector3.Zero();
  43118. /**
  43119. * The l2,1 coefficients of the spherical harmonics
  43120. */
  43121. this.l21 = BABYLON.Vector3.Zero();
  43122. /**
  43123. * The l2,2 coefficients of the spherical harmonics
  43124. */
  43125. this.lL22 = BABYLON.Vector3.Zero();
  43126. }
  43127. /**
  43128. * Adds a light to the spherical harmonics
  43129. * @param direction the direction of the light
  43130. * @param color the color of the light
  43131. * @param deltaSolidAngle the delta solid angle of the light
  43132. */
  43133. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  43134. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  43135. var c = colorVector.scale(deltaSolidAngle);
  43136. this.l00 = this.l00.add(c.scale(0.282095));
  43137. this.l1_1 = this.l1_1.add(c.scale(0.488603 * direction.y));
  43138. this.l10 = this.l10.add(c.scale(0.488603 * direction.z));
  43139. this.l11 = this.l11.add(c.scale(0.488603 * direction.x));
  43140. this.l2_2 = this.l2_2.add(c.scale(1.092548 * direction.x * direction.y));
  43141. this.l2_1 = this.l2_1.add(c.scale(1.092548 * direction.y * direction.z));
  43142. this.l21 = this.l21.add(c.scale(1.092548 * direction.x * direction.z));
  43143. this.l20 = this.l20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  43144. this.lL22 = this.lL22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  43145. };
  43146. /**
  43147. * Scales the spherical harmonics by the given amount
  43148. * @param scale the amount to scale
  43149. */
  43150. SphericalHarmonics.prototype.scale = function (scale) {
  43151. this.l00 = this.l00.scale(scale);
  43152. this.l1_1 = this.l1_1.scale(scale);
  43153. this.l10 = this.l10.scale(scale);
  43154. this.l11 = this.l11.scale(scale);
  43155. this.l2_2 = this.l2_2.scale(scale);
  43156. this.l2_1 = this.l2_1.scale(scale);
  43157. this.l20 = this.l20.scale(scale);
  43158. this.l21 = this.l21.scale(scale);
  43159. this.lL22 = this.lL22.scale(scale);
  43160. };
  43161. /**
  43162. * Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  43163. *
  43164. * ```
  43165. * E_lm = A_l * L_lm
  43166. * ```
  43167. *
  43168. * In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  43169. * This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  43170. * the scaling factors are given in equation 9.
  43171. */
  43172. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  43173. // Constant (Band 0)
  43174. this.l00 = this.l00.scale(3.141593);
  43175. // Linear (Band 1)
  43176. this.l1_1 = this.l1_1.scale(2.094395);
  43177. this.l10 = this.l10.scale(2.094395);
  43178. this.l11 = this.l11.scale(2.094395);
  43179. // Quadratic (Band 2)
  43180. this.l2_2 = this.l2_2.scale(0.785398);
  43181. this.l2_1 = this.l2_1.scale(0.785398);
  43182. this.l20 = this.l20.scale(0.785398);
  43183. this.l21 = this.l21.scale(0.785398);
  43184. this.lL22 = this.lL22.scale(0.785398);
  43185. };
  43186. /**
  43187. * Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  43188. *
  43189. * ```
  43190. * L = (1/pi) * E * rho
  43191. * ```
  43192. *
  43193. * This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  43194. */
  43195. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  43196. this.scale(1.0 / Math.PI);
  43197. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  43198. // (The pixel shader must apply albedo after texture fetches, etc).
  43199. };
  43200. /**
  43201. * Gets the spherical harmonics from polynomial
  43202. * @param polynomial the spherical polynomial
  43203. * @returns the spherical harmonics
  43204. */
  43205. SphericalHarmonics.FromPolynomial = function (polynomial) {
  43206. var result = new SphericalHarmonics();
  43207. result.l00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  43208. result.l1_1 = polynomial.y.scale(0.977204);
  43209. result.l10 = polynomial.z.scale(0.977204);
  43210. result.l11 = polynomial.x.scale(0.977204);
  43211. result.l2_2 = polynomial.xy.scale(1.16538);
  43212. result.l2_1 = polynomial.yz.scale(1.16538);
  43213. result.l20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  43214. result.l21 = polynomial.zx.scale(1.16538);
  43215. result.lL22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  43216. result.scale(Math.PI);
  43217. return result;
  43218. };
  43219. /**
  43220. * Constructs a spherical harmonics from an array.
  43221. * @param data defines the 9x3 coefficients (l00, l1-1, l10, l11, l2-2, l2-1, l20, l21, l22)
  43222. * @returns the spherical harmonics
  43223. */
  43224. SphericalHarmonics.FromArray = function (data) {
  43225. var sh = new SphericalHarmonics();
  43226. BABYLON.Vector3.FromArrayToRef(data[0], 0, sh.l00);
  43227. BABYLON.Vector3.FromArrayToRef(data[1], 0, sh.l1_1);
  43228. BABYLON.Vector3.FromArrayToRef(data[2], 0, sh.l10);
  43229. BABYLON.Vector3.FromArrayToRef(data[3], 0, sh.l11);
  43230. BABYLON.Vector3.FromArrayToRef(data[4], 0, sh.l2_2);
  43231. BABYLON.Vector3.FromArrayToRef(data[5], 0, sh.l2_1);
  43232. BABYLON.Vector3.FromArrayToRef(data[6], 0, sh.l20);
  43233. BABYLON.Vector3.FromArrayToRef(data[7], 0, sh.l21);
  43234. BABYLON.Vector3.FromArrayToRef(data[8], 0, sh.lL22);
  43235. return sh;
  43236. };
  43237. return SphericalHarmonics;
  43238. }());
  43239. BABYLON.SphericalHarmonics = SphericalHarmonics;
  43240. })(BABYLON || (BABYLON = {}));
  43241. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  43242. var BABYLON;
  43243. (function (BABYLON) {
  43244. var FileFaceOrientation = /** @class */ (function () {
  43245. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  43246. this.name = name;
  43247. this.worldAxisForNormal = worldAxisForNormal;
  43248. this.worldAxisForFileX = worldAxisForFileX;
  43249. this.worldAxisForFileY = worldAxisForFileY;
  43250. }
  43251. return FileFaceOrientation;
  43252. }());
  43253. ;
  43254. /**
  43255. * Helper class dealing with the extraction of spherical polynomial dataArray
  43256. * from a cube map.
  43257. */
  43258. var CubeMapToSphericalPolynomialTools = /** @class */ (function () {
  43259. function CubeMapToSphericalPolynomialTools() {
  43260. }
  43261. /**
  43262. * Converts a texture to the according Spherical Polynomial data.
  43263. * This extracts the first 3 orders only as they are the only one used in the lighting.
  43264. *
  43265. * @param texture The texture to extract the information from.
  43266. * @return The Spherical Polynomial data.
  43267. */
  43268. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  43269. if (!texture.isCube) {
  43270. // Only supports cube Textures currently.
  43271. return null;
  43272. }
  43273. var size = texture.getSize().width;
  43274. var right = texture.readPixels(0);
  43275. var left = texture.readPixels(1);
  43276. var up;
  43277. var down;
  43278. if (texture.isRenderTarget) {
  43279. up = texture.readPixels(3);
  43280. down = texture.readPixels(2);
  43281. }
  43282. else {
  43283. up = texture.readPixels(2);
  43284. down = texture.readPixels(3);
  43285. }
  43286. var front = texture.readPixels(4);
  43287. var back = texture.readPixels(5);
  43288. var gammaSpace = texture.gammaSpace;
  43289. // Always read as RGBA.
  43290. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  43291. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  43292. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  43293. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  43294. }
  43295. var cubeInfo = {
  43296. size: size,
  43297. right: right,
  43298. left: left,
  43299. up: up,
  43300. down: down,
  43301. front: front,
  43302. back: back,
  43303. format: format,
  43304. type: type,
  43305. gammaSpace: gammaSpace,
  43306. };
  43307. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  43308. };
  43309. /**
  43310. * Converts a cubemap to the according Spherical Polynomial data.
  43311. * This extracts the first 3 orders only as they are the only one used in the lighting.
  43312. *
  43313. * @param cubeInfo The Cube map to extract the information from.
  43314. * @return The Spherical Polynomial data.
  43315. */
  43316. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  43317. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  43318. var totalSolidAngle = 0.0;
  43319. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  43320. var du = 2.0 / cubeInfo.size;
  43321. var dv = du;
  43322. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  43323. var minUV = du * 0.5 - 1.0;
  43324. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  43325. var fileFace = this.FileFaces[faceIndex];
  43326. var dataArray = cubeInfo[fileFace.name];
  43327. var v = minUV;
  43328. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  43329. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  43330. // Because SP is still linear, so summation is fine in that basis.
  43331. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  43332. for (var y = 0; y < cubeInfo.size; y++) {
  43333. var u = minUV;
  43334. for (var x = 0; x < cubeInfo.size; x++) {
  43335. // World direction (not normalised)
  43336. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  43337. worldDirection.normalize();
  43338. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  43339. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  43340. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  43341. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  43342. // Handle Integer types.
  43343. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  43344. r /= 255;
  43345. g /= 255;
  43346. b /= 255;
  43347. }
  43348. // Handle Gamma space textures.
  43349. if (cubeInfo.gammaSpace) {
  43350. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  43351. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  43352. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  43353. }
  43354. var color = new BABYLON.Color3(r, g, b);
  43355. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  43356. totalSolidAngle += deltaSolidAngle;
  43357. u += du;
  43358. }
  43359. v += dv;
  43360. }
  43361. }
  43362. // Solid angle for entire sphere is 4*pi
  43363. var sphereSolidAngle = 4.0 * Math.PI;
  43364. // Adjust the solid angle to allow for how many faces we processed.
  43365. var facesProcessed = 6.0;
  43366. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  43367. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  43368. // This is needed because the numerical integration over the cube uses a
  43369. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  43370. // and also to compensate for accumulative error due to float precision in the summation.
  43371. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  43372. sphericalHarmonics.scale(correctionFactor);
  43373. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  43374. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  43375. return BABYLON.SphericalPolynomial.FromHarmonics(sphericalHarmonics);
  43376. };
  43377. CubeMapToSphericalPolynomialTools.FileFaces = [
  43378. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  43379. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  43380. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  43381. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  43382. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  43383. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  43384. ];
  43385. return CubeMapToSphericalPolynomialTools;
  43386. }());
  43387. BABYLON.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  43388. })(BABYLON || (BABYLON = {}));
  43389. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  43390. var BABYLON;
  43391. (function (BABYLON) {
  43392. /**
  43393. * Manages the defines for the PBR Material.
  43394. * @hiddenChildren
  43395. */
  43396. var PBRMaterialDefines = /** @class */ (function (_super) {
  43397. __extends(PBRMaterialDefines, _super);
  43398. /**
  43399. * Initializes the PBR Material defines.
  43400. */
  43401. function PBRMaterialDefines() {
  43402. var _this = _super.call(this) || this;
  43403. _this.PBR = true;
  43404. _this.MAINUV1 = false;
  43405. _this.MAINUV2 = false;
  43406. _this.UV1 = false;
  43407. _this.UV2 = false;
  43408. _this.ALBEDO = false;
  43409. _this.ALBEDODIRECTUV = 0;
  43410. _this.VERTEXCOLOR = false;
  43411. _this.AMBIENT = false;
  43412. _this.AMBIENTDIRECTUV = 0;
  43413. _this.AMBIENTINGRAYSCALE = false;
  43414. _this.OPACITY = false;
  43415. _this.VERTEXALPHA = false;
  43416. _this.OPACITYDIRECTUV = 0;
  43417. _this.OPACITYRGB = false;
  43418. _this.ALPHATEST = false;
  43419. _this.DEPTHPREPASS = false;
  43420. _this.ALPHABLEND = false;
  43421. _this.ALPHAFROMALBEDO = false;
  43422. _this.ALPHATESTVALUE = "0.5";
  43423. _this.SPECULAROVERALPHA = false;
  43424. _this.RADIANCEOVERALPHA = false;
  43425. _this.ALPHAFRESNEL = false;
  43426. _this.LINEARALPHAFRESNEL = false;
  43427. _this.PREMULTIPLYALPHA = false;
  43428. _this.EMISSIVE = false;
  43429. _this.EMISSIVEDIRECTUV = 0;
  43430. _this.REFLECTIVITY = false;
  43431. _this.REFLECTIVITYDIRECTUV = 0;
  43432. _this.SPECULARTERM = false;
  43433. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  43434. _this.MICROSURFACEAUTOMATIC = false;
  43435. _this.LODBASEDMICROSFURACE = false;
  43436. _this.MICROSURFACEMAP = false;
  43437. _this.MICROSURFACEMAPDIRECTUV = 0;
  43438. _this.METALLICWORKFLOW = false;
  43439. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  43440. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  43441. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  43442. _this.AOSTOREINMETALMAPRED = false;
  43443. _this.ENVIRONMENTBRDF = false;
  43444. _this.NORMAL = false;
  43445. _this.TANGENT = false;
  43446. _this.BUMP = false;
  43447. _this.BUMPDIRECTUV = 0;
  43448. _this.OBJECTSPACE_NORMALMAP = false;
  43449. _this.PARALLAX = false;
  43450. _this.PARALLAXOCCLUSION = false;
  43451. _this.NORMALXYSCALE = true;
  43452. _this.LIGHTMAP = false;
  43453. _this.LIGHTMAPDIRECTUV = 0;
  43454. _this.USELIGHTMAPASSHADOWMAP = false;
  43455. _this.GAMMALIGHTMAP = false;
  43456. _this.REFLECTION = false;
  43457. _this.REFLECTIONMAP_3D = false;
  43458. _this.REFLECTIONMAP_SPHERICAL = false;
  43459. _this.REFLECTIONMAP_PLANAR = false;
  43460. _this.REFLECTIONMAP_CUBIC = false;
  43461. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  43462. _this.REFLECTIONMAP_PROJECTION = false;
  43463. _this.REFLECTIONMAP_SKYBOX = false;
  43464. _this.REFLECTIONMAP_SKYBOX_TRANSFORMED = false;
  43465. _this.REFLECTIONMAP_EXPLICIT = false;
  43466. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  43467. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  43468. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  43469. _this.INVERTCUBICMAP = false;
  43470. _this.USESPHERICALFROMREFLECTIONMAP = false;
  43471. _this.USESPHERICALINVERTEX = false;
  43472. _this.REFLECTIONMAP_OPPOSITEZ = false;
  43473. _this.LODINREFLECTIONALPHA = false;
  43474. _this.GAMMAREFLECTION = false;
  43475. _this.RGBDREFLECTION = false;
  43476. _this.RADIANCEOCCLUSION = false;
  43477. _this.HORIZONOCCLUSION = false;
  43478. _this.REFRACTION = false;
  43479. _this.REFRACTIONMAP_3D = false;
  43480. _this.REFRACTIONMAP_OPPOSITEZ = false;
  43481. _this.LODINREFRACTIONALPHA = false;
  43482. _this.GAMMAREFRACTION = false;
  43483. _this.RGBDREFRACTION = false;
  43484. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  43485. _this.INSTANCES = false;
  43486. _this.NUM_BONE_INFLUENCERS = 0;
  43487. _this.BonesPerMesh = 0;
  43488. _this.NONUNIFORMSCALING = false;
  43489. _this.MORPHTARGETS = false;
  43490. _this.MORPHTARGETS_NORMAL = false;
  43491. _this.MORPHTARGETS_TANGENT = false;
  43492. _this.NUM_MORPH_INFLUENCERS = 0;
  43493. _this.IMAGEPROCESSING = false;
  43494. _this.VIGNETTE = false;
  43495. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  43496. _this.VIGNETTEBLENDMODEOPAQUE = false;
  43497. _this.TONEMAPPING = false;
  43498. _this.TONEMAPPING_ACES = false;
  43499. _this.CONTRAST = false;
  43500. _this.COLORCURVES = false;
  43501. _this.COLORGRADING = false;
  43502. _this.COLORGRADING3D = false;
  43503. _this.SAMPLER3DGREENDEPTH = false;
  43504. _this.SAMPLER3DBGRMAP = false;
  43505. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  43506. _this.EXPOSURE = false;
  43507. _this.USEPHYSICALLIGHTFALLOFF = false;
  43508. _this.USEGLTFLIGHTFALLOFF = false;
  43509. _this.TWOSIDEDLIGHTING = false;
  43510. _this.SHADOWFLOAT = false;
  43511. _this.CLIPPLANE = false;
  43512. _this.CLIPPLANE2 = false;
  43513. _this.CLIPPLANE3 = false;
  43514. _this.CLIPPLANE4 = false;
  43515. _this.POINTSIZE = false;
  43516. _this.FOG = false;
  43517. _this.LOGARITHMICDEPTH = false;
  43518. _this.FORCENORMALFORWARD = false;
  43519. _this.SPECULARAA = false;
  43520. _this.UNLIT = false;
  43521. _this.rebuild();
  43522. return _this;
  43523. }
  43524. /**
  43525. * Resets the PBR Material defines.
  43526. */
  43527. PBRMaterialDefines.prototype.reset = function () {
  43528. _super.prototype.reset.call(this);
  43529. this.ALPHATESTVALUE = "0.5";
  43530. this.PBR = true;
  43531. };
  43532. return PBRMaterialDefines;
  43533. }(BABYLON.MaterialDefines));
  43534. /**
  43535. * The Physically based material base class of BJS.
  43536. *
  43537. * This offers the main features of a standard PBR material.
  43538. * For more information, please refer to the documentation :
  43539. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  43540. */
  43541. var PBRBaseMaterial = /** @class */ (function (_super) {
  43542. __extends(PBRBaseMaterial, _super);
  43543. /**
  43544. * Instantiates a new PBRMaterial instance.
  43545. *
  43546. * @param name The material name
  43547. * @param scene The scene the material will be use in.
  43548. */
  43549. function PBRBaseMaterial(name, scene) {
  43550. var _this = _super.call(this, name, scene) || this;
  43551. /**
  43552. * Intensity of the direct lights e.g. the four lights available in your scene.
  43553. * This impacts both the direct diffuse and specular highlights.
  43554. */
  43555. _this._directIntensity = 1.0;
  43556. /**
  43557. * Intensity of the emissive part of the material.
  43558. * This helps controlling the emissive effect without modifying the emissive color.
  43559. */
  43560. _this._emissiveIntensity = 1.0;
  43561. /**
  43562. * Intensity of the environment e.g. how much the environment will light the object
  43563. * either through harmonics for rough material or through the refelction for shiny ones.
  43564. */
  43565. _this._environmentIntensity = 1.0;
  43566. /**
  43567. * This is a special control allowing the reduction of the specular highlights coming from the
  43568. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  43569. */
  43570. _this._specularIntensity = 1.0;
  43571. /**
  43572. * This stores the direct, emissive, environment, and specular light intensities into a Vector4.
  43573. */
  43574. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  43575. /**
  43576. * Debug Control allowing disabling the bump map on this material.
  43577. */
  43578. _this._disableBumpMap = false;
  43579. /**
  43580. * AKA Occlusion Texture Intensity in other nomenclature.
  43581. */
  43582. _this._ambientTextureStrength = 1.0;
  43583. /**
  43584. * Defines how much the AO map is occluding the analytical lights (point spot...).
  43585. * 1 means it completely occludes it
  43586. * 0 mean it has no impact
  43587. */
  43588. _this._ambientTextureImpactOnAnalyticalLights = BABYLON.PBRMaterial.DEFAULT_AO_ON_ANALYTICAL_LIGHTS;
  43589. /**
  43590. * The color of a material in ambient lighting.
  43591. */
  43592. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  43593. /**
  43594. * AKA Diffuse Color in other nomenclature.
  43595. */
  43596. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  43597. /**
  43598. * AKA Specular Color in other nomenclature.
  43599. */
  43600. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  43601. /**
  43602. * The color applied when light is reflected from a material.
  43603. */
  43604. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  43605. /**
  43606. * The color applied when light is emitted from a material.
  43607. */
  43608. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  43609. /**
  43610. * AKA Glossiness in other nomenclature.
  43611. */
  43612. _this._microSurface = 0.9;
  43613. /**
  43614. * source material index of refraction (IOR)' / 'destination material IOR.
  43615. */
  43616. _this._indexOfRefraction = 0.66;
  43617. /**
  43618. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  43619. */
  43620. _this._invertRefractionY = false;
  43621. /**
  43622. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  43623. * Materials half opaque for instance using refraction could benefit from this control.
  43624. */
  43625. _this._linkRefractionWithTransparency = false;
  43626. /**
  43627. * Specifies that the material will use the light map as a show map.
  43628. */
  43629. _this._useLightmapAsShadowmap = false;
  43630. /**
  43631. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  43632. * makes the reflect vector face the model (under horizon).
  43633. */
  43634. _this._useHorizonOcclusion = true;
  43635. /**
  43636. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  43637. * too much the area relying on ambient texture to define their ambient occlusion.
  43638. */
  43639. _this._useRadianceOcclusion = true;
  43640. /**
  43641. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  43642. */
  43643. _this._useAlphaFromAlbedoTexture = false;
  43644. /**
  43645. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  43646. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  43647. */
  43648. _this._useSpecularOverAlpha = true;
  43649. /**
  43650. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  43651. */
  43652. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  43653. /**
  43654. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  43655. */
  43656. _this._useRoughnessFromMetallicTextureAlpha = true;
  43657. /**
  43658. * Specifies if the metallic texture contains the roughness information in its green channel.
  43659. */
  43660. _this._useRoughnessFromMetallicTextureGreen = false;
  43661. /**
  43662. * Specifies if the metallic texture contains the metallness information in its blue channel.
  43663. */
  43664. _this._useMetallnessFromMetallicTextureBlue = false;
  43665. /**
  43666. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  43667. */
  43668. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  43669. /**
  43670. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  43671. */
  43672. _this._useAmbientInGrayScale = false;
  43673. /**
  43674. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  43675. * The material will try to infer what glossiness each pixel should be.
  43676. */
  43677. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  43678. /**
  43679. * Defines the falloff type used in this material.
  43680. * It by default is Physical.
  43681. */
  43682. _this._lightFalloff = PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL;
  43683. /**
  43684. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  43685. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  43686. */
  43687. _this._useRadianceOverAlpha = true;
  43688. /**
  43689. * Allows using an object space normal map (instead of tangent space).
  43690. */
  43691. _this._useObjectSpaceNormalMap = false;
  43692. /**
  43693. * Allows using the bump map in parallax mode.
  43694. */
  43695. _this._useParallax = false;
  43696. /**
  43697. * Allows using the bump map in parallax occlusion mode.
  43698. */
  43699. _this._useParallaxOcclusion = false;
  43700. /**
  43701. * Controls the scale bias of the parallax mode.
  43702. */
  43703. _this._parallaxScaleBias = 0.05;
  43704. /**
  43705. * If sets to true, disables all the lights affecting the material.
  43706. */
  43707. _this._disableLighting = false;
  43708. /**
  43709. * Number of Simultaneous lights allowed on the material.
  43710. */
  43711. _this._maxSimultaneousLights = 4;
  43712. /**
  43713. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  43714. */
  43715. _this._invertNormalMapX = false;
  43716. /**
  43717. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  43718. */
  43719. _this._invertNormalMapY = false;
  43720. /**
  43721. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  43722. */
  43723. _this._twoSidedLighting = false;
  43724. /**
  43725. * Defines the alpha limits in alpha test mode.
  43726. */
  43727. _this._alphaCutOff = 0.4;
  43728. /**
  43729. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  43730. */
  43731. _this._forceAlphaTest = false;
  43732. /**
  43733. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  43734. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  43735. */
  43736. _this._useAlphaFresnel = false;
  43737. /**
  43738. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  43739. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  43740. */
  43741. _this._useLinearAlphaFresnel = false;
  43742. /**
  43743. * The transparency mode of the material.
  43744. */
  43745. _this._transparencyMode = null;
  43746. /**
  43747. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  43748. * from cos thetav and roughness:
  43749. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  43750. */
  43751. _this._environmentBRDFTexture = null;
  43752. /**
  43753. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  43754. */
  43755. _this._forceIrradianceInFragment = false;
  43756. /**
  43757. * Force normal to face away from face.
  43758. */
  43759. _this._forceNormalForward = false;
  43760. /**
  43761. * Enables specular anti aliasing in the PBR shader.
  43762. * It will both interacts on the Geometry for analytical and IBL lighting.
  43763. * It also prefilter the roughness map based on the bump values.
  43764. */
  43765. _this._enableSpecularAntiAliasing = false;
  43766. /**
  43767. * Stores the available render targets.
  43768. */
  43769. _this._renderTargets = new BABYLON.SmartArray(16);
  43770. /**
  43771. * Sets the global ambient color for the material used in lighting calculations.
  43772. */
  43773. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  43774. /**
  43775. * If set to true, no lighting calculations will be applied.
  43776. */
  43777. _this._unlit = false;
  43778. // Setup the default processing configuration to the scene.
  43779. _this._attachImageProcessingConfiguration(null);
  43780. _this.getRenderTargetTextures = function () {
  43781. _this._renderTargets.reset();
  43782. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  43783. _this._renderTargets.push(_this._reflectionTexture);
  43784. }
  43785. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  43786. _this._renderTargets.push(_this._refractionTexture);
  43787. }
  43788. return _this._renderTargets;
  43789. };
  43790. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  43791. return _this;
  43792. }
  43793. /**
  43794. * Attaches a new image processing configuration to the PBR Material.
  43795. * @param configuration
  43796. */
  43797. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  43798. var _this = this;
  43799. if (configuration === this._imageProcessingConfiguration) {
  43800. return;
  43801. }
  43802. // Detaches observer.
  43803. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  43804. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  43805. }
  43806. // Pick the scene configuration if needed.
  43807. if (!configuration) {
  43808. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  43809. }
  43810. else {
  43811. this._imageProcessingConfiguration = configuration;
  43812. }
  43813. // Attaches observer.
  43814. if (this._imageProcessingConfiguration) {
  43815. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  43816. _this._markAllSubMeshesAsImageProcessingDirty();
  43817. });
  43818. }
  43819. };
  43820. Object.defineProperty(PBRBaseMaterial.prototype, "hasRenderTargetTextures", {
  43821. /**
  43822. * Gets a boolean indicating that current material needs to register RTT
  43823. */
  43824. get: function () {
  43825. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  43826. return true;
  43827. }
  43828. if (BABYLON.StandardMaterial.RefractionTextureEnabled && this._refractionTexture && this._refractionTexture.isRenderTarget) {
  43829. return true;
  43830. }
  43831. return false;
  43832. },
  43833. enumerable: true,
  43834. configurable: true
  43835. });
  43836. /**
  43837. * Gets the name of the material class.
  43838. */
  43839. PBRBaseMaterial.prototype.getClassName = function () {
  43840. return "PBRBaseMaterial";
  43841. };
  43842. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  43843. /**
  43844. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  43845. */
  43846. get: function () {
  43847. return this._useLogarithmicDepth;
  43848. },
  43849. /**
  43850. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  43851. */
  43852. set: function (value) {
  43853. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  43854. },
  43855. enumerable: true,
  43856. configurable: true
  43857. });
  43858. Object.defineProperty(PBRBaseMaterial.prototype, "transparencyMode", {
  43859. /**
  43860. * Gets the current transparency mode.
  43861. */
  43862. get: function () {
  43863. return this._transparencyMode;
  43864. },
  43865. /**
  43866. * Sets the transparency mode of the material.
  43867. *
  43868. * | Value | Type | Description |
  43869. * | ----- | ----------------------------------- | ----------- |
  43870. * | 0 | OPAQUE | |
  43871. * | 1 | ALPHATEST | |
  43872. * | 2 | ALPHABLEND | |
  43873. * | 3 | ALPHATESTANDBLEND | |
  43874. *
  43875. */
  43876. set: function (value) {
  43877. if (this._transparencyMode === value) {
  43878. return;
  43879. }
  43880. this._transparencyMode = value;
  43881. this._forceAlphaTest = (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND);
  43882. this._markAllSubMeshesAsTexturesAndMiscDirty();
  43883. },
  43884. enumerable: true,
  43885. configurable: true
  43886. });
  43887. Object.defineProperty(PBRBaseMaterial.prototype, "_disableAlphaBlending", {
  43888. /**
  43889. * Returns true if alpha blending should be disabled.
  43890. */
  43891. get: function () {
  43892. return (this._linkRefractionWithTransparency ||
  43893. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE ||
  43894. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  43895. },
  43896. enumerable: true,
  43897. configurable: true
  43898. });
  43899. /**
  43900. * Specifies whether or not this material should be rendered in alpha blend mode.
  43901. */
  43902. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  43903. if (this._disableAlphaBlending) {
  43904. return false;
  43905. }
  43906. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  43907. };
  43908. /**
  43909. * Specifies if the mesh will require alpha blending.
  43910. * @param mesh - BJS mesh.
  43911. */
  43912. PBRBaseMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  43913. if (this._disableAlphaBlending) {
  43914. return false;
  43915. }
  43916. return _super.prototype.needAlphaBlendingForMesh.call(this, mesh);
  43917. };
  43918. /**
  43919. * Specifies whether or not this material should be rendered in alpha test mode.
  43920. */
  43921. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  43922. if (this._forceAlphaTest) {
  43923. return true;
  43924. }
  43925. if (this._linkRefractionWithTransparency) {
  43926. return false;
  43927. }
  43928. return this._albedoTexture != null && this._albedoTexture.hasAlpha && (this._transparencyMode == null || this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  43929. };
  43930. /**
  43931. * Specifies whether or not the alpha value of the albedo texture should be used for alpha blending.
  43932. */
  43933. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  43934. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  43935. };
  43936. /**
  43937. * Gets the texture used for the alpha test.
  43938. */
  43939. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  43940. return this._albedoTexture;
  43941. };
  43942. /**
  43943. * Specifies that the submesh is ready to be used.
  43944. * @param mesh - BJS mesh.
  43945. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  43946. * @param useInstances - Specifies that instances should be used.
  43947. * @returns - boolean indicating that the submesh is ready or not.
  43948. */
  43949. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  43950. if (subMesh.effect && this.isFrozen) {
  43951. if (this._wasPreviouslyReady) {
  43952. return true;
  43953. }
  43954. }
  43955. if (!subMesh._materialDefines) {
  43956. subMesh._materialDefines = new PBRMaterialDefines();
  43957. }
  43958. var defines = subMesh._materialDefines;
  43959. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  43960. if (defines._renderId === this.getScene().getRenderId()) {
  43961. return true;
  43962. }
  43963. }
  43964. var scene = this.getScene();
  43965. var engine = scene.getEngine();
  43966. if (defines._areTexturesDirty) {
  43967. if (scene.texturesEnabled) {
  43968. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  43969. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  43970. return false;
  43971. }
  43972. }
  43973. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  43974. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  43975. return false;
  43976. }
  43977. }
  43978. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  43979. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  43980. return false;
  43981. }
  43982. }
  43983. var reflectionTexture = this._getReflectionTexture();
  43984. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  43985. if (!reflectionTexture.isReadyOrNotBlocking()) {
  43986. return false;
  43987. }
  43988. }
  43989. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  43990. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  43991. return false;
  43992. }
  43993. }
  43994. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  43995. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  43996. return false;
  43997. }
  43998. }
  43999. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44000. if (this._metallicTexture) {
  44001. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  44002. return false;
  44003. }
  44004. }
  44005. else if (this._reflectivityTexture) {
  44006. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  44007. return false;
  44008. }
  44009. }
  44010. if (this._microSurfaceTexture) {
  44011. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  44012. return false;
  44013. }
  44014. }
  44015. }
  44016. if (engine.getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44017. // Bump texture cannot be not blocking.
  44018. if (!this._bumpTexture.isReady()) {
  44019. return false;
  44020. }
  44021. }
  44022. var refractionTexture = this._getRefractionTexture();
  44023. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44024. if (!refractionTexture.isReadyOrNotBlocking()) {
  44025. return false;
  44026. }
  44027. }
  44028. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44029. // This is blocking.
  44030. if (!this._environmentBRDFTexture.isReady()) {
  44031. return false;
  44032. }
  44033. }
  44034. }
  44035. }
  44036. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  44037. if (!this._imageProcessingConfiguration.isReady()) {
  44038. return false;
  44039. }
  44040. }
  44041. if (!engine.getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  44042. mesh.createNormals(true);
  44043. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + mesh.name);
  44044. }
  44045. var effect = this._prepareEffect(mesh, defines, this.onCompiled, this.onError, useInstances);
  44046. if (effect) {
  44047. scene.resetCachedMaterial();
  44048. subMesh.setEffect(effect, defines);
  44049. this.buildUniformLayout();
  44050. }
  44051. if (!subMesh.effect || !subMesh.effect.isReady()) {
  44052. return false;
  44053. }
  44054. defines._renderId = scene.getRenderId();
  44055. this._wasPreviouslyReady = true;
  44056. return true;
  44057. };
  44058. /**
  44059. * Specifies if the material uses metallic roughness workflow.
  44060. * @returns boolean specifiying if the material uses metallic roughness workflow.
  44061. */
  44062. PBRBaseMaterial.prototype.isMetallicWorkflow = function () {
  44063. if (this._metallic != null || this._roughness != null || this._metallicTexture) {
  44064. return true;
  44065. }
  44066. return false;
  44067. };
  44068. PBRBaseMaterial.prototype._prepareEffect = function (mesh, defines, onCompiled, onError, useInstances, useClipPlane) {
  44069. if (onCompiled === void 0) { onCompiled = null; }
  44070. if (onError === void 0) { onError = null; }
  44071. if (useInstances === void 0) { useInstances = null; }
  44072. if (useClipPlane === void 0) { useClipPlane = null; }
  44073. this._prepareDefines(mesh, defines, useInstances, useClipPlane);
  44074. if (!defines.isDirty) {
  44075. return null;
  44076. }
  44077. defines.markAsProcessed();
  44078. var scene = this.getScene();
  44079. var engine = scene.getEngine();
  44080. // Fallbacks
  44081. var fallbacks = new BABYLON.EffectFallbacks();
  44082. var fallbackRank = 0;
  44083. if (defines.USESPHERICALINVERTEX) {
  44084. fallbacks.addFallback(fallbackRank++, "USESPHERICALINVERTEX");
  44085. }
  44086. if (defines.FOG) {
  44087. fallbacks.addFallback(fallbackRank, "FOG");
  44088. }
  44089. if (defines.SPECULARAA) {
  44090. fallbacks.addFallback(fallbackRank, "SPECULARAA");
  44091. }
  44092. if (defines.POINTSIZE) {
  44093. fallbacks.addFallback(fallbackRank, "POINTSIZE");
  44094. }
  44095. if (defines.LOGARITHMICDEPTH) {
  44096. fallbacks.addFallback(fallbackRank, "LOGARITHMICDEPTH");
  44097. }
  44098. if (defines.PARALLAX) {
  44099. fallbacks.addFallback(fallbackRank, "PARALLAX");
  44100. }
  44101. if (defines.PARALLAXOCCLUSION) {
  44102. fallbacks.addFallback(fallbackRank++, "PARALLAXOCCLUSION");
  44103. }
  44104. if (defines.ENVIRONMENTBRDF) {
  44105. fallbacks.addFallback(fallbackRank++, "ENVIRONMENTBRDF");
  44106. }
  44107. if (defines.TANGENT) {
  44108. fallbacks.addFallback(fallbackRank++, "TANGENT");
  44109. }
  44110. if (defines.BUMP) {
  44111. fallbacks.addFallback(fallbackRank++, "BUMP");
  44112. }
  44113. fallbackRank = BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++);
  44114. if (defines.SPECULARTERM) {
  44115. fallbacks.addFallback(fallbackRank++, "SPECULARTERM");
  44116. }
  44117. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  44118. fallbacks.addFallback(fallbackRank++, "USESPHERICALFROMREFLECTIONMAP");
  44119. }
  44120. if (defines.LIGHTMAP) {
  44121. fallbacks.addFallback(fallbackRank++, "LIGHTMAP");
  44122. }
  44123. if (defines.NORMAL) {
  44124. fallbacks.addFallback(fallbackRank++, "NORMAL");
  44125. }
  44126. if (defines.AMBIENT) {
  44127. fallbacks.addFallback(fallbackRank++, "AMBIENT");
  44128. }
  44129. if (defines.EMISSIVE) {
  44130. fallbacks.addFallback(fallbackRank++, "EMISSIVE");
  44131. }
  44132. if (defines.VERTEXCOLOR) {
  44133. fallbacks.addFallback(fallbackRank++, "VERTEXCOLOR");
  44134. }
  44135. if (defines.NUM_BONE_INFLUENCERS > 0) {
  44136. fallbacks.addCPUSkinningFallback(fallbackRank++, mesh);
  44137. }
  44138. if (defines.MORPHTARGETS) {
  44139. fallbacks.addFallback(fallbackRank++, "MORPHTARGETS");
  44140. }
  44141. //Attributes
  44142. var attribs = [BABYLON.VertexBuffer.PositionKind];
  44143. if (defines.NORMAL) {
  44144. attribs.push(BABYLON.VertexBuffer.NormalKind);
  44145. }
  44146. if (defines.TANGENT) {
  44147. attribs.push(BABYLON.VertexBuffer.TangentKind);
  44148. }
  44149. if (defines.UV1) {
  44150. attribs.push(BABYLON.VertexBuffer.UVKind);
  44151. }
  44152. if (defines.UV2) {
  44153. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  44154. }
  44155. if (defines.VERTEXCOLOR) {
  44156. attribs.push(BABYLON.VertexBuffer.ColorKind);
  44157. }
  44158. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  44159. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  44160. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  44161. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  44162. "vFogInfos", "vFogColor", "pointSize",
  44163. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vReflectionPosition", "vReflectionSize", "vEmissiveInfos", "vReflectivityInfos",
  44164. "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  44165. "mBones",
  44166. "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "normalMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  44167. "vLightingIntensity",
  44168. "logarithmicDepthConstant",
  44169. "vSphericalX", "vSphericalY", "vSphericalZ",
  44170. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  44171. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  44172. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  44173. "vTangentSpaceParams"
  44174. ];
  44175. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  44176. "bumpSampler", "lightmapSampler", "opacitySampler",
  44177. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  44178. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  44179. "microSurfaceSampler", "environmentBrdfSampler"];
  44180. var uniformBuffers = ["Material", "Scene"];
  44181. if (BABYLON.ImageProcessingConfiguration) {
  44182. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  44183. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  44184. }
  44185. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  44186. uniformsNames: uniforms,
  44187. uniformBuffersNames: uniformBuffers,
  44188. samplers: samplers,
  44189. defines: defines,
  44190. maxSimultaneousLights: this._maxSimultaneousLights
  44191. });
  44192. var join = defines.toString();
  44193. return engine.createEffect("pbr", {
  44194. attributes: attribs,
  44195. uniformsNames: uniforms,
  44196. uniformBuffersNames: uniformBuffers,
  44197. samplers: samplers,
  44198. defines: join,
  44199. fallbacks: fallbacks,
  44200. onCompiled: onCompiled,
  44201. onError: onError,
  44202. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  44203. }, engine);
  44204. };
  44205. PBRBaseMaterial.prototype._prepareDefines = function (mesh, defines, useInstances, useClipPlane) {
  44206. if (useInstances === void 0) { useInstances = null; }
  44207. if (useClipPlane === void 0) { useClipPlane = null; }
  44208. var scene = this.getScene();
  44209. var engine = scene.getEngine();
  44210. // Lights
  44211. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  44212. defines._needNormals = true;
  44213. // Textures
  44214. defines.METALLICWORKFLOW = this.isMetallicWorkflow();
  44215. if (defines._areTexturesDirty) {
  44216. defines._needUVs = false;
  44217. if (scene.texturesEnabled) {
  44218. if (scene.getEngine().getCaps().textureLOD) {
  44219. defines.LODBASEDMICROSFURACE = true;
  44220. }
  44221. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44222. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  44223. }
  44224. else {
  44225. defines.ALBEDO = false;
  44226. }
  44227. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44228. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  44229. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  44230. }
  44231. else {
  44232. defines.AMBIENT = false;
  44233. }
  44234. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44235. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  44236. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  44237. }
  44238. else {
  44239. defines.OPACITY = false;
  44240. }
  44241. var reflectionTexture = this._getReflectionTexture();
  44242. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44243. defines.REFLECTION = true;
  44244. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  44245. defines.RGBDREFLECTION = reflectionTexture.isRGBD;
  44246. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  44247. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  44248. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  44249. defines.INVERTCUBICMAP = true;
  44250. }
  44251. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  44252. switch (reflectionTexture.coordinatesMode) {
  44253. case BABYLON.Texture.EXPLICIT_MODE:
  44254. defines.REFLECTIONMAP_EXPLICIT = true;
  44255. break;
  44256. case BABYLON.Texture.PLANAR_MODE:
  44257. defines.REFLECTIONMAP_PLANAR = true;
  44258. break;
  44259. case BABYLON.Texture.PROJECTION_MODE:
  44260. defines.REFLECTIONMAP_PROJECTION = true;
  44261. break;
  44262. case BABYLON.Texture.SKYBOX_MODE:
  44263. defines.REFLECTIONMAP_SKYBOX = true;
  44264. break;
  44265. case BABYLON.Texture.SPHERICAL_MODE:
  44266. defines.REFLECTIONMAP_SPHERICAL = true;
  44267. break;
  44268. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  44269. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  44270. break;
  44271. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  44272. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  44273. break;
  44274. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  44275. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  44276. break;
  44277. case BABYLON.Texture.CUBIC_MODE:
  44278. case BABYLON.Texture.INVCUBIC_MODE:
  44279. default:
  44280. defines.REFLECTIONMAP_CUBIC = true;
  44281. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = reflectionTexture.boundingBoxSize ? true : false;
  44282. break;
  44283. }
  44284. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  44285. if (reflectionTexture.sphericalPolynomial) {
  44286. defines.USESPHERICALFROMREFLECTIONMAP = true;
  44287. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  44288. defines.USESPHERICALINVERTEX = false;
  44289. }
  44290. else {
  44291. defines.USESPHERICALINVERTEX = true;
  44292. }
  44293. }
  44294. }
  44295. else {
  44296. defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = !reflectionTexture.getReflectionTextureMatrix().isIdentity();
  44297. }
  44298. }
  44299. else {
  44300. defines.REFLECTION = false;
  44301. defines.REFLECTIONMAP_3D = false;
  44302. defines.REFLECTIONMAP_SPHERICAL = false;
  44303. defines.REFLECTIONMAP_PLANAR = false;
  44304. defines.REFLECTIONMAP_CUBIC = false;
  44305. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  44306. defines.REFLECTIONMAP_PROJECTION = false;
  44307. defines.REFLECTIONMAP_SKYBOX = false;
  44308. defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = false;
  44309. defines.REFLECTIONMAP_EXPLICIT = false;
  44310. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  44311. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  44312. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  44313. defines.INVERTCUBICMAP = false;
  44314. defines.USESPHERICALFROMREFLECTIONMAP = false;
  44315. defines.USESPHERICALINVERTEX = false;
  44316. defines.REFLECTIONMAP_OPPOSITEZ = false;
  44317. defines.LODINREFLECTIONALPHA = false;
  44318. defines.GAMMAREFLECTION = false;
  44319. defines.RGBDREFLECTION = false;
  44320. }
  44321. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44322. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  44323. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  44324. defines.GAMMALIGHTMAP = this._lightmapTexture.gammaSpace;
  44325. }
  44326. else {
  44327. defines.LIGHTMAP = false;
  44328. }
  44329. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44330. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  44331. }
  44332. else {
  44333. defines.EMISSIVE = false;
  44334. }
  44335. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44336. if (this._metallicTexture) {
  44337. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  44338. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  44339. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  44340. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  44341. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  44342. }
  44343. else if (this._reflectivityTexture) {
  44344. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  44345. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  44346. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  44347. }
  44348. else {
  44349. defines.REFLECTIVITY = false;
  44350. }
  44351. if (this._microSurfaceTexture) {
  44352. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  44353. }
  44354. else {
  44355. defines.MICROSURFACEMAP = false;
  44356. }
  44357. }
  44358. else {
  44359. defines.REFLECTIVITY = false;
  44360. defines.MICROSURFACEMAP = false;
  44361. }
  44362. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44363. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  44364. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44365. defines.PARALLAX = true;
  44366. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  44367. }
  44368. else {
  44369. defines.PARALLAX = false;
  44370. }
  44371. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  44372. }
  44373. else {
  44374. defines.BUMP = false;
  44375. }
  44376. var refractionTexture = this._getRefractionTexture();
  44377. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44378. defines.REFRACTION = true;
  44379. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  44380. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  44381. defines.RGBDREFRACTION = refractionTexture.isRGBD;
  44382. defines.REFRACTIONMAP_OPPOSITEZ = refractionTexture.invertZ;
  44383. defines.LODINREFRACTIONALPHA = refractionTexture.lodLevelInAlpha;
  44384. if (this._linkRefractionWithTransparency) {
  44385. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  44386. }
  44387. }
  44388. else {
  44389. defines.REFRACTION = false;
  44390. }
  44391. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44392. defines.ENVIRONMENTBRDF = true;
  44393. }
  44394. else {
  44395. defines.ENVIRONMENTBRDF = false;
  44396. }
  44397. if (this._shouldUseAlphaFromAlbedoTexture()) {
  44398. defines.ALPHAFROMALBEDO = true;
  44399. }
  44400. else {
  44401. defines.ALPHAFROMALBEDO = false;
  44402. }
  44403. }
  44404. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  44405. if (this._lightFalloff === PBRBaseMaterial.LIGHTFALLOFF_STANDARD) {
  44406. defines.USEPHYSICALLIGHTFALLOFF = false;
  44407. defines.USEGLTFLIGHTFALLOFF = false;
  44408. }
  44409. else if (this._lightFalloff === PBRBaseMaterial.LIGHTFALLOFF_GLTF) {
  44410. defines.USEPHYSICALLIGHTFALLOFF = false;
  44411. defines.USEGLTFLIGHTFALLOFF = true;
  44412. }
  44413. else {
  44414. defines.USEPHYSICALLIGHTFALLOFF = true;
  44415. defines.USEGLTFLIGHTFALLOFF = false;
  44416. }
  44417. defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;
  44418. if (!this.backFaceCulling && this._twoSidedLighting) {
  44419. defines.TWOSIDEDLIGHTING = true;
  44420. }
  44421. else {
  44422. defines.TWOSIDEDLIGHTING = false;
  44423. }
  44424. defines.ALPHATESTVALUE = "" + this._alphaCutOff + (this._alphaCutOff % 1 === 0 ? "." : "");
  44425. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  44426. defines.ALPHABLEND = this.needAlphaBlendingForMesh(mesh);
  44427. defines.ALPHAFRESNEL = this._useAlphaFresnel || this._useLinearAlphaFresnel;
  44428. defines.LINEARALPHAFRESNEL = this._useLinearAlphaFresnel;
  44429. defines.SPECULARAA = scene.getEngine().getCaps().standardDerivatives && this._enableSpecularAntiAliasing;
  44430. }
  44431. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  44432. this._imageProcessingConfiguration.prepareDefines(defines);
  44433. }
  44434. defines.FORCENORMALFORWARD = this._forceNormalForward;
  44435. defines.RADIANCEOCCLUSION = this._useRadianceOcclusion;
  44436. defines.HORIZONOCCLUSION = this._useHorizonOcclusion;
  44437. // Misc.
  44438. if (defines._areMiscDirty) {
  44439. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh) || this._forceAlphaTest, defines);
  44440. defines.UNLIT = this._unlit || ((this.pointsCloud || this.wireframe) && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  44441. }
  44442. // Values that need to be evaluated on every frame
  44443. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false, useClipPlane);
  44444. // Attribs
  44445. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true, this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE);
  44446. };
  44447. /**
  44448. * Force shader compilation
  44449. */
  44450. PBRBaseMaterial.prototype.forceCompilation = function (mesh, onCompiled, options) {
  44451. var _this = this;
  44452. var localOptions = __assign({ clipPlane: false }, options);
  44453. var defines = new PBRMaterialDefines();
  44454. var effect = this._prepareEffect(mesh, defines, undefined, undefined, undefined, localOptions.clipPlane);
  44455. if (effect.isReady()) {
  44456. if (onCompiled) {
  44457. onCompiled(this);
  44458. }
  44459. }
  44460. else {
  44461. effect.onCompileObservable.add(function () {
  44462. if (onCompiled) {
  44463. onCompiled(_this);
  44464. }
  44465. });
  44466. }
  44467. };
  44468. /**
  44469. * Initializes the uniform buffer layout for the shader.
  44470. */
  44471. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  44472. // Order is important !
  44473. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  44474. this._uniformBuffer.addUniform("vAmbientInfos", 4);
  44475. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  44476. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  44477. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  44478. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  44479. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  44480. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  44481. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  44482. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  44483. this._uniformBuffer.addUniform("vReflectionSize", 3);
  44484. this._uniformBuffer.addUniform("vBumpInfos", 3);
  44485. this._uniformBuffer.addUniform("albedoMatrix", 16);
  44486. this._uniformBuffer.addUniform("ambientMatrix", 16);
  44487. this._uniformBuffer.addUniform("opacityMatrix", 16);
  44488. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  44489. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  44490. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  44491. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  44492. this._uniformBuffer.addUniform("bumpMatrix", 16);
  44493. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  44494. this._uniformBuffer.addUniform("refractionMatrix", 16);
  44495. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  44496. this._uniformBuffer.addUniform("vReflectionColor", 3);
  44497. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  44498. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  44499. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  44500. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  44501. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  44502. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  44503. this._uniformBuffer.addUniform("pointSize", 1);
  44504. this._uniformBuffer.create();
  44505. };
  44506. /**
  44507. * Unbinds the textures.
  44508. */
  44509. PBRBaseMaterial.prototype.unbind = function () {
  44510. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  44511. this._uniformBuffer.setTexture("reflectionSampler", null);
  44512. }
  44513. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  44514. this._uniformBuffer.setTexture("refractionSampler", null);
  44515. }
  44516. _super.prototype.unbind.call(this);
  44517. };
  44518. /**
  44519. * Binds the submesh data.
  44520. * @param world - The world matrix.
  44521. * @param mesh - The BJS mesh.
  44522. * @param subMesh - A submesh of the BJS mesh.
  44523. */
  44524. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  44525. var scene = this.getScene();
  44526. var defines = subMesh._materialDefines;
  44527. if (!defines) {
  44528. return;
  44529. }
  44530. var effect = subMesh.effect;
  44531. if (!effect) {
  44532. return;
  44533. }
  44534. this._activeEffect = effect;
  44535. // Matrices
  44536. this.bindOnlyWorldMatrix(world);
  44537. // Normal Matrix
  44538. if (defines.OBJECTSPACE_NORMALMAP) {
  44539. world.toNormalMatrix(this._normalMatrix);
  44540. this.bindOnlyNormalMatrix(this._normalMatrix);
  44541. }
  44542. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  44543. // Bones
  44544. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  44545. var reflectionTexture = null;
  44546. if (mustRebind) {
  44547. this._uniformBuffer.bindToEffect(effect, "Material");
  44548. this.bindViewProjection(effect);
  44549. reflectionTexture = this._getReflectionTexture();
  44550. var refractionTexture = this._getRefractionTexture();
  44551. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  44552. // Texture uniforms
  44553. if (scene.texturesEnabled) {
  44554. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44555. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  44556. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  44557. }
  44558. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44559. this._uniformBuffer.updateFloat4("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength, this._ambientTextureImpactOnAnalyticalLights);
  44560. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  44561. }
  44562. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44563. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  44564. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  44565. }
  44566. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44567. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  44568. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  44569. if (reflectionTexture.boundingBoxSize) {
  44570. var cubeTexture = reflectionTexture;
  44571. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  44572. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  44573. }
  44574. var polynomials = reflectionTexture.sphericalPolynomial;
  44575. if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
  44576. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  44577. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  44578. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  44579. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  44580. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  44581. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  44582. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  44583. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  44584. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  44585. }
  44586. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  44587. }
  44588. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44589. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  44590. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  44591. }
  44592. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44593. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  44594. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  44595. }
  44596. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44597. if (this._metallicTexture) {
  44598. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  44599. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  44600. }
  44601. else if (this._reflectivityTexture) {
  44602. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  44603. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  44604. }
  44605. if (this._microSurfaceTexture) {
  44606. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  44607. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  44608. }
  44609. }
  44610. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44611. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  44612. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  44613. if (scene._mirroredCameraPosition) {
  44614. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  44615. }
  44616. else {
  44617. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  44618. }
  44619. }
  44620. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44621. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  44622. var depth = 1.0;
  44623. if (!refractionTexture.isCube) {
  44624. if (refractionTexture.depth) {
  44625. depth = refractionTexture.depth;
  44626. }
  44627. }
  44628. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  44629. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  44630. }
  44631. }
  44632. // Point size
  44633. if (this.pointsCloud) {
  44634. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  44635. }
  44636. // Colors
  44637. if (defines.METALLICWORKFLOW) {
  44638. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  44639. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  44640. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  44641. }
  44642. else {
  44643. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  44644. }
  44645. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  44646. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  44647. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  44648. // Misc
  44649. this._lightingInfos.x = this._directIntensity;
  44650. this._lightingInfos.y = this._emissiveIntensity;
  44651. this._lightingInfos.z = this._environmentIntensity;
  44652. this._lightingInfos.w = this._specularIntensity;
  44653. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  44654. }
  44655. // Textures
  44656. if (scene.texturesEnabled) {
  44657. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44658. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  44659. }
  44660. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44661. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  44662. }
  44663. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44664. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  44665. }
  44666. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44667. if (defines.LODBASEDMICROSFURACE) {
  44668. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  44669. }
  44670. else {
  44671. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  44672. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  44673. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  44674. }
  44675. }
  44676. if (defines.ENVIRONMENTBRDF) {
  44677. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  44678. }
  44679. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44680. if (defines.LODBASEDMICROSFURACE) {
  44681. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  44682. }
  44683. else {
  44684. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  44685. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  44686. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  44687. }
  44688. }
  44689. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44690. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  44691. }
  44692. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44693. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  44694. }
  44695. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44696. if (this._metallicTexture) {
  44697. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  44698. }
  44699. else if (this._reflectivityTexture) {
  44700. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  44701. }
  44702. if (this._microSurfaceTexture) {
  44703. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  44704. }
  44705. }
  44706. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44707. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  44708. }
  44709. }
  44710. // Clip plane
  44711. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  44712. // Colors
  44713. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  44714. var eyePosition = scene._forcedViewPosition ? scene._forcedViewPosition : (scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  44715. var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  44716. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
  44717. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  44718. }
  44719. if (mustRebind || !this.isFrozen) {
  44720. // Lights
  44721. if (scene.lightsEnabled && !this._disableLighting) {
  44722. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._lightFalloff !== PBRBaseMaterial.LIGHTFALLOFF_STANDARD);
  44723. }
  44724. // View
  44725. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  44726. this.bindView(effect);
  44727. }
  44728. // Fog
  44729. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect, true);
  44730. // Morph targets
  44731. if (defines.NUM_MORPH_INFLUENCERS) {
  44732. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  44733. }
  44734. // image processing
  44735. this._imageProcessingConfiguration.bind(this._activeEffect);
  44736. // Log. depth
  44737. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  44738. }
  44739. this._uniformBuffer.update();
  44740. this._afterBind(mesh, this._activeEffect);
  44741. };
  44742. /**
  44743. * Returns the animatable textures.
  44744. * @returns - Array of animatable textures.
  44745. */
  44746. PBRBaseMaterial.prototype.getAnimatables = function () {
  44747. var results = [];
  44748. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  44749. results.push(this._albedoTexture);
  44750. }
  44751. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  44752. results.push(this._ambientTexture);
  44753. }
  44754. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  44755. results.push(this._opacityTexture);
  44756. }
  44757. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  44758. results.push(this._reflectionTexture);
  44759. }
  44760. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  44761. results.push(this._emissiveTexture);
  44762. }
  44763. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  44764. results.push(this._metallicTexture);
  44765. }
  44766. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  44767. results.push(this._reflectivityTexture);
  44768. }
  44769. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  44770. results.push(this._bumpTexture);
  44771. }
  44772. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  44773. results.push(this._lightmapTexture);
  44774. }
  44775. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  44776. results.push(this._refractionTexture);
  44777. }
  44778. return results;
  44779. };
  44780. /**
  44781. * Returns the texture used for reflections.
  44782. * @returns - Reflection texture if present. Otherwise, returns the environment texture.
  44783. */
  44784. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  44785. if (this._reflectionTexture) {
  44786. return this._reflectionTexture;
  44787. }
  44788. return this.getScene().environmentTexture;
  44789. };
  44790. /**
  44791. * Returns the texture used for refraction or null if none is used.
  44792. * @returns - Refection texture if present. If no refraction texture and refraction
  44793. * is linked with transparency, returns environment texture. Otherwise, returns null.
  44794. */
  44795. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  44796. if (this._refractionTexture) {
  44797. return this._refractionTexture;
  44798. }
  44799. if (this._linkRefractionWithTransparency) {
  44800. return this.getScene().environmentTexture;
  44801. }
  44802. return null;
  44803. };
  44804. /**
  44805. * Disposes the resources of the material.
  44806. * @param forceDisposeEffect - Forces the disposal of effects.
  44807. * @param forceDisposeTextures - Forces the disposal of all textures.
  44808. */
  44809. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  44810. if (forceDisposeTextures) {
  44811. if (this._albedoTexture) {
  44812. this._albedoTexture.dispose();
  44813. }
  44814. if (this._ambientTexture) {
  44815. this._ambientTexture.dispose();
  44816. }
  44817. if (this._opacityTexture) {
  44818. this._opacityTexture.dispose();
  44819. }
  44820. if (this._reflectionTexture) {
  44821. this._reflectionTexture.dispose();
  44822. }
  44823. if (this._environmentBRDFTexture && this.getScene()._environmentBRDFTexture !== this._environmentBRDFTexture) {
  44824. this._environmentBRDFTexture.dispose();
  44825. }
  44826. if (this._emissiveTexture) {
  44827. this._emissiveTexture.dispose();
  44828. }
  44829. if (this._metallicTexture) {
  44830. this._metallicTexture.dispose();
  44831. }
  44832. if (this._reflectivityTexture) {
  44833. this._reflectivityTexture.dispose();
  44834. }
  44835. if (this._bumpTexture) {
  44836. this._bumpTexture.dispose();
  44837. }
  44838. if (this._lightmapTexture) {
  44839. this._lightmapTexture.dispose();
  44840. }
  44841. if (this._refractionTexture) {
  44842. this._refractionTexture.dispose();
  44843. }
  44844. }
  44845. this._renderTargets.dispose();
  44846. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  44847. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  44848. }
  44849. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  44850. };
  44851. /**
  44852. * PBRMaterialLightFalloff Physical: light is falling off following the inverse squared distance law.
  44853. */
  44854. PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL = 0;
  44855. /**
  44856. * PBRMaterialLightFalloff gltf: light is falling off as described in the gltf moving to PBR document
  44857. * to enhance interoperability with other engines.
  44858. */
  44859. PBRBaseMaterial.LIGHTFALLOFF_GLTF = 1;
  44860. /**
  44861. * PBRMaterialLightFalloff Standard: light is falling off like in the standard material
  44862. * to enhance interoperability with other materials.
  44863. */
  44864. PBRBaseMaterial.LIGHTFALLOFF_STANDARD = 2;
  44865. /**
  44866. * Stores the reflectivity values based on metallic roughness workflow.
  44867. */
  44868. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  44869. __decorate([
  44870. BABYLON.serializeAsImageProcessingConfiguration()
  44871. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  44872. __decorate([
  44873. BABYLON.serialize()
  44874. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  44875. __decorate([
  44876. BABYLON.serialize()
  44877. ], PBRBaseMaterial.prototype, "transparencyMode", null);
  44878. return PBRBaseMaterial;
  44879. }(BABYLON.PushMaterial));
  44880. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  44881. })(BABYLON || (BABYLON = {}));
  44882. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  44883. var BABYLON;
  44884. (function (BABYLON) {
  44885. /**
  44886. * The Physically based simple base material of BJS.
  44887. *
  44888. * This enables better naming and convention enforcements on top of the pbrMaterial.
  44889. * It is used as the base class for both the specGloss and metalRough conventions.
  44890. */
  44891. var PBRBaseSimpleMaterial = /** @class */ (function (_super) {
  44892. __extends(PBRBaseSimpleMaterial, _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 PBRBaseSimpleMaterial(name, scene) {
  44900. var _this = _super.call(this, name, scene) || this;
  44901. /**
  44902. * Number of Simultaneous lights allowed on the material.
  44903. */
  44904. _this.maxSimultaneousLights = 4;
  44905. /**
  44906. * If sets to true, disables all the lights affecting the material.
  44907. */
  44908. _this.disableLighting = false;
  44909. /**
  44910. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  44911. */
  44912. _this.invertNormalMapX = false;
  44913. /**
  44914. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  44915. */
  44916. _this.invertNormalMapY = false;
  44917. /**
  44918. * Emissivie color used to self-illuminate the model.
  44919. */
  44920. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  44921. /**
  44922. * Occlusion Channel Strenght.
  44923. */
  44924. _this.occlusionStrength = 1.0;
  44925. _this.useLightmapAsShadowmap = false;
  44926. _this._useAlphaFromAlbedoTexture = true;
  44927. _this._useAmbientInGrayScale = true;
  44928. return _this;
  44929. }
  44930. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  44931. /**
  44932. * Gets the current double sided mode.
  44933. */
  44934. get: function () {
  44935. return this._twoSidedLighting;
  44936. },
  44937. /**
  44938. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  44939. */
  44940. set: function (value) {
  44941. if (this._twoSidedLighting === value) {
  44942. return;
  44943. }
  44944. this._twoSidedLighting = value;
  44945. this.backFaceCulling = !value;
  44946. this._markAllSubMeshesAsTexturesDirty();
  44947. },
  44948. enumerable: true,
  44949. configurable: true
  44950. });
  44951. /**
  44952. * Return the active textures of the material.
  44953. */
  44954. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  44955. var activeTextures = _super.prototype.getActiveTextures.call(this);
  44956. if (this.environmentTexture) {
  44957. activeTextures.push(this.environmentTexture);
  44958. }
  44959. if (this.normalTexture) {
  44960. activeTextures.push(this.normalTexture);
  44961. }
  44962. if (this.emissiveTexture) {
  44963. activeTextures.push(this.emissiveTexture);
  44964. }
  44965. if (this.occlusionTexture) {
  44966. activeTextures.push(this.occlusionTexture);
  44967. }
  44968. if (this.lightmapTexture) {
  44969. activeTextures.push(this.lightmapTexture);
  44970. }
  44971. return activeTextures;
  44972. };
  44973. PBRBaseSimpleMaterial.prototype.hasTexture = function (texture) {
  44974. if (_super.prototype.hasTexture.call(this, texture)) {
  44975. return true;
  44976. }
  44977. if (this.lightmapTexture === texture) {
  44978. return true;
  44979. }
  44980. return false;
  44981. };
  44982. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  44983. return "PBRBaseSimpleMaterial";
  44984. };
  44985. __decorate([
  44986. BABYLON.serialize(),
  44987. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  44988. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  44989. __decorate([
  44990. BABYLON.serialize(),
  44991. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  44992. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  44993. __decorate([
  44994. BABYLON.serializeAsTexture(),
  44995. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  44996. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  44997. __decorate([
  44998. BABYLON.serialize(),
  44999. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45000. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  45001. __decorate([
  45002. BABYLON.serialize(),
  45003. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45004. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  45005. __decorate([
  45006. BABYLON.serializeAsTexture(),
  45007. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  45008. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  45009. __decorate([
  45010. BABYLON.serializeAsColor3("emissive"),
  45011. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45012. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  45013. __decorate([
  45014. BABYLON.serializeAsTexture(),
  45015. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45016. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  45017. __decorate([
  45018. BABYLON.serialize(),
  45019. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  45020. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  45021. __decorate([
  45022. BABYLON.serializeAsTexture(),
  45023. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  45024. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  45025. __decorate([
  45026. BABYLON.serialize(),
  45027. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  45028. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  45029. __decorate([
  45030. BABYLON.serialize()
  45031. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  45032. __decorate([
  45033. BABYLON.serializeAsTexture(),
  45034. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  45035. ], PBRBaseSimpleMaterial.prototype, "lightmapTexture", void 0);
  45036. __decorate([
  45037. BABYLON.serialize(),
  45038. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45039. ], PBRBaseSimpleMaterial.prototype, "useLightmapAsShadowmap", void 0);
  45040. return PBRBaseSimpleMaterial;
  45041. }(BABYLON.PBRBaseMaterial));
  45042. BABYLON.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  45043. })(BABYLON || (BABYLON = {}));
  45044. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  45045. var BABYLON;
  45046. (function (BABYLON) {
  45047. /**
  45048. * The Physically based material of BJS.
  45049. *
  45050. * This offers the main features of a standard PBR material.
  45051. * For more information, please refer to the documentation :
  45052. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  45053. */
  45054. var PBRMaterial = /** @class */ (function (_super) {
  45055. __extends(PBRMaterial, _super);
  45056. /**
  45057. * Instantiates a new PBRMaterial instance.
  45058. *
  45059. * @param name The material name
  45060. * @param scene The scene the material will be use in.
  45061. */
  45062. function PBRMaterial(name, scene) {
  45063. var _this = _super.call(this, name, scene) || this;
  45064. /**
  45065. * Intensity of the direct lights e.g. the four lights available in your scene.
  45066. * This impacts both the direct diffuse and specular highlights.
  45067. */
  45068. _this.directIntensity = 1.0;
  45069. /**
  45070. * Intensity of the emissive part of the material.
  45071. * This helps controlling the emissive effect without modifying the emissive color.
  45072. */
  45073. _this.emissiveIntensity = 1.0;
  45074. /**
  45075. * Intensity of the environment e.g. how much the environment will light the object
  45076. * either through harmonics for rough material or through the refelction for shiny ones.
  45077. */
  45078. _this.environmentIntensity = 1.0;
  45079. /**
  45080. * This is a special control allowing the reduction of the specular highlights coming from the
  45081. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  45082. */
  45083. _this.specularIntensity = 1.0;
  45084. /**
  45085. * Debug Control allowing disabling the bump map on this material.
  45086. */
  45087. _this.disableBumpMap = false;
  45088. /**
  45089. * AKA Occlusion Texture Intensity in other nomenclature.
  45090. */
  45091. _this.ambientTextureStrength = 1.0;
  45092. /**
  45093. * Defines how much the AO map is occluding the analytical lights (point spot...).
  45094. * 1 means it completely occludes it
  45095. * 0 mean it has no impact
  45096. */
  45097. _this.ambientTextureImpactOnAnalyticalLights = PBRMaterial.DEFAULT_AO_ON_ANALYTICAL_LIGHTS;
  45098. /**
  45099. * The color of a material in ambient lighting.
  45100. */
  45101. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  45102. /**
  45103. * AKA Diffuse Color in other nomenclature.
  45104. */
  45105. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  45106. /**
  45107. * AKA Specular Color in other nomenclature.
  45108. */
  45109. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  45110. /**
  45111. * The color reflected from the material.
  45112. */
  45113. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  45114. /**
  45115. * The color emitted from the material.
  45116. */
  45117. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  45118. /**
  45119. * AKA Glossiness in other nomenclature.
  45120. */
  45121. _this.microSurface = 1.0;
  45122. /**
  45123. * source material index of refraction (IOR)' / 'destination material IOR.
  45124. */
  45125. _this.indexOfRefraction = 0.66;
  45126. /**
  45127. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  45128. */
  45129. _this.invertRefractionY = false;
  45130. /**
  45131. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  45132. * Materials half opaque for instance using refraction could benefit from this control.
  45133. */
  45134. _this.linkRefractionWithTransparency = false;
  45135. _this.useLightmapAsShadowmap = false;
  45136. /**
  45137. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  45138. */
  45139. _this.useAlphaFromAlbedoTexture = false;
  45140. /**
  45141. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  45142. */
  45143. _this.forceAlphaTest = false;
  45144. /**
  45145. * Defines the alpha limits in alpha test mode.
  45146. */
  45147. _this.alphaCutOff = 0.4;
  45148. /**
  45149. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  45150. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  45151. */
  45152. _this.useSpecularOverAlpha = true;
  45153. /**
  45154. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  45155. */
  45156. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  45157. /**
  45158. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  45159. */
  45160. _this.useRoughnessFromMetallicTextureAlpha = true;
  45161. /**
  45162. * Specifies if the metallic texture contains the roughness information in its green channel.
  45163. */
  45164. _this.useRoughnessFromMetallicTextureGreen = false;
  45165. /**
  45166. * Specifies if the metallic texture contains the metallness information in its blue channel.
  45167. */
  45168. _this.useMetallnessFromMetallicTextureBlue = false;
  45169. /**
  45170. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  45171. */
  45172. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  45173. /**
  45174. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  45175. */
  45176. _this.useAmbientInGrayScale = false;
  45177. /**
  45178. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  45179. * The material will try to infer what glossiness each pixel should be.
  45180. */
  45181. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  45182. /**
  45183. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  45184. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  45185. */
  45186. _this.useRadianceOverAlpha = true;
  45187. /**
  45188. * Allows using an object space normal map (instead of tangent space).
  45189. */
  45190. _this.useObjectSpaceNormalMap = false;
  45191. /**
  45192. * Allows using the bump map in parallax mode.
  45193. */
  45194. _this.useParallax = false;
  45195. /**
  45196. * Allows using the bump map in parallax occlusion mode.
  45197. */
  45198. _this.useParallaxOcclusion = false;
  45199. /**
  45200. * Controls the scale bias of the parallax mode.
  45201. */
  45202. _this.parallaxScaleBias = 0.05;
  45203. /**
  45204. * If sets to true, disables all the lights affecting the material.
  45205. */
  45206. _this.disableLighting = false;
  45207. /**
  45208. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  45209. */
  45210. _this.forceIrradianceInFragment = false;
  45211. /**
  45212. * Number of Simultaneous lights allowed on the material.
  45213. */
  45214. _this.maxSimultaneousLights = 4;
  45215. /**
  45216. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  45217. */
  45218. _this.invertNormalMapX = false;
  45219. /**
  45220. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  45221. */
  45222. _this.invertNormalMapY = false;
  45223. /**
  45224. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  45225. */
  45226. _this.twoSidedLighting = false;
  45227. /**
  45228. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  45229. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  45230. */
  45231. _this.useAlphaFresnel = false;
  45232. /**
  45233. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  45234. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  45235. */
  45236. _this.useLinearAlphaFresnel = false;
  45237. /**
  45238. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  45239. * And/Or occlude the blended part.
  45240. */
  45241. _this.environmentBRDFTexture = null;
  45242. /**
  45243. * Force normal to face away from face.
  45244. */
  45245. _this.forceNormalForward = false;
  45246. /**
  45247. * Enables specular anti aliasing in the PBR shader.
  45248. * It will both interacts on the Geometry for analytical and IBL lighting.
  45249. * It also prefilter the roughness map based on the bump values.
  45250. */
  45251. _this.enableSpecularAntiAliasing = false;
  45252. /**
  45253. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  45254. * makes the reflect vector face the model (under horizon).
  45255. */
  45256. _this.useHorizonOcclusion = true;
  45257. /**
  45258. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  45259. * too much the area relying on ambient texture to define their ambient occlusion.
  45260. */
  45261. _this.useRadianceOcclusion = true;
  45262. /**
  45263. * If set to true, no lighting calculations will be applied.
  45264. */
  45265. _this.unlit = false;
  45266. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  45267. return _this;
  45268. }
  45269. Object.defineProperty(PBRMaterial.prototype, "usePhysicalLightFalloff", {
  45270. /**
  45271. * BJS is using an harcoded light falloff based on a manually sets up range.
  45272. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  45273. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  45274. */
  45275. get: function () {
  45276. return this._lightFalloff === BABYLON.PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL;
  45277. },
  45278. /**
  45279. * BJS is using an harcoded light falloff based on a manually sets up range.
  45280. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  45281. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  45282. */
  45283. set: function (value) {
  45284. if (value !== this.usePhysicalLightFalloff) {
  45285. // Ensure the effect will be rebuilt.
  45286. this._markAllSubMeshesAsTexturesDirty();
  45287. if (value) {
  45288. this._lightFalloff = BABYLON.PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL;
  45289. }
  45290. else {
  45291. this._lightFalloff = BABYLON.PBRBaseMaterial.LIGHTFALLOFF_STANDARD;
  45292. }
  45293. }
  45294. },
  45295. enumerable: true,
  45296. configurable: true
  45297. });
  45298. Object.defineProperty(PBRMaterial.prototype, "useGLTFLightFalloff", {
  45299. /**
  45300. * In order to support the falloff compatibility with gltf, a special mode has been added
  45301. * to reproduce the gltf light falloff.
  45302. */
  45303. get: function () {
  45304. return this._lightFalloff === BABYLON.PBRBaseMaterial.LIGHTFALLOFF_GLTF;
  45305. },
  45306. /**
  45307. * In order to support the falloff compatibility with gltf, a special mode has been added
  45308. * to reproduce the gltf light falloff.
  45309. */
  45310. set: function (value) {
  45311. if (value !== this.useGLTFLightFalloff) {
  45312. // Ensure the effect will be rebuilt.
  45313. this._markAllSubMeshesAsTexturesDirty();
  45314. if (value) {
  45315. this._lightFalloff = BABYLON.PBRBaseMaterial.LIGHTFALLOFF_GLTF;
  45316. }
  45317. else {
  45318. this._lightFalloff = BABYLON.PBRBaseMaterial.LIGHTFALLOFF_STANDARD;
  45319. }
  45320. }
  45321. },
  45322. enumerable: true,
  45323. configurable: true
  45324. });
  45325. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  45326. /**
  45327. * Gets the image processing configuration used either in this material.
  45328. */
  45329. get: function () {
  45330. return this._imageProcessingConfiguration;
  45331. },
  45332. /**
  45333. * Sets the Default image processing configuration used either in the this material.
  45334. *
  45335. * If sets to null, the scene one is in use.
  45336. */
  45337. set: function (value) {
  45338. this._attachImageProcessingConfiguration(value);
  45339. // Ensure the effect will be rebuilt.
  45340. this._markAllSubMeshesAsTexturesDirty();
  45341. },
  45342. enumerable: true,
  45343. configurable: true
  45344. });
  45345. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  45346. /**
  45347. * Gets wether the color curves effect is enabled.
  45348. */
  45349. get: function () {
  45350. return this.imageProcessingConfiguration.colorCurvesEnabled;
  45351. },
  45352. /**
  45353. * Sets wether the color curves effect is enabled.
  45354. */
  45355. set: function (value) {
  45356. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  45357. },
  45358. enumerable: true,
  45359. configurable: true
  45360. });
  45361. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  45362. /**
  45363. * Gets wether the color grading effect is enabled.
  45364. */
  45365. get: function () {
  45366. return this.imageProcessingConfiguration.colorGradingEnabled;
  45367. },
  45368. /**
  45369. * Gets wether the color grading effect is enabled.
  45370. */
  45371. set: function (value) {
  45372. this.imageProcessingConfiguration.colorGradingEnabled = value;
  45373. },
  45374. enumerable: true,
  45375. configurable: true
  45376. });
  45377. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  45378. /**
  45379. * Gets wether tonemapping is enabled or not.
  45380. */
  45381. get: function () {
  45382. return this._imageProcessingConfiguration.toneMappingEnabled;
  45383. },
  45384. /**
  45385. * Sets wether tonemapping is enabled or not
  45386. */
  45387. set: function (value) {
  45388. this._imageProcessingConfiguration.toneMappingEnabled = value;
  45389. },
  45390. enumerable: true,
  45391. configurable: true
  45392. });
  45393. ;
  45394. ;
  45395. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  45396. /**
  45397. * The camera exposure used on this material.
  45398. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  45399. * This corresponds to a photographic exposure.
  45400. */
  45401. get: function () {
  45402. return this._imageProcessingConfiguration.exposure;
  45403. },
  45404. /**
  45405. * The camera exposure used on this material.
  45406. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  45407. * This corresponds to a photographic exposure.
  45408. */
  45409. set: function (value) {
  45410. this._imageProcessingConfiguration.exposure = value;
  45411. },
  45412. enumerable: true,
  45413. configurable: true
  45414. });
  45415. ;
  45416. ;
  45417. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  45418. /**
  45419. * Gets The camera contrast used on this material.
  45420. */
  45421. get: function () {
  45422. return this._imageProcessingConfiguration.contrast;
  45423. },
  45424. /**
  45425. * Sets The camera contrast used on this material.
  45426. */
  45427. set: function (value) {
  45428. this._imageProcessingConfiguration.contrast = value;
  45429. },
  45430. enumerable: true,
  45431. configurable: true
  45432. });
  45433. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  45434. /**
  45435. * Gets the Color Grading 2D Lookup Texture.
  45436. */
  45437. get: function () {
  45438. return this._imageProcessingConfiguration.colorGradingTexture;
  45439. },
  45440. /**
  45441. * Sets the Color Grading 2D Lookup Texture.
  45442. */
  45443. set: function (value) {
  45444. this._imageProcessingConfiguration.colorGradingTexture = value;
  45445. },
  45446. enumerable: true,
  45447. configurable: true
  45448. });
  45449. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  45450. /**
  45451. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  45452. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  45453. * 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;
  45454. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  45455. */
  45456. get: function () {
  45457. return this._imageProcessingConfiguration.colorCurves;
  45458. },
  45459. /**
  45460. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  45461. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  45462. * 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;
  45463. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  45464. */
  45465. set: function (value) {
  45466. this._imageProcessingConfiguration.colorCurves = value;
  45467. },
  45468. enumerable: true,
  45469. configurable: true
  45470. });
  45471. /**
  45472. * Returns the name of this material class.
  45473. */
  45474. PBRMaterial.prototype.getClassName = function () {
  45475. return "PBRMaterial";
  45476. };
  45477. /**
  45478. * Returns an array of the actively used textures.
  45479. * @returns - Array of BaseTextures
  45480. */
  45481. PBRMaterial.prototype.getActiveTextures = function () {
  45482. var activeTextures = _super.prototype.getActiveTextures.call(this);
  45483. if (this._albedoTexture) {
  45484. activeTextures.push(this._albedoTexture);
  45485. }
  45486. if (this._ambientTexture) {
  45487. activeTextures.push(this._ambientTexture);
  45488. }
  45489. if (this._opacityTexture) {
  45490. activeTextures.push(this._opacityTexture);
  45491. }
  45492. if (this._reflectionTexture) {
  45493. activeTextures.push(this._reflectionTexture);
  45494. }
  45495. if (this._emissiveTexture) {
  45496. activeTextures.push(this._emissiveTexture);
  45497. }
  45498. if (this._reflectivityTexture) {
  45499. activeTextures.push(this._reflectivityTexture);
  45500. }
  45501. if (this._metallicTexture) {
  45502. activeTextures.push(this._metallicTexture);
  45503. }
  45504. if (this._microSurfaceTexture) {
  45505. activeTextures.push(this._microSurfaceTexture);
  45506. }
  45507. if (this._bumpTexture) {
  45508. activeTextures.push(this._bumpTexture);
  45509. }
  45510. if (this._lightmapTexture) {
  45511. activeTextures.push(this._lightmapTexture);
  45512. }
  45513. if (this._refractionTexture) {
  45514. activeTextures.push(this._refractionTexture);
  45515. }
  45516. return activeTextures;
  45517. };
  45518. /**
  45519. * Checks to see if a texture is used in the material.
  45520. * @param texture - Base texture to use.
  45521. * @returns - Boolean specifying if a texture is used in the material.
  45522. */
  45523. PBRMaterial.prototype.hasTexture = function (texture) {
  45524. if (_super.prototype.hasTexture.call(this, texture)) {
  45525. return true;
  45526. }
  45527. if (this._albedoTexture === texture) {
  45528. return true;
  45529. }
  45530. if (this._ambientTexture === texture) {
  45531. return true;
  45532. }
  45533. if (this._opacityTexture === texture) {
  45534. return true;
  45535. }
  45536. if (this._reflectionTexture === texture) {
  45537. return true;
  45538. }
  45539. if (this._reflectivityTexture === texture) {
  45540. return true;
  45541. }
  45542. if (this._metallicTexture === texture) {
  45543. return true;
  45544. }
  45545. if (this._microSurfaceTexture === texture) {
  45546. return true;
  45547. }
  45548. if (this._bumpTexture === texture) {
  45549. return true;
  45550. }
  45551. if (this._lightmapTexture === texture) {
  45552. return true;
  45553. }
  45554. if (this._refractionTexture === texture) {
  45555. return true;
  45556. }
  45557. return false;
  45558. };
  45559. /**
  45560. * Makes a duplicate of the current material.
  45561. * @param name - name to use for the new material.
  45562. */
  45563. PBRMaterial.prototype.clone = function (name) {
  45564. var _this = this;
  45565. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  45566. clone.id = name;
  45567. clone.name = name;
  45568. return clone;
  45569. };
  45570. /**
  45571. * Serializes this PBR Material.
  45572. * @returns - An object with the serialized material.
  45573. */
  45574. PBRMaterial.prototype.serialize = function () {
  45575. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  45576. serializationObject.customType = "BABYLON.PBRMaterial";
  45577. return serializationObject;
  45578. };
  45579. // Statics
  45580. /**
  45581. * Parses a PBR Material from a serialized object.
  45582. * @param source - Serialized object.
  45583. * @param scene - BJS scene instance.
  45584. * @param rootUrl - url for the scene object
  45585. * @returns - PBRMaterial
  45586. */
  45587. PBRMaterial.Parse = function (source, scene, rootUrl) {
  45588. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  45589. };
  45590. /**
  45591. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  45592. */
  45593. PBRMaterial.PBRMATERIAL_OPAQUE = 0;
  45594. /**
  45595. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  45596. */
  45597. PBRMaterial.PBRMATERIAL_ALPHATEST = 1;
  45598. /**
  45599. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  45600. */
  45601. PBRMaterial.PBRMATERIAL_ALPHABLEND = 2;
  45602. /**
  45603. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  45604. * They are also discarded below the alpha cutoff threshold to improve performances.
  45605. */
  45606. PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND = 3;
  45607. /**
  45608. * Defines the default value of how much AO map is occluding the analytical lights
  45609. * (point spot...).
  45610. */
  45611. PBRMaterial.DEFAULT_AO_ON_ANALYTICAL_LIGHTS = 1;
  45612. __decorate([
  45613. BABYLON.serialize(),
  45614. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45615. ], PBRMaterial.prototype, "directIntensity", void 0);
  45616. __decorate([
  45617. BABYLON.serialize(),
  45618. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45619. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  45620. __decorate([
  45621. BABYLON.serialize(),
  45622. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45623. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  45624. __decorate([
  45625. BABYLON.serialize(),
  45626. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45627. ], PBRMaterial.prototype, "specularIntensity", void 0);
  45628. __decorate([
  45629. BABYLON.serialize(),
  45630. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45631. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  45632. __decorate([
  45633. BABYLON.serializeAsTexture(),
  45634. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45635. ], PBRMaterial.prototype, "albedoTexture", void 0);
  45636. __decorate([
  45637. BABYLON.serializeAsTexture(),
  45638. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45639. ], PBRMaterial.prototype, "ambientTexture", void 0);
  45640. __decorate([
  45641. BABYLON.serialize(),
  45642. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45643. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  45644. __decorate([
  45645. BABYLON.serialize(),
  45646. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45647. ], PBRMaterial.prototype, "ambientTextureImpactOnAnalyticalLights", void 0);
  45648. __decorate([
  45649. BABYLON.serializeAsTexture(),
  45650. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45651. ], PBRMaterial.prototype, "opacityTexture", void 0);
  45652. __decorate([
  45653. BABYLON.serializeAsTexture(),
  45654. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45655. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  45656. __decorate([
  45657. BABYLON.serializeAsTexture(),
  45658. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45659. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  45660. __decorate([
  45661. BABYLON.serializeAsTexture(),
  45662. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45663. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  45664. __decorate([
  45665. BABYLON.serializeAsTexture(),
  45666. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45667. ], PBRMaterial.prototype, "metallicTexture", void 0);
  45668. __decorate([
  45669. BABYLON.serialize(),
  45670. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45671. ], PBRMaterial.prototype, "metallic", void 0);
  45672. __decorate([
  45673. BABYLON.serialize(),
  45674. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45675. ], PBRMaterial.prototype, "roughness", void 0);
  45676. __decorate([
  45677. BABYLON.serializeAsTexture(),
  45678. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45679. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  45680. __decorate([
  45681. BABYLON.serializeAsTexture(),
  45682. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45683. ], PBRMaterial.prototype, "bumpTexture", void 0);
  45684. __decorate([
  45685. BABYLON.serializeAsTexture(),
  45686. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  45687. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  45688. __decorate([
  45689. BABYLON.serializeAsTexture(),
  45690. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45691. ], PBRMaterial.prototype, "refractionTexture", void 0);
  45692. __decorate([
  45693. BABYLON.serializeAsColor3("ambient"),
  45694. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45695. ], PBRMaterial.prototype, "ambientColor", void 0);
  45696. __decorate([
  45697. BABYLON.serializeAsColor3("albedo"),
  45698. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45699. ], PBRMaterial.prototype, "albedoColor", void 0);
  45700. __decorate([
  45701. BABYLON.serializeAsColor3("reflectivity"),
  45702. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45703. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  45704. __decorate([
  45705. BABYLON.serializeAsColor3("reflection"),
  45706. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45707. ], PBRMaterial.prototype, "reflectionColor", void 0);
  45708. __decorate([
  45709. BABYLON.serializeAsColor3("emissive"),
  45710. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45711. ], PBRMaterial.prototype, "emissiveColor", void 0);
  45712. __decorate([
  45713. BABYLON.serialize(),
  45714. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45715. ], PBRMaterial.prototype, "microSurface", void 0);
  45716. __decorate([
  45717. BABYLON.serialize(),
  45718. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45719. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  45720. __decorate([
  45721. BABYLON.serialize(),
  45722. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45723. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  45724. __decorate([
  45725. BABYLON.serialize(),
  45726. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45727. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  45728. __decorate([
  45729. BABYLON.serialize(),
  45730. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45731. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  45732. __decorate([
  45733. BABYLON.serialize(),
  45734. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45735. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  45736. __decorate([
  45737. BABYLON.serialize(),
  45738. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45739. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  45740. __decorate([
  45741. BABYLON.serialize(),
  45742. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45743. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  45744. __decorate([
  45745. BABYLON.serialize(),
  45746. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45747. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  45748. __decorate([
  45749. BABYLON.serialize(),
  45750. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45751. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  45752. __decorate([
  45753. BABYLON.serialize(),
  45754. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45755. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  45756. __decorate([
  45757. BABYLON.serialize(),
  45758. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45759. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  45760. __decorate([
  45761. BABYLON.serialize(),
  45762. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45763. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  45764. __decorate([
  45765. BABYLON.serialize(),
  45766. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45767. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  45768. __decorate([
  45769. BABYLON.serialize(),
  45770. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45771. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  45772. __decorate([
  45773. BABYLON.serialize(),
  45774. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45775. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  45776. __decorate([
  45777. BABYLON.serialize()
  45778. ], PBRMaterial.prototype, "usePhysicalLightFalloff", null);
  45779. __decorate([
  45780. BABYLON.serialize()
  45781. ], PBRMaterial.prototype, "useGLTFLightFalloff", null);
  45782. __decorate([
  45783. BABYLON.serialize(),
  45784. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45785. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  45786. __decorate([
  45787. BABYLON.serialize(),
  45788. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45789. ], PBRMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  45790. __decorate([
  45791. BABYLON.serialize(),
  45792. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45793. ], PBRMaterial.prototype, "useParallax", void 0);
  45794. __decorate([
  45795. BABYLON.serialize(),
  45796. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45797. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  45798. __decorate([
  45799. BABYLON.serialize(),
  45800. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45801. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  45802. __decorate([
  45803. BABYLON.serialize(),
  45804. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45805. ], PBRMaterial.prototype, "disableLighting", void 0);
  45806. __decorate([
  45807. BABYLON.serialize(),
  45808. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45809. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  45810. __decorate([
  45811. BABYLON.serialize(),
  45812. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45813. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  45814. __decorate([
  45815. BABYLON.serialize(),
  45816. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45817. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  45818. __decorate([
  45819. BABYLON.serialize(),
  45820. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45821. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  45822. __decorate([
  45823. BABYLON.serialize(),
  45824. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45825. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  45826. __decorate([
  45827. BABYLON.serialize(),
  45828. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45829. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  45830. __decorate([
  45831. BABYLON.serialize(),
  45832. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45833. ], PBRMaterial.prototype, "useLinearAlphaFresnel", void 0);
  45834. __decorate([
  45835. BABYLON.serializeAsTexture(),
  45836. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45837. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  45838. __decorate([
  45839. BABYLON.serialize(),
  45840. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45841. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  45842. __decorate([
  45843. BABYLON.serialize(),
  45844. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45845. ], PBRMaterial.prototype, "enableSpecularAntiAliasing", void 0);
  45846. __decorate([
  45847. BABYLON.serialize(),
  45848. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45849. ], PBRMaterial.prototype, "useHorizonOcclusion", void 0);
  45850. __decorate([
  45851. BABYLON.serialize(),
  45852. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45853. ], PBRMaterial.prototype, "useRadianceOcclusion", void 0);
  45854. __decorate([
  45855. BABYLON.serialize(),
  45856. BABYLON.expandToProperty("_markAllSubMeshesAsMiscDirty")
  45857. ], PBRMaterial.prototype, "unlit", void 0);
  45858. return PBRMaterial;
  45859. }(BABYLON.PBRBaseMaterial));
  45860. BABYLON.PBRMaterial = PBRMaterial;
  45861. })(BABYLON || (BABYLON = {}));
  45862. //# sourceMappingURL=babylon.pbrMaterial.js.map
  45863. var BABYLON;
  45864. (function (BABYLON) {
  45865. /**
  45866. * The PBR material of BJS following the metal roughness convention.
  45867. *
  45868. * This fits to the PBR convention in the GLTF definition:
  45869. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  45870. */
  45871. var PBRMetallicRoughnessMaterial = /** @class */ (function (_super) {
  45872. __extends(PBRMetallicRoughnessMaterial, _super);
  45873. /**
  45874. * Instantiates a new PBRMetalRoughnessMaterial instance.
  45875. *
  45876. * @param name The material name
  45877. * @param scene The scene the material will be use in.
  45878. */
  45879. function PBRMetallicRoughnessMaterial(name, scene) {
  45880. var _this = _super.call(this, name, scene) || this;
  45881. _this._useRoughnessFromMetallicTextureAlpha = false;
  45882. _this._useRoughnessFromMetallicTextureGreen = true;
  45883. _this._useMetallnessFromMetallicTextureBlue = true;
  45884. _this.metallic = 1.0;
  45885. _this.roughness = 1.0;
  45886. return _this;
  45887. }
  45888. /**
  45889. * Return the currrent class name of the material.
  45890. */
  45891. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  45892. return "PBRMetallicRoughnessMaterial";
  45893. };
  45894. /**
  45895. * Return the active textures of the material.
  45896. */
  45897. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  45898. var activeTextures = _super.prototype.getActiveTextures.call(this);
  45899. if (this.baseTexture) {
  45900. activeTextures.push(this.baseTexture);
  45901. }
  45902. if (this.metallicRoughnessTexture) {
  45903. activeTextures.push(this.metallicRoughnessTexture);
  45904. }
  45905. return activeTextures;
  45906. };
  45907. /**
  45908. * Checks to see if a texture is used in the material.
  45909. * @param texture - Base texture to use.
  45910. * @returns - Boolean specifying if a texture is used in the material.
  45911. */
  45912. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  45913. if (_super.prototype.hasTexture.call(this, texture)) {
  45914. return true;
  45915. }
  45916. if (this.baseTexture === texture) {
  45917. return true;
  45918. }
  45919. if (this.metallicRoughnessTexture === texture) {
  45920. return true;
  45921. }
  45922. return false;
  45923. };
  45924. /**
  45925. * Makes a duplicate of the current material.
  45926. * @param name - name to use for the new material.
  45927. */
  45928. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  45929. var _this = this;
  45930. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  45931. clone.id = name;
  45932. clone.name = name;
  45933. return clone;
  45934. };
  45935. /**
  45936. * Serialize the material to a parsable JSON object.
  45937. */
  45938. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  45939. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  45940. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  45941. return serializationObject;
  45942. };
  45943. /**
  45944. * Parses a JSON object correponding to the serialize function.
  45945. */
  45946. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  45947. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  45948. };
  45949. __decorate([
  45950. BABYLON.serializeAsColor3(),
  45951. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  45952. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  45953. __decorate([
  45954. BABYLON.serializeAsTexture(),
  45955. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  45956. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  45957. __decorate([
  45958. BABYLON.serialize(),
  45959. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45960. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  45961. __decorate([
  45962. BABYLON.serialize(),
  45963. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45964. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  45965. __decorate([
  45966. BABYLON.serializeAsTexture(),
  45967. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  45968. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  45969. return PBRMetallicRoughnessMaterial;
  45970. }(BABYLON.PBRBaseSimpleMaterial));
  45971. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  45972. })(BABYLON || (BABYLON = {}));
  45973. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  45974. var BABYLON;
  45975. (function (BABYLON) {
  45976. /**
  45977. * The PBR material of BJS following the specular glossiness convention.
  45978. *
  45979. * This fits to the PBR convention in the GLTF definition:
  45980. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  45981. */
  45982. var PBRSpecularGlossinessMaterial = /** @class */ (function (_super) {
  45983. __extends(PBRSpecularGlossinessMaterial, _super);
  45984. /**
  45985. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  45986. *
  45987. * @param name The material name
  45988. * @param scene The scene the material will be use in.
  45989. */
  45990. function PBRSpecularGlossinessMaterial(name, scene) {
  45991. var _this = _super.call(this, name, scene) || this;
  45992. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  45993. return _this;
  45994. }
  45995. /**
  45996. * Return the currrent class name of the material.
  45997. */
  45998. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  45999. return "PBRSpecularGlossinessMaterial";
  46000. };
  46001. /**
  46002. * Return the active textures of the material.
  46003. */
  46004. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  46005. var activeTextures = _super.prototype.getActiveTextures.call(this);
  46006. if (this.diffuseTexture) {
  46007. activeTextures.push(this.diffuseTexture);
  46008. }
  46009. if (this.specularGlossinessTexture) {
  46010. activeTextures.push(this.specularGlossinessTexture);
  46011. }
  46012. return activeTextures;
  46013. };
  46014. /**
  46015. * Checks to see if a texture is used in the material.
  46016. * @param texture - Base texture to use.
  46017. * @returns - Boolean specifying if a texture is used in the material.
  46018. */
  46019. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  46020. if (_super.prototype.hasTexture.call(this, texture)) {
  46021. return true;
  46022. }
  46023. if (this.diffuseTexture === texture) {
  46024. return true;
  46025. }
  46026. if (this.specularGlossinessTexture === texture) {
  46027. return true;
  46028. }
  46029. return false;
  46030. };
  46031. /**
  46032. * Makes a duplicate of the current material.
  46033. * @param name - name to use for the new material.
  46034. */
  46035. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  46036. var _this = this;
  46037. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  46038. clone.id = name;
  46039. clone.name = name;
  46040. return clone;
  46041. };
  46042. /**
  46043. * Serialize the material to a parsable JSON object.
  46044. */
  46045. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  46046. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  46047. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  46048. return serializationObject;
  46049. };
  46050. /**
  46051. * Parses a JSON object correponding to the serialize function.
  46052. */
  46053. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  46054. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  46055. };
  46056. __decorate([
  46057. BABYLON.serializeAsColor3("diffuse"),
  46058. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  46059. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  46060. __decorate([
  46061. BABYLON.serializeAsTexture(),
  46062. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  46063. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  46064. __decorate([
  46065. BABYLON.serializeAsColor3("specular"),
  46066. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  46067. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  46068. __decorate([
  46069. BABYLON.serialize(),
  46070. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  46071. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  46072. __decorate([
  46073. BABYLON.serializeAsTexture(),
  46074. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  46075. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  46076. return PBRSpecularGlossinessMaterial;
  46077. }(BABYLON.PBRBaseSimpleMaterial));
  46078. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  46079. })(BABYLON || (BABYLON = {}));
  46080. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  46081. var BABYLON;
  46082. (function (BABYLON) {
  46083. /**
  46084. * This is a list of all the different input types that are available in the application.
  46085. * Fo instance: ArcRotateCameraGamepadInput...
  46086. */
  46087. BABYLON.CameraInputTypes = {};
  46088. /**
  46089. * This represents the input manager used within a camera.
  46090. * It helps dealing with all the different kind of input attached to a camera.
  46091. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  46092. */
  46093. var CameraInputsManager = /** @class */ (function () {
  46094. /**
  46095. * Instantiate a new Camera Input Manager.
  46096. * @param camera Defines the camera the input manager blongs to
  46097. */
  46098. function CameraInputsManager(camera) {
  46099. this.attached = {};
  46100. this.camera = camera;
  46101. this.checkInputs = function () { };
  46102. }
  46103. /**
  46104. * Add an input method to a camera
  46105. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  46106. * @param input camera input method
  46107. */
  46108. CameraInputsManager.prototype.add = function (input) {
  46109. var type = input.getSimpleName();
  46110. if (this.attached[type]) {
  46111. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  46112. return;
  46113. }
  46114. this.attached[type] = input;
  46115. input.camera = this.camera;
  46116. //for checkInputs, we are dynamically creating a function
  46117. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  46118. if (input.checkInputs) {
  46119. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  46120. }
  46121. if (this.attachedElement) {
  46122. input.attachControl(this.attachedElement);
  46123. }
  46124. };
  46125. /**
  46126. * Remove a specific input method from a camera
  46127. * example: camera.inputs.remove(camera.inputs.attached.mouse);
  46128. * @param inputToRemove camera input method
  46129. */
  46130. CameraInputsManager.prototype.remove = function (inputToRemove) {
  46131. for (var cam in this.attached) {
  46132. var input = this.attached[cam];
  46133. if (input === inputToRemove) {
  46134. input.detachControl(this.attachedElement);
  46135. input.camera = null;
  46136. delete this.attached[cam];
  46137. this.rebuildInputCheck();
  46138. }
  46139. }
  46140. };
  46141. /**
  46142. * Remove a specific input type from a camera
  46143. * example: camera.inputs.remove("ArcRotateCameraGamepadInput");
  46144. * @param inputType the type of the input to remove
  46145. */
  46146. CameraInputsManager.prototype.removeByType = function (inputType) {
  46147. for (var cam in this.attached) {
  46148. var input = this.attached[cam];
  46149. if (input.getClassName() === inputType) {
  46150. input.detachControl(this.attachedElement);
  46151. input.camera = null;
  46152. delete this.attached[cam];
  46153. this.rebuildInputCheck();
  46154. }
  46155. }
  46156. };
  46157. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  46158. var current = this.checkInputs;
  46159. return function () {
  46160. current();
  46161. fn();
  46162. };
  46163. };
  46164. /**
  46165. * Attach the input controls to the currently attached dom element to listen the events from.
  46166. * @param input Defines the input to attach
  46167. */
  46168. CameraInputsManager.prototype.attachInput = function (input) {
  46169. if (this.attachedElement) {
  46170. input.attachControl(this.attachedElement, this.noPreventDefault);
  46171. }
  46172. };
  46173. /**
  46174. * Attach the current manager inputs controls to a specific dom element to listen the events from.
  46175. * @param element Defines the dom element to collect the events from
  46176. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  46177. */
  46178. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  46179. if (noPreventDefault === void 0) { noPreventDefault = false; }
  46180. if (this.attachedElement) {
  46181. return;
  46182. }
  46183. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  46184. this.attachedElement = element;
  46185. this.noPreventDefault = noPreventDefault;
  46186. for (var cam in this.attached) {
  46187. this.attached[cam].attachControl(element, noPreventDefault);
  46188. }
  46189. };
  46190. /**
  46191. * Detach the current manager inputs controls from a specific dom element.
  46192. * @param element Defines the dom element to collect the events from
  46193. * @param disconnect Defines whether the input should be removed from the current list of attached inputs
  46194. */
  46195. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  46196. if (disconnect === void 0) { disconnect = false; }
  46197. if (this.attachedElement !== element) {
  46198. return;
  46199. }
  46200. for (var cam in this.attached) {
  46201. this.attached[cam].detachControl(element);
  46202. if (disconnect) {
  46203. this.attached[cam].camera = null;
  46204. }
  46205. }
  46206. this.attachedElement = null;
  46207. };
  46208. /**
  46209. * Rebuild the dynamic inputCheck function from the current list of
  46210. * defined inputs in the manager.
  46211. */
  46212. CameraInputsManager.prototype.rebuildInputCheck = function () {
  46213. this.checkInputs = function () { };
  46214. for (var cam in this.attached) {
  46215. var input = this.attached[cam];
  46216. if (input.checkInputs) {
  46217. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  46218. }
  46219. }
  46220. };
  46221. /**
  46222. * Remove all attached input methods from a camera
  46223. */
  46224. CameraInputsManager.prototype.clear = function () {
  46225. if (this.attachedElement) {
  46226. this.detachElement(this.attachedElement, true);
  46227. }
  46228. this.attached = {};
  46229. this.attachedElement = null;
  46230. this.checkInputs = function () { };
  46231. };
  46232. /**
  46233. * Serialize the current input manager attached to a camera.
  46234. * This ensures than once parsed,
  46235. * the input associated to the camera will be identical to the current ones
  46236. * @param serializedCamera Defines the camera serialization JSON the input serialization should write to
  46237. */
  46238. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  46239. var inputs = {};
  46240. for (var cam in this.attached) {
  46241. var input = this.attached[cam];
  46242. var res = BABYLON.SerializationHelper.Serialize(input);
  46243. inputs[input.getClassName()] = res;
  46244. }
  46245. serializedCamera.inputsmgr = inputs;
  46246. };
  46247. /**
  46248. * Parses an input manager serialized JSON to restore the previous list of inputs
  46249. * and states associated to a camera.
  46250. * @param parsedCamera Defines the JSON to parse
  46251. */
  46252. CameraInputsManager.prototype.parse = function (parsedCamera) {
  46253. var parsedInputs = parsedCamera.inputsmgr;
  46254. if (parsedInputs) {
  46255. this.clear();
  46256. for (var n in parsedInputs) {
  46257. var construct = BABYLON.CameraInputTypes[n];
  46258. if (construct) {
  46259. var parsedinput = parsedInputs[n];
  46260. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  46261. this.add(input);
  46262. }
  46263. }
  46264. }
  46265. else {
  46266. //2016-03-08 this part is for managing backward compatibility
  46267. for (var n in this.attached) {
  46268. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  46269. if (construct) {
  46270. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  46271. this.remove(this.attached[n]);
  46272. this.add(input);
  46273. }
  46274. }
  46275. }
  46276. };
  46277. return CameraInputsManager;
  46278. }());
  46279. BABYLON.CameraInputsManager = CameraInputsManager;
  46280. })(BABYLON || (BABYLON = {}));
  46281. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  46282. var BABYLON;
  46283. (function (BABYLON) {
  46284. /**
  46285. * A target camera takes a mesh or position as a target and continues to look at it while it moves.
  46286. * This is the base of the follow, arc rotate cameras and Free camera
  46287. * @see http://doc.babylonjs.com/features/cameras
  46288. */
  46289. var TargetCamera = /** @class */ (function (_super) {
  46290. __extends(TargetCamera, _super);
  46291. /**
  46292. * Instantiates a target camera that takes a meshor position as a target and continues to look at it while it moves.
  46293. * This is the base of the follow, arc rotate cameras and Free camera
  46294. * @see http://doc.babylonjs.com/features/cameras
  46295. * @param name Defines the name of the camera in the scene
  46296. * @param position Defines the start position of the camera in the scene
  46297. * @param scene Defines the scene the camera belongs to
  46298. * @param setActiveOnSceneIfNoneActive Defines wheter the camera should be marked as active if not other active cameras have been defined
  46299. */
  46300. function TargetCamera(name, position, scene, setActiveOnSceneIfNoneActive) {
  46301. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  46302. var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;
  46303. /**
  46304. * Define the current direction the camera is moving to
  46305. */
  46306. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  46307. /**
  46308. * Define the current rotation the camera is rotating to
  46309. */
  46310. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  46311. /**
  46312. * Define the current rotation of the camera
  46313. */
  46314. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  46315. /**
  46316. * Define the current speed of the camera
  46317. */
  46318. _this.speed = 2.0;
  46319. /**
  46320. * Add cconstraint to the camera to prevent it to move freely in all directions and
  46321. * around all axis.
  46322. */
  46323. _this.noRotationConstraint = false;
  46324. /**
  46325. * Define the current target of the camera as an object or a position.
  46326. */
  46327. _this.lockedTarget = null;
  46328. /** @hidden */
  46329. _this._currentTarget = BABYLON.Vector3.Zero();
  46330. /** @hidden */
  46331. _this._viewMatrix = BABYLON.Matrix.Zero();
  46332. /** @hidden */
  46333. _this._camMatrix = BABYLON.Matrix.Zero();
  46334. /** @hidden */
  46335. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  46336. /** @hidden */
  46337. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  46338. /** @hidden */
  46339. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  46340. /** @hidden */
  46341. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  46342. _this._globalCurrentTarget = BABYLON.Vector3.Zero();
  46343. _this._globalCurrentUpVector = BABYLON.Vector3.Zero();
  46344. _this._defaultUp = BABYLON.Vector3.Up();
  46345. _this._cachedRotationZ = 0;
  46346. return _this;
  46347. }
  46348. /**
  46349. * Gets the position in front of the camera at a given distance.
  46350. * @param distance The distance from the camera we want the position to be
  46351. * @returns the position
  46352. */
  46353. TargetCamera.prototype.getFrontPosition = function (distance) {
  46354. this.getWorldMatrix();
  46355. var direction = this.getTarget().subtract(this.position);
  46356. direction.normalize();
  46357. direction.scaleInPlace(distance);
  46358. return this.globalPosition.add(direction);
  46359. };
  46360. /** @hidden */
  46361. TargetCamera.prototype._getLockedTargetPosition = function () {
  46362. if (!this.lockedTarget) {
  46363. return null;
  46364. }
  46365. if (this.lockedTarget.absolutePosition) {
  46366. this.lockedTarget.computeWorldMatrix();
  46367. }
  46368. return this.lockedTarget.absolutePosition || this.lockedTarget;
  46369. };
  46370. /**
  46371. * Store current camera state of the camera (fov, position, rotation, etc..)
  46372. * @returns the camera
  46373. */
  46374. TargetCamera.prototype.storeState = function () {
  46375. this._storedPosition = this.position.clone();
  46376. this._storedRotation = this.rotation.clone();
  46377. if (this.rotationQuaternion) {
  46378. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  46379. }
  46380. return _super.prototype.storeState.call(this);
  46381. };
  46382. /**
  46383. * Restored camera state. You must call storeState() first
  46384. * @returns whether it was successful or not
  46385. * @hidden
  46386. */
  46387. TargetCamera.prototype._restoreStateValues = function () {
  46388. if (!_super.prototype._restoreStateValues.call(this)) {
  46389. return false;
  46390. }
  46391. this.position = this._storedPosition.clone();
  46392. this.rotation = this._storedRotation.clone();
  46393. if (this.rotationQuaternion) {
  46394. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  46395. }
  46396. this.cameraDirection.copyFromFloats(0, 0, 0);
  46397. this.cameraRotation.copyFromFloats(0, 0);
  46398. return true;
  46399. };
  46400. /** @hidden */
  46401. TargetCamera.prototype._initCache = function () {
  46402. _super.prototype._initCache.call(this);
  46403. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  46404. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  46405. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  46406. };
  46407. /** @hidden */
  46408. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  46409. if (!ignoreParentClass) {
  46410. _super.prototype._updateCache.call(this);
  46411. }
  46412. var lockedTargetPosition = this._getLockedTargetPosition();
  46413. if (!lockedTargetPosition) {
  46414. this._cache.lockedTarget = null;
  46415. }
  46416. else {
  46417. if (!this._cache.lockedTarget) {
  46418. this._cache.lockedTarget = lockedTargetPosition.clone();
  46419. }
  46420. else {
  46421. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  46422. }
  46423. }
  46424. this._cache.rotation.copyFrom(this.rotation);
  46425. if (this.rotationQuaternion)
  46426. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  46427. };
  46428. // Synchronized
  46429. /** @hidden */
  46430. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  46431. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  46432. return false;
  46433. }
  46434. var lockedTargetPosition = this._getLockedTargetPosition();
  46435. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  46436. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  46437. };
  46438. // Methods
  46439. /** @hidden */
  46440. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  46441. var engine = this.getEngine();
  46442. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  46443. };
  46444. // Target
  46445. /** @hidden */
  46446. TargetCamera.prototype.setTarget = function (target) {
  46447. this.upVector.normalize();
  46448. if (this.position.z === target.z) {
  46449. this.position.z += BABYLON.Epsilon;
  46450. }
  46451. BABYLON.Matrix.LookAtLHToRef(this.position, target, this._defaultUp, this._camMatrix);
  46452. this._camMatrix.invert();
  46453. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  46454. var vDir = target.subtract(this.position);
  46455. if (vDir.x >= 0.0) {
  46456. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  46457. }
  46458. else {
  46459. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  46460. }
  46461. this.rotation.z = 0;
  46462. if (isNaN(this.rotation.x)) {
  46463. this.rotation.x = 0;
  46464. }
  46465. if (isNaN(this.rotation.y)) {
  46466. this.rotation.y = 0;
  46467. }
  46468. if (isNaN(this.rotation.z)) {
  46469. this.rotation.z = 0;
  46470. }
  46471. if (this.rotationQuaternion) {
  46472. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  46473. }
  46474. };
  46475. /**
  46476. * Return the current target position of the camera. This value is expressed in local space.
  46477. * @returns the target position
  46478. */
  46479. TargetCamera.prototype.getTarget = function () {
  46480. return this._currentTarget;
  46481. };
  46482. /** @hidden */
  46483. TargetCamera.prototype._decideIfNeedsToMove = function () {
  46484. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  46485. };
  46486. /** @hidden */
  46487. TargetCamera.prototype._updatePosition = function () {
  46488. if (this.parent) {
  46489. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  46490. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  46491. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  46492. return;
  46493. }
  46494. this.position.addInPlace(this.cameraDirection);
  46495. };
  46496. /** @hidden */
  46497. TargetCamera.prototype._checkInputs = function () {
  46498. var needToMove = this._decideIfNeedsToMove();
  46499. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  46500. // Move
  46501. if (needToMove) {
  46502. this._updatePosition();
  46503. }
  46504. // Rotate
  46505. if (needToRotate) {
  46506. this.rotation.x += this.cameraRotation.x;
  46507. this.rotation.y += this.cameraRotation.y;
  46508. //rotate, if quaternion is set and rotation was used
  46509. if (this.rotationQuaternion) {
  46510. var len = this.rotation.lengthSquared();
  46511. if (len) {
  46512. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  46513. }
  46514. }
  46515. if (!this.noRotationConstraint) {
  46516. var limit = (Math.PI / 2) * 0.95;
  46517. if (this.rotation.x > limit)
  46518. this.rotation.x = limit;
  46519. if (this.rotation.x < -limit)
  46520. this.rotation.x = -limit;
  46521. }
  46522. }
  46523. // Inertia
  46524. if (needToMove) {
  46525. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  46526. this.cameraDirection.x = 0;
  46527. }
  46528. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  46529. this.cameraDirection.y = 0;
  46530. }
  46531. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  46532. this.cameraDirection.z = 0;
  46533. }
  46534. this.cameraDirection.scaleInPlace(this.inertia);
  46535. }
  46536. if (needToRotate) {
  46537. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  46538. this.cameraRotation.x = 0;
  46539. }
  46540. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  46541. this.cameraRotation.y = 0;
  46542. }
  46543. this.cameraRotation.scaleInPlace(this.inertia);
  46544. }
  46545. _super.prototype._checkInputs.call(this);
  46546. };
  46547. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  46548. if (this.rotationQuaternion) {
  46549. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  46550. }
  46551. else {
  46552. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  46553. }
  46554. };
  46555. /**
  46556. * Update the up vector to apply the rotation of the camera (So if you changed the camera rotation.z this will let you update the up vector as well)
  46557. * @returns the current camera
  46558. */
  46559. TargetCamera.prototype._rotateUpVectorWithCameraRotationMatrix = function () {
  46560. BABYLON.Vector3.TransformNormalToRef(this._defaultUp, this._cameraRotationMatrix, this.upVector);
  46561. return this;
  46562. };
  46563. /** @hidden */
  46564. TargetCamera.prototype._getViewMatrix = function () {
  46565. if (this.lockedTarget) {
  46566. this.setTarget(this._getLockedTargetPosition());
  46567. }
  46568. // Compute
  46569. this._updateCameraRotationMatrix();
  46570. // Apply the changed rotation to the upVector.
  46571. if (this._cachedRotationZ != this.rotation.z) {
  46572. this._rotateUpVectorWithCameraRotationMatrix();
  46573. this._cachedRotationZ = this.rotation.z;
  46574. }
  46575. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  46576. // Computing target and final matrix
  46577. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  46578. this._computeViewMatrix(this.position, this._currentTarget, this.upVector);
  46579. return this._viewMatrix;
  46580. };
  46581. TargetCamera.prototype._computeViewMatrix = function (position, target, up) {
  46582. if (this.parent) {
  46583. var parentWorldMatrix = this.parent.getWorldMatrix();
  46584. BABYLON.Vector3.TransformCoordinatesToRef(position, parentWorldMatrix, this._globalPosition);
  46585. BABYLON.Vector3.TransformCoordinatesToRef(target, parentWorldMatrix, this._globalCurrentTarget);
  46586. BABYLON.Vector3.TransformNormalToRef(up, parentWorldMatrix, this._globalCurrentUpVector);
  46587. this._markSyncedWithParent();
  46588. }
  46589. else {
  46590. this._globalPosition.copyFrom(position);
  46591. this._globalCurrentTarget.copyFrom(target);
  46592. this._globalCurrentUpVector.copyFrom(up);
  46593. }
  46594. if (this.getScene().useRightHandedSystem) {
  46595. BABYLON.Matrix.LookAtRHToRef(this._globalPosition, this._globalCurrentTarget, this._globalCurrentUpVector, this._viewMatrix);
  46596. }
  46597. else {
  46598. BABYLON.Matrix.LookAtLHToRef(this._globalPosition, this._globalCurrentTarget, this._globalCurrentUpVector, this._viewMatrix);
  46599. }
  46600. };
  46601. /**
  46602. * @hidden
  46603. */
  46604. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  46605. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  46606. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  46607. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  46608. if (!this.rotationQuaternion) {
  46609. this.rotationQuaternion = new BABYLON.Quaternion();
  46610. }
  46611. rigCamera._cameraRigParams = {};
  46612. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  46613. }
  46614. return rigCamera;
  46615. }
  46616. return null;
  46617. };
  46618. /**
  46619. * @hidden
  46620. */
  46621. TargetCamera.prototype._updateRigCameras = function () {
  46622. var camLeft = this._rigCameras[0];
  46623. var camRight = this._rigCameras[1];
  46624. switch (this.cameraRigMode) {
  46625. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  46626. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  46627. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  46628. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  46629. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  46630. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  46631. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  46632. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  46633. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  46634. camLeft.setTarget(this.getTarget());
  46635. camRight.setTarget(this.getTarget());
  46636. break;
  46637. case BABYLON.Camera.RIG_MODE_VR:
  46638. if (camLeft.rotationQuaternion) {
  46639. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  46640. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  46641. }
  46642. else {
  46643. camLeft.rotation.copyFrom(this.rotation);
  46644. camRight.rotation.copyFrom(this.rotation);
  46645. }
  46646. camLeft.position.copyFrom(this.position);
  46647. camRight.position.copyFrom(this.position);
  46648. break;
  46649. }
  46650. _super.prototype._updateRigCameras.call(this);
  46651. };
  46652. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  46653. if (!this._rigCamTransformMatrix) {
  46654. this._rigCamTransformMatrix = new BABYLON.Matrix();
  46655. }
  46656. var target = this.getTarget();
  46657. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  46658. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  46659. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  46660. };
  46661. /**
  46662. * Gets the current object class name.
  46663. * @return the class name
  46664. */
  46665. TargetCamera.prototype.getClassName = function () {
  46666. return "TargetCamera";
  46667. };
  46668. __decorate([
  46669. BABYLON.serializeAsVector3()
  46670. ], TargetCamera.prototype, "rotation", void 0);
  46671. __decorate([
  46672. BABYLON.serialize()
  46673. ], TargetCamera.prototype, "speed", void 0);
  46674. __decorate([
  46675. BABYLON.serializeAsMeshReference("lockedTargetId")
  46676. ], TargetCamera.prototype, "lockedTarget", void 0);
  46677. return TargetCamera;
  46678. }(BABYLON.Camera));
  46679. BABYLON.TargetCamera = TargetCamera;
  46680. })(BABYLON || (BABYLON = {}));
  46681. //# sourceMappingURL=babylon.targetCamera.js.map
  46682. var BABYLON;
  46683. (function (BABYLON) {
  46684. /**
  46685. * Manage the mouse inputs to control the movement of a free camera.
  46686. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  46687. */
  46688. var FreeCameraMouseInput = /** @class */ (function () {
  46689. /**
  46690. * Manage the mouse inputs to control the movement of a free camera.
  46691. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  46692. * @param touchEnabled Defines if touch is enabled or not
  46693. */
  46694. function FreeCameraMouseInput(
  46695. /**
  46696. * Define if touch is enabled in the mouse input
  46697. */
  46698. touchEnabled) {
  46699. if (touchEnabled === void 0) { touchEnabled = true; }
  46700. this.touchEnabled = touchEnabled;
  46701. /**
  46702. * Defines the buttons associated with the input to handle camera move.
  46703. */
  46704. this.buttons = [0, 1, 2];
  46705. /**
  46706. * Defines the pointer angular sensibility along the X and Y axis or how fast is the camera rotating.
  46707. */
  46708. this.angularSensibility = 2000.0;
  46709. this.previousPosition = null;
  46710. }
  46711. /**
  46712. * Attach the input controls to a specific dom element to get the input from.
  46713. * @param element Defines the element the controls should be listened from
  46714. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  46715. */
  46716. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  46717. var _this = this;
  46718. var engine = this.camera.getEngine();
  46719. if (!this._pointerInput) {
  46720. this._pointerInput = function (p, s) {
  46721. var evt = p.event;
  46722. if (engine.isInVRExclusivePointerMode) {
  46723. return;
  46724. }
  46725. if (!_this.touchEnabled && evt.pointerType === "touch") {
  46726. return;
  46727. }
  46728. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  46729. return;
  46730. }
  46731. var srcElement = (evt.srcElement || evt.target);
  46732. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  46733. try {
  46734. srcElement.setPointerCapture(evt.pointerId);
  46735. }
  46736. catch (e) {
  46737. //Nothing to do with the error. Execution will continue.
  46738. }
  46739. _this.previousPosition = {
  46740. x: evt.clientX,
  46741. y: evt.clientY
  46742. };
  46743. if (!noPreventDefault) {
  46744. evt.preventDefault();
  46745. element.focus();
  46746. }
  46747. }
  46748. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  46749. try {
  46750. srcElement.releasePointerCapture(evt.pointerId);
  46751. }
  46752. catch (e) {
  46753. //Nothing to do with the error.
  46754. }
  46755. _this.previousPosition = null;
  46756. if (!noPreventDefault) {
  46757. evt.preventDefault();
  46758. }
  46759. }
  46760. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  46761. if (!_this.previousPosition || engine.isPointerLock) {
  46762. return;
  46763. }
  46764. var offsetX = evt.clientX - _this.previousPosition.x;
  46765. if (_this.camera.getScene().useRightHandedSystem)
  46766. offsetX *= -1;
  46767. if (_this.camera.parent && _this.camera.parent._getWorldMatrixDeterminant() < 0)
  46768. offsetX *= -1;
  46769. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  46770. var offsetY = evt.clientY - _this.previousPosition.y;
  46771. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  46772. _this.previousPosition = {
  46773. x: evt.clientX,
  46774. y: evt.clientY
  46775. };
  46776. if (!noPreventDefault) {
  46777. evt.preventDefault();
  46778. }
  46779. }
  46780. };
  46781. }
  46782. this._onMouseMove = function (evt) {
  46783. if (!engine.isPointerLock) {
  46784. return;
  46785. }
  46786. if (engine.isInVRExclusivePointerMode) {
  46787. return;
  46788. }
  46789. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  46790. if (_this.camera.getScene().useRightHandedSystem)
  46791. offsetX *= -1;
  46792. if (_this.camera.parent && _this.camera.parent._getWorldMatrixDeterminant() < 0)
  46793. offsetX *= -1;
  46794. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  46795. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  46796. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  46797. _this.previousPosition = null;
  46798. if (!noPreventDefault) {
  46799. evt.preventDefault();
  46800. }
  46801. };
  46802. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  46803. element.addEventListener("mousemove", this._onMouseMove, false);
  46804. };
  46805. /**
  46806. * Detach the current controls from the specified dom element.
  46807. * @param element Defines the element to stop listening the inputs from
  46808. */
  46809. FreeCameraMouseInput.prototype.detachControl = function (element) {
  46810. if (this._observer && element) {
  46811. this.camera.getScene().onPointerObservable.remove(this._observer);
  46812. if (this._onMouseMove) {
  46813. element.removeEventListener("mousemove", this._onMouseMove);
  46814. }
  46815. this._observer = null;
  46816. this._onMouseMove = null;
  46817. this.previousPosition = null;
  46818. }
  46819. };
  46820. /**
  46821. * Gets the class name of the current intput.
  46822. * @returns the class name
  46823. */
  46824. FreeCameraMouseInput.prototype.getClassName = function () {
  46825. return "FreeCameraMouseInput";
  46826. };
  46827. /**
  46828. * Get the friendly name associated with the input class.
  46829. * @returns the input friendly name
  46830. */
  46831. FreeCameraMouseInput.prototype.getSimpleName = function () {
  46832. return "mouse";
  46833. };
  46834. __decorate([
  46835. BABYLON.serialize()
  46836. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  46837. __decorate([
  46838. BABYLON.serialize()
  46839. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  46840. return FreeCameraMouseInput;
  46841. }());
  46842. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  46843. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  46844. })(BABYLON || (BABYLON = {}));
  46845. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  46846. var BABYLON;
  46847. (function (BABYLON) {
  46848. /**
  46849. * Manage the keyboard inputs to control the movement of a free camera.
  46850. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  46851. */
  46852. var FreeCameraKeyboardMoveInput = /** @class */ (function () {
  46853. function FreeCameraKeyboardMoveInput() {
  46854. /**
  46855. * Gets or Set the list of keyboard keys used to control the forward move of the camera.
  46856. */
  46857. this.keysUp = [38];
  46858. /**
  46859. * Gets or Set the list of keyboard keys used to control the backward move of the camera.
  46860. */
  46861. this.keysDown = [40];
  46862. /**
  46863. * Gets or Set the list of keyboard keys used to control the left strafe move of the camera.
  46864. */
  46865. this.keysLeft = [37];
  46866. /**
  46867. * Gets or Set the list of keyboard keys used to control the right strafe move of the camera.
  46868. */
  46869. this.keysRight = [39];
  46870. this._keys = new Array();
  46871. }
  46872. /**
  46873. * Attach the input controls to a specific dom element to get the input from.
  46874. * @param element Defines the element the controls should be listened from
  46875. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  46876. */
  46877. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  46878. var _this = this;
  46879. if (this._onCanvasBlurObserver) {
  46880. return;
  46881. }
  46882. this._scene = this.camera.getScene();
  46883. this._engine = this._scene.getEngine();
  46884. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  46885. _this._keys = [];
  46886. });
  46887. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  46888. var evt = info.event;
  46889. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  46890. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  46891. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  46892. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  46893. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  46894. var index = _this._keys.indexOf(evt.keyCode);
  46895. if (index === -1) {
  46896. _this._keys.push(evt.keyCode);
  46897. }
  46898. if (!noPreventDefault) {
  46899. evt.preventDefault();
  46900. }
  46901. }
  46902. }
  46903. else {
  46904. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  46905. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  46906. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  46907. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  46908. var index = _this._keys.indexOf(evt.keyCode);
  46909. if (index >= 0) {
  46910. _this._keys.splice(index, 1);
  46911. }
  46912. if (!noPreventDefault) {
  46913. evt.preventDefault();
  46914. }
  46915. }
  46916. }
  46917. });
  46918. };
  46919. /**
  46920. * Detach the current controls from the specified dom element.
  46921. * @param element Defines the element to stop listening the inputs from
  46922. */
  46923. FreeCameraKeyboardMoveInput.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. /**
  46937. * Update the current camera state depending on the inputs that have been used this frame.
  46938. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
  46939. */
  46940. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  46941. if (this._onKeyboardObserver) {
  46942. var camera = this.camera;
  46943. // Keyboard
  46944. for (var index = 0; index < this._keys.length; index++) {
  46945. var keyCode = this._keys[index];
  46946. var speed = camera._computeLocalCameraSpeed();
  46947. if (this.keysLeft.indexOf(keyCode) !== -1) {
  46948. camera._localDirection.copyFromFloats(-speed, 0, 0);
  46949. }
  46950. else if (this.keysUp.indexOf(keyCode) !== -1) {
  46951. camera._localDirection.copyFromFloats(0, 0, speed);
  46952. }
  46953. else if (this.keysRight.indexOf(keyCode) !== -1) {
  46954. camera._localDirection.copyFromFloats(speed, 0, 0);
  46955. }
  46956. else if (this.keysDown.indexOf(keyCode) !== -1) {
  46957. camera._localDirection.copyFromFloats(0, 0, -speed);
  46958. }
  46959. if (camera.getScene().useRightHandedSystem) {
  46960. camera._localDirection.z *= -1;
  46961. }
  46962. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  46963. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  46964. camera.cameraDirection.addInPlace(camera._transformedDirection);
  46965. }
  46966. }
  46967. };
  46968. /**
  46969. * Gets the class name of the current intput.
  46970. * @returns the class name
  46971. */
  46972. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  46973. return "FreeCameraKeyboardMoveInput";
  46974. };
  46975. /** @hidden */
  46976. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  46977. this._keys = [];
  46978. };
  46979. /**
  46980. * Get the friendly name associated with the input class.
  46981. * @returns the input friendly name
  46982. */
  46983. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  46984. return "keyboard";
  46985. };
  46986. __decorate([
  46987. BABYLON.serialize()
  46988. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  46989. __decorate([
  46990. BABYLON.serialize()
  46991. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  46992. __decorate([
  46993. BABYLON.serialize()
  46994. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  46995. __decorate([
  46996. BABYLON.serialize()
  46997. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  46998. return FreeCameraKeyboardMoveInput;
  46999. }());
  47000. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  47001. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  47002. })(BABYLON || (BABYLON = {}));
  47003. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  47004. var BABYLON;
  47005. (function (BABYLON) {
  47006. /**
  47007. * Default Inputs manager for the FreeCamera.
  47008. * It groups all the default supported inputs for ease of use.
  47009. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  47010. */
  47011. var FreeCameraInputsManager = /** @class */ (function (_super) {
  47012. __extends(FreeCameraInputsManager, _super);
  47013. /**
  47014. * Instantiates a new FreeCameraInputsManager.
  47015. * @param camera Defines the camera the inputs belong to
  47016. */
  47017. function FreeCameraInputsManager(camera) {
  47018. return _super.call(this, camera) || this;
  47019. }
  47020. /**
  47021. * Add keyboard input support to the input manager.
  47022. * @returns the current input manager
  47023. */
  47024. FreeCameraInputsManager.prototype.addKeyboard = function () {
  47025. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  47026. return this;
  47027. };
  47028. /**
  47029. * Add mouse input support to the input manager.
  47030. * @returns the current input manager
  47031. */
  47032. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  47033. if (touchEnabled === void 0) { touchEnabled = true; }
  47034. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  47035. return this;
  47036. };
  47037. /**
  47038. * Add orientation input support to the input manager.
  47039. * @returns the current input manager
  47040. */
  47041. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  47042. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  47043. return this;
  47044. };
  47045. /**
  47046. * Add touch input support to the input manager.
  47047. * @returns the current input manager
  47048. */
  47049. FreeCameraInputsManager.prototype.addTouch = function () {
  47050. this.add(new BABYLON.FreeCameraTouchInput());
  47051. return this;
  47052. };
  47053. /**
  47054. * Add virtual joystick input support to the input manager.
  47055. * @returns the current input manager
  47056. */
  47057. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  47058. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  47059. return this;
  47060. };
  47061. return FreeCameraInputsManager;
  47062. }(BABYLON.CameraInputsManager));
  47063. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  47064. })(BABYLON || (BABYLON = {}));
  47065. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  47066. var BABYLON;
  47067. (function (BABYLON) {
  47068. BABYLON.Node.AddNodeConstructor("FreeCamera", function (name, scene) {
  47069. // Forcing to use the Universal camera
  47070. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  47071. });
  47072. /**
  47073. * This represents a free type of camera. It can be usefull in First Person Shooter game for instance.
  47074. * Please consider using the new UniversalCamera instead as it adds more functionality like the gamepad.
  47075. * @see http://doc.babylonjs.com/features/cameras#universal-camera
  47076. */
  47077. var FreeCamera = /** @class */ (function (_super) {
  47078. __extends(FreeCamera, _super);
  47079. /**
  47080. * Instantiates a Free Camera.
  47081. * This represents a free type of camera. It can be usefull in First Person Shooter game for instance.
  47082. * Please consider using the new UniversalCamera instead as it adds more functionality like touch to this camera.
  47083. * @see http://doc.babylonjs.com/features/cameras#universal-camera
  47084. * @param name Define the name of the camera in the scene
  47085. * @param position Define the start position of the camera in the scene
  47086. * @param scene Define the scene the camera belongs to
  47087. * @param setActiveOnSceneIfNoneActive Defines wheter the camera should be marked as active if not other active cameras have been defined
  47088. */
  47089. function FreeCamera(name, position, scene, setActiveOnSceneIfNoneActive) {
  47090. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  47091. var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;
  47092. /**
  47093. * Define the collision ellipsoid of the camera.
  47094. * This is helpful to simulate a camera body like the player body around the camera
  47095. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#arcrotatecamera
  47096. */
  47097. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  47098. /**
  47099. * Define an offset for the position of the ellipsoid around the camera.
  47100. * This can be helpful to determine the center of the body near the gravity center of the body
  47101. * instead of its head.
  47102. */
  47103. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  47104. /**
  47105. * Enable or disable collisions of the camera with the rest of the scene objects.
  47106. */
  47107. _this.checkCollisions = false;
  47108. /**
  47109. * Enable or disable gravity on the camera.
  47110. */
  47111. _this.applyGravity = false;
  47112. _this._needMoveForGravity = false;
  47113. _this._oldPosition = BABYLON.Vector3.Zero();
  47114. _this._diffPosition = BABYLON.Vector3.Zero();
  47115. _this._newPosition = BABYLON.Vector3.Zero();
  47116. // Collisions
  47117. _this._collisionMask = -1;
  47118. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  47119. if (collidedMesh === void 0) { collidedMesh = null; }
  47120. //TODO move this to the collision coordinator!
  47121. if (_this.getScene().workerCollisions)
  47122. newPosition.multiplyInPlace(_this._collider._radius);
  47123. var updatePosition = function (newPos) {
  47124. _this._newPosition.copyFrom(newPos);
  47125. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  47126. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  47127. _this.position.addInPlace(_this._diffPosition);
  47128. if (_this.onCollide && collidedMesh) {
  47129. _this.onCollide(collidedMesh);
  47130. }
  47131. }
  47132. };
  47133. updatePosition(newPosition);
  47134. };
  47135. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  47136. _this.inputs.addKeyboard().addMouse();
  47137. return _this;
  47138. }
  47139. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  47140. /**
  47141. * Gets the input sensibility for a mouse input. (default is 2000.0)
  47142. * Higher values reduce sensitivity.
  47143. */
  47144. get: function () {
  47145. var mouse = this.inputs.attached["mouse"];
  47146. if (mouse)
  47147. return mouse.angularSensibility;
  47148. return 0;
  47149. },
  47150. /**
  47151. * Sets the input sensibility for a mouse input. (default is 2000.0)
  47152. * Higher values reduce sensitivity.
  47153. */
  47154. set: function (value) {
  47155. var mouse = this.inputs.attached["mouse"];
  47156. if (mouse)
  47157. mouse.angularSensibility = value;
  47158. },
  47159. enumerable: true,
  47160. configurable: true
  47161. });
  47162. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  47163. /**
  47164. * Gets or Set the list of keyboard keys used to control the forward move of the camera.
  47165. */
  47166. get: function () {
  47167. var keyboard = this.inputs.attached["keyboard"];
  47168. if (keyboard)
  47169. return keyboard.keysUp;
  47170. return [];
  47171. },
  47172. set: function (value) {
  47173. var keyboard = this.inputs.attached["keyboard"];
  47174. if (keyboard)
  47175. keyboard.keysUp = value;
  47176. },
  47177. enumerable: true,
  47178. configurable: true
  47179. });
  47180. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  47181. /**
  47182. * Gets or Set the list of keyboard keys used to control the backward move of the camera.
  47183. */
  47184. get: function () {
  47185. var keyboard = this.inputs.attached["keyboard"];
  47186. if (keyboard)
  47187. return keyboard.keysDown;
  47188. return [];
  47189. },
  47190. set: function (value) {
  47191. var keyboard = this.inputs.attached["keyboard"];
  47192. if (keyboard)
  47193. keyboard.keysDown = value;
  47194. },
  47195. enumerable: true,
  47196. configurable: true
  47197. });
  47198. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  47199. /**
  47200. * Gets or Set the list of keyboard keys used to control the left strafe move of the camera.
  47201. */
  47202. get: function () {
  47203. var keyboard = this.inputs.attached["keyboard"];
  47204. if (keyboard)
  47205. return keyboard.keysLeft;
  47206. return [];
  47207. },
  47208. set: function (value) {
  47209. var keyboard = this.inputs.attached["keyboard"];
  47210. if (keyboard)
  47211. keyboard.keysLeft = value;
  47212. },
  47213. enumerable: true,
  47214. configurable: true
  47215. });
  47216. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  47217. /**
  47218. * Gets or Set the list of keyboard keys used to control the right strafe move of the camera.
  47219. */
  47220. get: function () {
  47221. var keyboard = this.inputs.attached["keyboard"];
  47222. if (keyboard)
  47223. return keyboard.keysRight;
  47224. return [];
  47225. },
  47226. set: function (value) {
  47227. var keyboard = this.inputs.attached["keyboard"];
  47228. if (keyboard)
  47229. keyboard.keysRight = value;
  47230. },
  47231. enumerable: true,
  47232. configurable: true
  47233. });
  47234. /**
  47235. * Attached controls to the current camera.
  47236. * @param element Defines the element the controls should be listened from
  47237. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  47238. */
  47239. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  47240. this.inputs.attachElement(element, noPreventDefault);
  47241. };
  47242. /**
  47243. * Detach the current controls from the camera.
  47244. * The camera will stop reacting to inputs.
  47245. * @param element Defines the element to stop listening the inputs from
  47246. */
  47247. FreeCamera.prototype.detachControl = function (element) {
  47248. this.inputs.detachElement(element);
  47249. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  47250. this.cameraRotation = new BABYLON.Vector2(0, 0);
  47251. };
  47252. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  47253. /**
  47254. * Define a collision mask to limit the list of object the camera can collide with
  47255. */
  47256. get: function () {
  47257. return this._collisionMask;
  47258. },
  47259. set: function (mask) {
  47260. this._collisionMask = !isNaN(mask) ? mask : -1;
  47261. },
  47262. enumerable: true,
  47263. configurable: true
  47264. });
  47265. /** @hidden */
  47266. FreeCamera.prototype._collideWithWorld = function (displacement) {
  47267. var globalPosition;
  47268. if (this.parent) {
  47269. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  47270. }
  47271. else {
  47272. globalPosition = this.position;
  47273. }
  47274. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  47275. this._oldPosition.addInPlace(this.ellipsoidOffset);
  47276. if (!this._collider) {
  47277. this._collider = new BABYLON.Collider();
  47278. }
  47279. this._collider._radius = this.ellipsoid;
  47280. this._collider.collisionMask = this._collisionMask;
  47281. //no need for clone, as long as gravity is not on.
  47282. var actualDisplacement = displacement;
  47283. //add gravity to the direction to prevent the dual-collision checking
  47284. if (this.applyGravity) {
  47285. //this prevents mending with cameraDirection, a global variable of the free camera class.
  47286. actualDisplacement = displacement.add(this.getScene().gravity);
  47287. }
  47288. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  47289. };
  47290. /** @hidden */
  47291. FreeCamera.prototype._checkInputs = function () {
  47292. if (!this._localDirection) {
  47293. this._localDirection = BABYLON.Vector3.Zero();
  47294. this._transformedDirection = BABYLON.Vector3.Zero();
  47295. }
  47296. this.inputs.checkInputs();
  47297. _super.prototype._checkInputs.call(this);
  47298. };
  47299. /** @hidden */
  47300. FreeCamera.prototype._decideIfNeedsToMove = function () {
  47301. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  47302. };
  47303. /** @hidden */
  47304. FreeCamera.prototype._updatePosition = function () {
  47305. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  47306. this._collideWithWorld(this.cameraDirection);
  47307. }
  47308. else {
  47309. _super.prototype._updatePosition.call(this);
  47310. }
  47311. };
  47312. /**
  47313. * Destroy the camera and release the current resources hold by it.
  47314. */
  47315. FreeCamera.prototype.dispose = function () {
  47316. this.inputs.clear();
  47317. _super.prototype.dispose.call(this);
  47318. };
  47319. /**
  47320. * Gets the current object class name.
  47321. * @return the class name
  47322. */
  47323. FreeCamera.prototype.getClassName = function () {
  47324. return "FreeCamera";
  47325. };
  47326. __decorate([
  47327. BABYLON.serializeAsVector3()
  47328. ], FreeCamera.prototype, "ellipsoid", void 0);
  47329. __decorate([
  47330. BABYLON.serializeAsVector3()
  47331. ], FreeCamera.prototype, "ellipsoidOffset", void 0);
  47332. __decorate([
  47333. BABYLON.serialize()
  47334. ], FreeCamera.prototype, "checkCollisions", void 0);
  47335. __decorate([
  47336. BABYLON.serialize()
  47337. ], FreeCamera.prototype, "applyGravity", void 0);
  47338. return FreeCamera;
  47339. }(BABYLON.TargetCamera));
  47340. BABYLON.FreeCamera = FreeCamera;
  47341. })(BABYLON || (BABYLON = {}));
  47342. //# sourceMappingURL=babylon.freeCamera.js.map
  47343. var BABYLON;
  47344. (function (BABYLON) {
  47345. /**
  47346. * Manage the keyboard inputs to control the movement of an arc rotate camera.
  47347. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  47348. */
  47349. var ArcRotateCameraKeyboardMoveInput = /** @class */ (function () {
  47350. function ArcRotateCameraKeyboardMoveInput() {
  47351. /**
  47352. * Defines the list of key codes associated with the up action (increase alpha)
  47353. */
  47354. this.keysUp = [38];
  47355. /**
  47356. * Defines the list of key codes associated with the down action (decrease alpha)
  47357. */
  47358. this.keysDown = [40];
  47359. /**
  47360. * Defines the list of key codes associated with the left action (increase beta)
  47361. */
  47362. this.keysLeft = [37];
  47363. /**
  47364. * Defines the list of key codes associated with the right action (decrease beta)
  47365. */
  47366. this.keysRight = [39];
  47367. /**
  47368. * Defines the list of key codes associated with the reset action.
  47369. * Those keys reset the camera to its last stored state (with the method camera.storeState())
  47370. */
  47371. this.keysReset = [220];
  47372. /**
  47373. * Defines the panning sensibility of the inputs.
  47374. * (How fast is the camera paning)
  47375. */
  47376. this.panningSensibility = 50.0;
  47377. /**
  47378. * Defines the zooming sensibility of the inputs.
  47379. * (How fast is the camera zooming)
  47380. */
  47381. this.zoomingSensibility = 25.0;
  47382. /**
  47383. * Defines wether maintaining the alt key down switch the movement mode from
  47384. * orientation to zoom.
  47385. */
  47386. this.useAltToZoom = true;
  47387. this._keys = new Array();
  47388. }
  47389. /**
  47390. * Attach the input controls to a specific dom element to get the input from.
  47391. * @param element Defines the element the controls should be listened from
  47392. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  47393. */
  47394. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  47395. var _this = this;
  47396. if (this._onCanvasBlurObserver) {
  47397. return;
  47398. }
  47399. this._scene = this.camera.getScene();
  47400. this._engine = this._scene.getEngine();
  47401. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  47402. _this._keys = [];
  47403. });
  47404. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  47405. var evt = info.event;
  47406. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  47407. _this._ctrlPressed = evt.ctrlKey;
  47408. _this._altPressed = evt.altKey;
  47409. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  47410. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  47411. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  47412. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  47413. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  47414. var index = _this._keys.indexOf(evt.keyCode);
  47415. if (index === -1) {
  47416. _this._keys.push(evt.keyCode);
  47417. }
  47418. if (evt.preventDefault) {
  47419. if (!noPreventDefault) {
  47420. evt.preventDefault();
  47421. }
  47422. }
  47423. }
  47424. }
  47425. else {
  47426. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  47427. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  47428. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  47429. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  47430. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  47431. var index = _this._keys.indexOf(evt.keyCode);
  47432. if (index >= 0) {
  47433. _this._keys.splice(index, 1);
  47434. }
  47435. if (evt.preventDefault) {
  47436. if (!noPreventDefault) {
  47437. evt.preventDefault();
  47438. }
  47439. }
  47440. }
  47441. }
  47442. });
  47443. };
  47444. /**
  47445. * Detach the current controls from the specified dom element.
  47446. * @param element Defines the element to stop listening the inputs from
  47447. */
  47448. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  47449. if (this._scene) {
  47450. if (this._onKeyboardObserver) {
  47451. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  47452. }
  47453. if (this._onCanvasBlurObserver) {
  47454. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  47455. }
  47456. this._onKeyboardObserver = null;
  47457. this._onCanvasBlurObserver = null;
  47458. }
  47459. this._keys = [];
  47460. };
  47461. /**
  47462. * Update the current camera state depending on the inputs that have been used this frame.
  47463. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
  47464. */
  47465. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  47466. if (this._onKeyboardObserver) {
  47467. var camera = this.camera;
  47468. for (var index = 0; index < this._keys.length; index++) {
  47469. var keyCode = this._keys[index];
  47470. if (this.keysLeft.indexOf(keyCode) !== -1) {
  47471. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  47472. camera.inertialPanningX -= 1 / this.panningSensibility;
  47473. }
  47474. else {
  47475. camera.inertialAlphaOffset -= 0.01;
  47476. }
  47477. }
  47478. else if (this.keysUp.indexOf(keyCode) !== -1) {
  47479. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  47480. camera.inertialPanningY += 1 / this.panningSensibility;
  47481. }
  47482. else if (this._altPressed && this.useAltToZoom) {
  47483. camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
  47484. }
  47485. else {
  47486. camera.inertialBetaOffset -= 0.01;
  47487. }
  47488. }
  47489. else if (this.keysRight.indexOf(keyCode) !== -1) {
  47490. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  47491. camera.inertialPanningX += 1 / this.panningSensibility;
  47492. }
  47493. else {
  47494. camera.inertialAlphaOffset += 0.01;
  47495. }
  47496. }
  47497. else if (this.keysDown.indexOf(keyCode) !== -1) {
  47498. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  47499. camera.inertialPanningY -= 1 / this.panningSensibility;
  47500. }
  47501. else if (this._altPressed && this.useAltToZoom) {
  47502. camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
  47503. }
  47504. else {
  47505. camera.inertialBetaOffset += 0.01;
  47506. }
  47507. }
  47508. else if (this.keysReset.indexOf(keyCode) !== -1) {
  47509. if (camera.useInputToRestoreState) {
  47510. camera.restoreState();
  47511. }
  47512. }
  47513. }
  47514. }
  47515. };
  47516. /**
  47517. * Gets the class name of the current intput.
  47518. * @returns the class name
  47519. */
  47520. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  47521. return "ArcRotateCameraKeyboardMoveInput";
  47522. };
  47523. /**
  47524. * Get the friendly name associated with the input class.
  47525. * @returns the input friendly name
  47526. */
  47527. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  47528. return "keyboard";
  47529. };
  47530. __decorate([
  47531. BABYLON.serialize()
  47532. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  47533. __decorate([
  47534. BABYLON.serialize()
  47535. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  47536. __decorate([
  47537. BABYLON.serialize()
  47538. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  47539. __decorate([
  47540. BABYLON.serialize()
  47541. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  47542. __decorate([
  47543. BABYLON.serialize()
  47544. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  47545. __decorate([
  47546. BABYLON.serialize()
  47547. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  47548. __decorate([
  47549. BABYLON.serialize()
  47550. ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0);
  47551. __decorate([
  47552. BABYLON.serialize()
  47553. ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0);
  47554. return ArcRotateCameraKeyboardMoveInput;
  47555. }());
  47556. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  47557. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  47558. })(BABYLON || (BABYLON = {}));
  47559. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  47560. var BABYLON;
  47561. (function (BABYLON) {
  47562. /**
  47563. * Manage the mouse wheel inputs to control an arc rotate camera.
  47564. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  47565. */
  47566. var ArcRotateCameraMouseWheelInput = /** @class */ (function () {
  47567. function ArcRotateCameraMouseWheelInput() {
  47568. /**
  47569. * Gets or Set the mouse wheel precision or how fast is the camera zooming.
  47570. */
  47571. this.wheelPrecision = 3.0;
  47572. /**
  47573. * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.
  47574. * It defines the percentage of current camera.radius to use as delta when wheel is used.
  47575. */
  47576. this.wheelDeltaPercentage = 0;
  47577. }
  47578. /**
  47579. * Attach the input controls to a specific dom element to get the input from.
  47580. * @param element Defines the element the controls should be listened from
  47581. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  47582. */
  47583. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  47584. var _this = this;
  47585. this._wheel = function (p, s) {
  47586. //sanity check - this should be a PointerWheel event.
  47587. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  47588. return;
  47589. var event = p.event;
  47590. var delta = 0;
  47591. if (event.wheelDelta) {
  47592. if (_this.wheelDeltaPercentage) {
  47593. var wheelDelta = (event.wheelDelta * 0.01 * _this.wheelDeltaPercentage) * _this.camera.radius;
  47594. if (event.wheelDelta > 0) {
  47595. delta = wheelDelta / (1.0 + _this.wheelDeltaPercentage);
  47596. }
  47597. else {
  47598. delta = wheelDelta * (1.0 + _this.wheelDeltaPercentage);
  47599. }
  47600. }
  47601. else {
  47602. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  47603. }
  47604. }
  47605. else if (event.detail) {
  47606. delta = -event.detail / _this.wheelPrecision;
  47607. }
  47608. if (delta)
  47609. _this.camera.inertialRadiusOffset += delta;
  47610. if (event.preventDefault) {
  47611. if (!noPreventDefault) {
  47612. event.preventDefault();
  47613. }
  47614. }
  47615. };
  47616. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  47617. };
  47618. /**
  47619. * Detach the current controls from the specified dom element.
  47620. * @param element Defines the element to stop listening the inputs from
  47621. */
  47622. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  47623. if (this._observer && element) {
  47624. this.camera.getScene().onPointerObservable.remove(this._observer);
  47625. this._observer = null;
  47626. this._wheel = null;
  47627. }
  47628. };
  47629. /**
  47630. * Gets the class name of the current intput.
  47631. * @returns the class name
  47632. */
  47633. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  47634. return "ArcRotateCameraMouseWheelInput";
  47635. };
  47636. /**
  47637. * Get the friendly name associated with the input class.
  47638. * @returns the input friendly name
  47639. */
  47640. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  47641. return "mousewheel";
  47642. };
  47643. __decorate([
  47644. BABYLON.serialize()
  47645. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  47646. __decorate([
  47647. BABYLON.serialize()
  47648. ], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0);
  47649. return ArcRotateCameraMouseWheelInput;
  47650. }());
  47651. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  47652. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  47653. })(BABYLON || (BABYLON = {}));
  47654. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  47655. var BABYLON;
  47656. (function (BABYLON) {
  47657. /**
  47658. * Manage the pointers inputs to control an arc rotate camera.
  47659. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  47660. */
  47661. var ArcRotateCameraPointersInput = /** @class */ (function () {
  47662. function ArcRotateCameraPointersInput() {
  47663. /**
  47664. * Defines the buttons associated with the input to handle camera move.
  47665. */
  47666. this.buttons = [0, 1, 2];
  47667. /**
  47668. * Defines the pointer angular sensibility along the X axis or how fast is the camera rotating.
  47669. */
  47670. this.angularSensibilityX = 1000.0;
  47671. /**
  47672. * Defines the pointer angular sensibility along the Y axis or how fast is the camera rotating.
  47673. */
  47674. this.angularSensibilityY = 1000.0;
  47675. /**
  47676. * Defines the pointer pinch precision or how fast is the camera zooming.
  47677. */
  47678. this.pinchPrecision = 12.0;
  47679. /**
  47680. * pinchDeltaPercentage will be used instead of pinchPrecision if different from 0.
  47681. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  47682. */
  47683. this.pinchDeltaPercentage = 0;
  47684. /**
  47685. * Defines the pointer panning sensibility or how fast is the camera moving.
  47686. */
  47687. this.panningSensibility = 1000.0;
  47688. /**
  47689. * Defines whether panning (2 fingers swipe) is enabled through multitouch.
  47690. */
  47691. this.multiTouchPanning = true;
  47692. /**
  47693. * Defines whether panning is enabled for both pan (2 fingers swipe) and zoom (pinch) through multitouch.
  47694. */
  47695. this.multiTouchPanAndZoom = true;
  47696. /**
  47697. * Revers pinch action direction.
  47698. */
  47699. this.pinchInwards = true;
  47700. this._isPanClick = false;
  47701. }
  47702. /**
  47703. * Attach the input controls to a specific dom element to get the input from.
  47704. * @param element Defines the element the controls should be listened from
  47705. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  47706. */
  47707. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  47708. var _this = this;
  47709. var engine = this.camera.getEngine();
  47710. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  47711. var pointA = null;
  47712. var pointB = null;
  47713. var previousPinchSquaredDistance = 0;
  47714. var initialDistance = 0;
  47715. var twoFingerActivityCount = 0;
  47716. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };
  47717. this._pointerInput = function (p, s) {
  47718. var evt = p.event;
  47719. var isTouch = p.event.pointerType === "touch";
  47720. if (engine.isInVRExclusivePointerMode) {
  47721. return;
  47722. }
  47723. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  47724. return;
  47725. }
  47726. var srcElement = (evt.srcElement || evt.target);
  47727. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  47728. try {
  47729. srcElement.setPointerCapture(evt.pointerId);
  47730. }
  47731. catch (e) {
  47732. //Nothing to do with the error. Execution will continue.
  47733. }
  47734. // Manage panning with pan button click
  47735. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  47736. // manage pointers
  47737. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  47738. if (pointA === null) {
  47739. pointA = cacheSoloPointer;
  47740. }
  47741. else if (pointB === null) {
  47742. pointB = cacheSoloPointer;
  47743. }
  47744. if (!noPreventDefault) {
  47745. evt.preventDefault();
  47746. element.focus();
  47747. }
  47748. }
  47749. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  47750. if (_this.camera.useInputToRestoreState) {
  47751. _this.camera.restoreState();
  47752. }
  47753. }
  47754. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  47755. try {
  47756. srcElement.releasePointerCapture(evt.pointerId);
  47757. }
  47758. catch (e) {
  47759. //Nothing to do with the error.
  47760. }
  47761. cacheSoloPointer = null;
  47762. previousPinchSquaredDistance = 0;
  47763. previousMultiTouchPanPosition.isPaning = false;
  47764. previousMultiTouchPanPosition.isPinching = false;
  47765. twoFingerActivityCount = 0;
  47766. initialDistance = 0;
  47767. if (!isTouch) {
  47768. pointB = null; // Mouse and pen are mono pointer
  47769. }
  47770. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  47771. //but emptying completly pointers collection is required to fix a bug on iPhone :
  47772. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  47773. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  47774. if (engine._badOS) {
  47775. pointA = pointB = null;
  47776. }
  47777. else {
  47778. //only remove the impacted pointer in case of multitouch allowing on most
  47779. //platforms switching from rotate to zoom and pan seamlessly.
  47780. if (pointB && pointA && pointA.pointerId == evt.pointerId) {
  47781. pointA = pointB;
  47782. pointB = null;
  47783. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  47784. }
  47785. else if (pointA && pointB && pointB.pointerId == evt.pointerId) {
  47786. pointB = null;
  47787. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  47788. }
  47789. else {
  47790. pointA = pointB = null;
  47791. }
  47792. }
  47793. if (!noPreventDefault) {
  47794. evt.preventDefault();
  47795. }
  47796. }
  47797. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  47798. if (!noPreventDefault) {
  47799. evt.preventDefault();
  47800. }
  47801. // One button down
  47802. if (pointA && pointB === null && cacheSoloPointer) {
  47803. if (_this.panningSensibility !== 0 &&
  47804. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  47805. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  47806. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  47807. }
  47808. else {
  47809. var offsetX = evt.clientX - cacheSoloPointer.x;
  47810. var offsetY = evt.clientY - cacheSoloPointer.y;
  47811. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  47812. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  47813. }
  47814. cacheSoloPointer.x = evt.clientX;
  47815. cacheSoloPointer.y = evt.clientY;
  47816. }
  47817. // Two buttons down: pinch/pan
  47818. else if (pointA && pointB) {
  47819. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  47820. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  47821. ed.x = evt.clientX;
  47822. ed.y = evt.clientY;
  47823. var direction = _this.pinchInwards ? 1 : -1;
  47824. var distX = pointA.x - pointB.x;
  47825. var distY = pointA.y - pointB.y;
  47826. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  47827. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  47828. if (previousPinchSquaredDistance === 0) {
  47829. initialDistance = pinchDistance;
  47830. previousPinchSquaredDistance = pinchSquaredDistance;
  47831. previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;
  47832. previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;
  47833. return;
  47834. }
  47835. if (_this.multiTouchPanAndZoom) {
  47836. if (_this.pinchDeltaPercentage) {
  47837. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  47838. }
  47839. else {
  47840. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  47841. (_this.pinchPrecision *
  47842. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  47843. direction);
  47844. }
  47845. if (_this.panningSensibility !== 0) {
  47846. var pointersCenterX = (pointA.x + pointB.x) / 2;
  47847. var pointersCenterY = (pointA.y + pointB.y) / 2;
  47848. var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;
  47849. var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;
  47850. previousMultiTouchPanPosition.x = pointersCenterX;
  47851. previousMultiTouchPanPosition.y = pointersCenterY;
  47852. _this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);
  47853. _this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);
  47854. }
  47855. }
  47856. else {
  47857. twoFingerActivityCount++;
  47858. if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {
  47859. if (_this.pinchDeltaPercentage) {
  47860. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  47861. }
  47862. else {
  47863. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  47864. (_this.pinchPrecision *
  47865. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  47866. direction);
  47867. }
  47868. previousMultiTouchPanPosition.isPaning = false;
  47869. previousMultiTouchPanPosition.isPinching = true;
  47870. }
  47871. else {
  47872. if (cacheSoloPointer && cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  47873. if (!previousMultiTouchPanPosition.isPaning) {
  47874. previousMultiTouchPanPosition.isPaning = true;
  47875. previousMultiTouchPanPosition.isPinching = false;
  47876. previousMultiTouchPanPosition.x = ed.x;
  47877. previousMultiTouchPanPosition.y = ed.y;
  47878. return;
  47879. }
  47880. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);
  47881. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);
  47882. }
  47883. }
  47884. if (cacheSoloPointer && cacheSoloPointer.pointerId === evt.pointerId) {
  47885. previousMultiTouchPanPosition.x = ed.x;
  47886. previousMultiTouchPanPosition.y = ed.y;
  47887. }
  47888. }
  47889. previousPinchSquaredDistance = pinchSquaredDistance;
  47890. }
  47891. }
  47892. };
  47893. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes._POINTERDOUBLETAP);
  47894. this._onContextMenu = function (evt) {
  47895. evt.preventDefault();
  47896. };
  47897. if (!this.camera._useCtrlForPanning) {
  47898. element.addEventListener("contextmenu", this._onContextMenu, false);
  47899. }
  47900. this._onLostFocus = function () {
  47901. //this._keys = [];
  47902. pointA = pointB = null;
  47903. previousPinchSquaredDistance = 0;
  47904. previousMultiTouchPanPosition.isPaning = false;
  47905. previousMultiTouchPanPosition.isPinching = false;
  47906. twoFingerActivityCount = 0;
  47907. cacheSoloPointer = null;
  47908. initialDistance = 0;
  47909. };
  47910. this._onMouseMove = function (evt) {
  47911. if (!engine.isPointerLock) {
  47912. return;
  47913. }
  47914. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  47915. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  47916. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  47917. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  47918. if (!noPreventDefault) {
  47919. evt.preventDefault();
  47920. }
  47921. };
  47922. this._onGestureStart = function (e) {
  47923. if (window.MSGesture === undefined) {
  47924. return;
  47925. }
  47926. if (!_this._MSGestureHandler) {
  47927. _this._MSGestureHandler = new MSGesture();
  47928. _this._MSGestureHandler.target = element;
  47929. }
  47930. _this._MSGestureHandler.addPointer(e.pointerId);
  47931. };
  47932. this._onGesture = function (e) {
  47933. _this.camera.radius *= e.scale;
  47934. if (e.preventDefault) {
  47935. if (!noPreventDefault) {
  47936. e.stopPropagation();
  47937. e.preventDefault();
  47938. }
  47939. }
  47940. };
  47941. element.addEventListener("mousemove", this._onMouseMove, false);
  47942. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  47943. element.addEventListener("MSGestureChange", this._onGesture, false);
  47944. BABYLON.Tools.RegisterTopRootEvents([
  47945. { name: "blur", handler: this._onLostFocus }
  47946. ]);
  47947. };
  47948. /**
  47949. * Detach the current controls from the specified dom element.
  47950. * @param element Defines the element to stop listening the inputs from
  47951. */
  47952. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  47953. if (this._onLostFocus) {
  47954. BABYLON.Tools.UnregisterTopRootEvents([
  47955. { name: "blur", handler: this._onLostFocus }
  47956. ]);
  47957. }
  47958. if (element && this._observer) {
  47959. this.camera.getScene().onPointerObservable.remove(this._observer);
  47960. this._observer = null;
  47961. if (this._onContextMenu) {
  47962. element.removeEventListener("contextmenu", this._onContextMenu);
  47963. }
  47964. if (this._onMouseMove) {
  47965. element.removeEventListener("mousemove", this._onMouseMove);
  47966. }
  47967. if (this._onGestureStart) {
  47968. element.removeEventListener("MSPointerDown", this._onGestureStart);
  47969. }
  47970. if (this._onGesture) {
  47971. element.removeEventListener("MSGestureChange", this._onGesture);
  47972. }
  47973. this._isPanClick = false;
  47974. this.pinchInwards = true;
  47975. this._onMouseMove = null;
  47976. this._onGestureStart = null;
  47977. this._onGesture = null;
  47978. this._MSGestureHandler = null;
  47979. this._onLostFocus = null;
  47980. this._onContextMenu = null;
  47981. }
  47982. };
  47983. /**
  47984. * Gets the class name of the current intput.
  47985. * @returns the class name
  47986. */
  47987. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  47988. return "ArcRotateCameraPointersInput";
  47989. };
  47990. /**
  47991. * Get the friendly name associated with the input class.
  47992. * @returns the input friendly name
  47993. */
  47994. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  47995. return "pointers";
  47996. };
  47997. __decorate([
  47998. BABYLON.serialize()
  47999. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  48000. __decorate([
  48001. BABYLON.serialize()
  48002. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  48003. __decorate([
  48004. BABYLON.serialize()
  48005. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  48006. __decorate([
  48007. BABYLON.serialize()
  48008. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  48009. __decorate([
  48010. BABYLON.serialize()
  48011. ], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0);
  48012. __decorate([
  48013. BABYLON.serialize()
  48014. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  48015. __decorate([
  48016. BABYLON.serialize()
  48017. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  48018. __decorate([
  48019. BABYLON.serialize()
  48020. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0);
  48021. return ArcRotateCameraPointersInput;
  48022. }());
  48023. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  48024. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  48025. })(BABYLON || (BABYLON = {}));
  48026. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  48027. var BABYLON;
  48028. (function (BABYLON) {
  48029. /**
  48030. * Default Inputs manager for the ArcRotateCamera.
  48031. * It groups all the default supported inputs for ease of use.
  48032. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  48033. */
  48034. var ArcRotateCameraInputsManager = /** @class */ (function (_super) {
  48035. __extends(ArcRotateCameraInputsManager, _super);
  48036. /**
  48037. * Instantiates a new ArcRotateCameraInputsManager.
  48038. * @param camera Defines the camera the inputs belong to
  48039. */
  48040. function ArcRotateCameraInputsManager(camera) {
  48041. return _super.call(this, camera) || this;
  48042. }
  48043. /**
  48044. * Add mouse wheel input support to the input manager.
  48045. * @returns the current input manager
  48046. */
  48047. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  48048. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  48049. return this;
  48050. };
  48051. /**
  48052. * Add pointers input support to the input manager.
  48053. * @returns the current input manager
  48054. */
  48055. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  48056. this.add(new BABYLON.ArcRotateCameraPointersInput());
  48057. return this;
  48058. };
  48059. /**
  48060. * Add keyboard input support to the input manager.
  48061. * @returns the current input manager
  48062. */
  48063. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  48064. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  48065. return this;
  48066. };
  48067. /**
  48068. * Add orientation input support to the input manager.
  48069. * @returns the current input manager
  48070. */
  48071. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  48072. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  48073. return this;
  48074. };
  48075. return ArcRotateCameraInputsManager;
  48076. }(BABYLON.CameraInputsManager));
  48077. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  48078. })(BABYLON || (BABYLON = {}));
  48079. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  48080. var BABYLON;
  48081. (function (BABYLON) {
  48082. BABYLON.Node.AddNodeConstructor("ArcRotateCamera", function (name, scene) {
  48083. return function () { return new ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  48084. });
  48085. /**
  48086. * This represents an orbital type of camera.
  48087. *
  48088. * This camera always points towards a given target position and can be rotated around that target with the target as the centre of rotation. It can be controlled with cursors and mouse, or with touch events.
  48089. * Think of this camera as one orbiting its target position, or more imaginatively as a spy satellite orbiting the earth. Its position relative to the target (earth) can be set by three parameters, alpha (radians) the longitudinal rotation, beta (radians) the latitudinal rotation and radius the distance from the target position.
  48090. * @see http://doc.babylonjs.com/babylon101/cameras#arc-rotate-camera
  48091. */
  48092. var ArcRotateCamera = /** @class */ (function (_super) {
  48093. __extends(ArcRotateCamera, _super);
  48094. /**
  48095. * Instantiates a new ArcRotateCamera in a given scene
  48096. * @param name Defines the name of the camera
  48097. * @param alpha Defines the camera rotation along the logitudinal axis
  48098. * @param beta Defines the camera rotation along the latitudinal axis
  48099. * @param radius Defines the camera distance from its target
  48100. * @param target Defines the camera target
  48101. * @param scene Defines the scene the camera belongs to
  48102. * @param setActiveOnSceneIfNoneActive Defines wheter the camera should be marked as active if not other active cameras have been defined
  48103. */
  48104. function ArcRotateCamera(name, alpha, beta, radius, target, scene, setActiveOnSceneIfNoneActive) {
  48105. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  48106. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene, setActiveOnSceneIfNoneActive) || this;
  48107. /**
  48108. * Current inertia value on the longitudinal axis.
  48109. * The bigger this number the longer it will take for the camera to stop.
  48110. */
  48111. _this.inertialAlphaOffset = 0;
  48112. /**
  48113. * Current inertia value on the latitudinal axis.
  48114. * The bigger this number the longer it will take for the camera to stop.
  48115. */
  48116. _this.inertialBetaOffset = 0;
  48117. /**
  48118. * Current inertia value on the radius axis.
  48119. * The bigger this number the longer it will take for the camera to stop.
  48120. */
  48121. _this.inertialRadiusOffset = 0;
  48122. /**
  48123. * Minimum allowed angle on the longitudinal axis.
  48124. * This can help limiting how the Camera is able to move in the scene.
  48125. */
  48126. _this.lowerAlphaLimit = null;
  48127. /**
  48128. * Maximum allowed angle on the longitudinal axis.
  48129. * This can help limiting how the Camera is able to move in the scene.
  48130. */
  48131. _this.upperAlphaLimit = null;
  48132. /**
  48133. * Minimum allowed angle on the latitudinal axis.
  48134. * This can help limiting how the Camera is able to move in the scene.
  48135. */
  48136. _this.lowerBetaLimit = 0.01;
  48137. /**
  48138. * Maximum allowed angle on the latitudinal axis.
  48139. * This can help limiting how the Camera is able to move in the scene.
  48140. */
  48141. _this.upperBetaLimit = Math.PI;
  48142. /**
  48143. * Minimum allowed distance of the camera to the target (The camera can not get closer).
  48144. * This can help limiting how the Camera is able to move in the scene.
  48145. */
  48146. _this.lowerRadiusLimit = null;
  48147. /**
  48148. * Maximum allowed distance of the camera to the target (The camera can not get further).
  48149. * This can help limiting how the Camera is able to move in the scene.
  48150. */
  48151. _this.upperRadiusLimit = null;
  48152. /**
  48153. * Defines the current inertia value used during panning of the camera along the X axis.
  48154. */
  48155. _this.inertialPanningX = 0;
  48156. /**
  48157. * Defines the current inertia value used during panning of the camera along the Y axis.
  48158. */
  48159. _this.inertialPanningY = 0;
  48160. /**
  48161. * Defines the distance used to consider the camera in pan mode vs pinch/zoom.
  48162. * Basically if your fingers moves away from more than this distance you will be considered
  48163. * in pinch mode.
  48164. */
  48165. _this.pinchToPanMaxDistance = 20;
  48166. /**
  48167. * Defines the maximum distance the camera can pan.
  48168. * This could help keeping the cammera always in your scene.
  48169. */
  48170. _this.panningDistanceLimit = null;
  48171. /**
  48172. * Defines the target of the camera before paning.
  48173. */
  48174. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  48175. /**
  48176. * Defines the value of the inertia used during panning.
  48177. * 0 would mean stop inertia and one would mean no decelleration at all.
  48178. */
  48179. _this.panningInertia = 0.9;
  48180. //-- end properties for backward compatibility for inputs
  48181. /**
  48182. * Defines how much the radius should be scaled while zomming on a particular mesh (through the zoomOn function)
  48183. */
  48184. _this.zoomOnFactor = 1;
  48185. /**
  48186. * Defines a screen offset for the camera position.
  48187. */
  48188. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  48189. /**
  48190. * Allows the camera to be completely reversed.
  48191. * If false the camera can not arrive upside down.
  48192. */
  48193. _this.allowUpsideDown = true;
  48194. /**
  48195. * Define if double tap/click is used to restore the previously saved state of the camera.
  48196. */
  48197. _this.useInputToRestoreState = true;
  48198. /** @hidden */
  48199. _this._viewMatrix = new BABYLON.Matrix();
  48200. /**
  48201. * Defines the allowed panning axis.
  48202. */
  48203. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  48204. /**
  48205. * Observable triggered when the mesh target has been changed on the camera.
  48206. */
  48207. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  48208. /**
  48209. * Defines whether the camera should check collision with the objects oh the scene.
  48210. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#how-can-i-do-this
  48211. */
  48212. _this.checkCollisions = false;
  48213. /**
  48214. * Defines the collision radius of the camera.
  48215. * This simulates a sphere around the camera.
  48216. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#arcrotatecamera
  48217. */
  48218. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  48219. _this._previousPosition = BABYLON.Vector3.Zero();
  48220. _this._collisionVelocity = BABYLON.Vector3.Zero();
  48221. _this._newPosition = BABYLON.Vector3.Zero();
  48222. _this._computationVector = BABYLON.Vector3.Zero();
  48223. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  48224. if (collidedMesh === void 0) { collidedMesh = null; }
  48225. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  48226. newPosition.multiplyInPlace(_this._collider._radius);
  48227. }
  48228. if (!collidedMesh) {
  48229. _this._previousPosition.copyFrom(_this.position);
  48230. }
  48231. else {
  48232. _this.setPosition(newPosition);
  48233. if (_this.onCollide) {
  48234. _this.onCollide(collidedMesh);
  48235. }
  48236. }
  48237. // Recompute because of constraints
  48238. var cosa = Math.cos(_this.alpha);
  48239. var sina = Math.sin(_this.alpha);
  48240. var cosb = Math.cos(_this.beta);
  48241. var sinb = Math.sin(_this.beta);
  48242. if (sinb === 0) {
  48243. sinb = 0.0001;
  48244. }
  48245. var target = _this._getTargetPosition();
  48246. _this._computationVector.copyFromFloats(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb);
  48247. target.addToRef(_this._computationVector, _this._newPosition);
  48248. _this.position.copyFrom(_this._newPosition);
  48249. var up = _this.upVector;
  48250. if (_this.allowUpsideDown && _this.beta < 0) {
  48251. up = up.clone();
  48252. up = up.negate();
  48253. }
  48254. _this._computeViewMatrix(_this.position, target, up);
  48255. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  48256. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  48257. _this._collisionTriggered = false;
  48258. };
  48259. _this._target = BABYLON.Vector3.Zero();
  48260. if (target) {
  48261. _this.setTarget(target);
  48262. }
  48263. _this.alpha = alpha;
  48264. _this.beta = beta;
  48265. _this.radius = radius;
  48266. _this.getViewMatrix();
  48267. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  48268. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  48269. return _this;
  48270. }
  48271. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  48272. /**
  48273. * Defines the target point of the camera.
  48274. * The camera looks towards it form the radius distance.
  48275. */
  48276. get: function () {
  48277. return this._target;
  48278. },
  48279. set: function (value) {
  48280. this.setTarget(value);
  48281. },
  48282. enumerable: true,
  48283. configurable: true
  48284. });
  48285. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  48286. //-- begin properties for backward compatibility for inputs
  48287. /**
  48288. * Gets or Set the pointer angular sensibility along the X axis or how fast is the camera rotating.
  48289. */
  48290. get: function () {
  48291. var pointers = this.inputs.attached["pointers"];
  48292. if (pointers)
  48293. return pointers.angularSensibilityX;
  48294. return 0;
  48295. },
  48296. set: function (value) {
  48297. var pointers = this.inputs.attached["pointers"];
  48298. if (pointers) {
  48299. pointers.angularSensibilityX = value;
  48300. }
  48301. },
  48302. enumerable: true,
  48303. configurable: true
  48304. });
  48305. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  48306. /**
  48307. * Gets or Set the pointer angular sensibility along the Y axis or how fast is the camera rotating.
  48308. */
  48309. get: function () {
  48310. var pointers = this.inputs.attached["pointers"];
  48311. if (pointers)
  48312. return pointers.angularSensibilityY;
  48313. return 0;
  48314. },
  48315. set: function (value) {
  48316. var pointers = this.inputs.attached["pointers"];
  48317. if (pointers) {
  48318. pointers.angularSensibilityY = value;
  48319. }
  48320. },
  48321. enumerable: true,
  48322. configurable: true
  48323. });
  48324. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  48325. /**
  48326. * Gets or Set the pointer pinch precision or how fast is the camera zooming.
  48327. */
  48328. get: function () {
  48329. var pointers = this.inputs.attached["pointers"];
  48330. if (pointers)
  48331. return pointers.pinchPrecision;
  48332. return 0;
  48333. },
  48334. set: function (value) {
  48335. var pointers = this.inputs.attached["pointers"];
  48336. if (pointers) {
  48337. pointers.pinchPrecision = value;
  48338. }
  48339. },
  48340. enumerable: true,
  48341. configurable: true
  48342. });
  48343. Object.defineProperty(ArcRotateCamera.prototype, "pinchDeltaPercentage", {
  48344. /**
  48345. * Gets or Set the pointer pinch delta percentage or how fast is the camera zooming.
  48346. * It will be used instead of pinchDeltaPrecision if different from 0.
  48347. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  48348. */
  48349. get: function () {
  48350. var pointers = this.inputs.attached["pointers"];
  48351. if (pointers)
  48352. return pointers.pinchDeltaPercentage;
  48353. return 0;
  48354. },
  48355. set: function (value) {
  48356. var pointers = this.inputs.attached["pointers"];
  48357. if (pointers) {
  48358. pointers.pinchDeltaPercentage = value;
  48359. }
  48360. },
  48361. enumerable: true,
  48362. configurable: true
  48363. });
  48364. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  48365. /**
  48366. * Gets or Set the pointer panning sensibility or how fast is the camera moving.
  48367. */
  48368. get: function () {
  48369. var pointers = this.inputs.attached["pointers"];
  48370. if (pointers)
  48371. return pointers.panningSensibility;
  48372. return 0;
  48373. },
  48374. set: function (value) {
  48375. var pointers = this.inputs.attached["pointers"];
  48376. if (pointers) {
  48377. pointers.panningSensibility = value;
  48378. }
  48379. },
  48380. enumerable: true,
  48381. configurable: true
  48382. });
  48383. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  48384. /**
  48385. * Gets or Set the list of keyboard keys used to control beta angle in a positive direction.
  48386. */
  48387. get: function () {
  48388. var keyboard = this.inputs.attached["keyboard"];
  48389. if (keyboard)
  48390. return keyboard.keysUp;
  48391. return [];
  48392. },
  48393. set: function (value) {
  48394. var keyboard = this.inputs.attached["keyboard"];
  48395. if (keyboard)
  48396. keyboard.keysUp = value;
  48397. },
  48398. enumerable: true,
  48399. configurable: true
  48400. });
  48401. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  48402. /**
  48403. * Gets or Set the list of keyboard keys used to control beta angle in a negative direction.
  48404. */
  48405. get: function () {
  48406. var keyboard = this.inputs.attached["keyboard"];
  48407. if (keyboard)
  48408. return keyboard.keysDown;
  48409. return [];
  48410. },
  48411. set: function (value) {
  48412. var keyboard = this.inputs.attached["keyboard"];
  48413. if (keyboard)
  48414. keyboard.keysDown = value;
  48415. },
  48416. enumerable: true,
  48417. configurable: true
  48418. });
  48419. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  48420. /**
  48421. * Gets or Set the list of keyboard keys used to control alpha angle in a negative direction.
  48422. */
  48423. get: function () {
  48424. var keyboard = this.inputs.attached["keyboard"];
  48425. if (keyboard)
  48426. return keyboard.keysLeft;
  48427. return [];
  48428. },
  48429. set: function (value) {
  48430. var keyboard = this.inputs.attached["keyboard"];
  48431. if (keyboard)
  48432. keyboard.keysLeft = value;
  48433. },
  48434. enumerable: true,
  48435. configurable: true
  48436. });
  48437. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  48438. /**
  48439. * Gets or Set the list of keyboard keys used to control alpha angle in a positive direction.
  48440. */
  48441. get: function () {
  48442. var keyboard = this.inputs.attached["keyboard"];
  48443. if (keyboard)
  48444. return keyboard.keysRight;
  48445. return [];
  48446. },
  48447. set: function (value) {
  48448. var keyboard = this.inputs.attached["keyboard"];
  48449. if (keyboard)
  48450. keyboard.keysRight = value;
  48451. },
  48452. enumerable: true,
  48453. configurable: true
  48454. });
  48455. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  48456. /**
  48457. * Gets or Set the mouse wheel precision or how fast is the camera zooming.
  48458. */
  48459. get: function () {
  48460. var mousewheel = this.inputs.attached["mousewheel"];
  48461. if (mousewheel)
  48462. return mousewheel.wheelPrecision;
  48463. return 0;
  48464. },
  48465. set: function (value) {
  48466. var mousewheel = this.inputs.attached["mousewheel"];
  48467. if (mousewheel)
  48468. mousewheel.wheelPrecision = value;
  48469. },
  48470. enumerable: true,
  48471. configurable: true
  48472. });
  48473. Object.defineProperty(ArcRotateCamera.prototype, "wheelDeltaPercentage", {
  48474. /**
  48475. * Gets or Set the mouse wheel delta percentage or how fast is the camera zooming.
  48476. * It will be used instead of pinchDeltaPrecision if different from 0.
  48477. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  48478. */
  48479. get: function () {
  48480. var mousewheel = this.inputs.attached["mousewheel"];
  48481. if (mousewheel)
  48482. return mousewheel.wheelDeltaPercentage;
  48483. return 0;
  48484. },
  48485. set: function (value) {
  48486. var mousewheel = this.inputs.attached["mousewheel"];
  48487. if (mousewheel)
  48488. mousewheel.wheelDeltaPercentage = value;
  48489. },
  48490. enumerable: true,
  48491. configurable: true
  48492. });
  48493. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  48494. /**
  48495. * Gets the bouncing behavior of the camera if it has been enabled.
  48496. * @see http://doc.babylonjs.com/how_to/camera_behaviors#bouncing-behavior
  48497. */
  48498. get: function () {
  48499. return this._bouncingBehavior;
  48500. },
  48501. enumerable: true,
  48502. configurable: true
  48503. });
  48504. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  48505. /**
  48506. * Defines if the bouncing behavior of the camera is enabled on the camera.
  48507. * @see http://doc.babylonjs.com/how_to/camera_behaviors#bouncing-behavior
  48508. */
  48509. get: function () {
  48510. return this._bouncingBehavior != null;
  48511. },
  48512. set: function (value) {
  48513. if (value === this.useBouncingBehavior) {
  48514. return;
  48515. }
  48516. if (value) {
  48517. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  48518. this.addBehavior(this._bouncingBehavior);
  48519. }
  48520. else if (this._bouncingBehavior) {
  48521. this.removeBehavior(this._bouncingBehavior);
  48522. this._bouncingBehavior = null;
  48523. }
  48524. },
  48525. enumerable: true,
  48526. configurable: true
  48527. });
  48528. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  48529. /**
  48530. * Gets the framing behavior of the camera if it has been enabled.
  48531. * @see http://doc.babylonjs.com/how_to/camera_behaviors#framing-behavior
  48532. */
  48533. get: function () {
  48534. return this._framingBehavior;
  48535. },
  48536. enumerable: true,
  48537. configurable: true
  48538. });
  48539. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  48540. /**
  48541. * Defines if the framing behavior of the camera is enabled on the camera.
  48542. * @see http://doc.babylonjs.com/how_to/camera_behaviors#framing-behavior
  48543. */
  48544. get: function () {
  48545. return this._framingBehavior != null;
  48546. },
  48547. set: function (value) {
  48548. if (value === this.useFramingBehavior) {
  48549. return;
  48550. }
  48551. if (value) {
  48552. this._framingBehavior = new BABYLON.FramingBehavior();
  48553. this.addBehavior(this._framingBehavior);
  48554. }
  48555. else if (this._framingBehavior) {
  48556. this.removeBehavior(this._framingBehavior);
  48557. this._framingBehavior = null;
  48558. }
  48559. },
  48560. enumerable: true,
  48561. configurable: true
  48562. });
  48563. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  48564. /**
  48565. * Gets the auto rotation behavior of the camera if it has been enabled.
  48566. * @see http://doc.babylonjs.com/how_to/camera_behaviors#autorotation-behavior
  48567. */
  48568. get: function () {
  48569. return this._autoRotationBehavior;
  48570. },
  48571. enumerable: true,
  48572. configurable: true
  48573. });
  48574. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  48575. /**
  48576. * Defines if the auto rotation behavior of the camera is enabled on the camera.
  48577. * @see http://doc.babylonjs.com/how_to/camera_behaviors#autorotation-behavior
  48578. */
  48579. get: function () {
  48580. return this._autoRotationBehavior != null;
  48581. },
  48582. set: function (value) {
  48583. if (value === this.useAutoRotationBehavior) {
  48584. return;
  48585. }
  48586. if (value) {
  48587. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  48588. this.addBehavior(this._autoRotationBehavior);
  48589. }
  48590. else if (this._autoRotationBehavior) {
  48591. this.removeBehavior(this._autoRotationBehavior);
  48592. this._autoRotationBehavior = null;
  48593. }
  48594. },
  48595. enumerable: true,
  48596. configurable: true
  48597. });
  48598. // Cache
  48599. /** @hidden */
  48600. ArcRotateCamera.prototype._initCache = function () {
  48601. _super.prototype._initCache.call(this);
  48602. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  48603. this._cache.alpha = undefined;
  48604. this._cache.beta = undefined;
  48605. this._cache.radius = undefined;
  48606. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  48607. };
  48608. /** @hidden */
  48609. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  48610. if (!ignoreParentClass) {
  48611. _super.prototype._updateCache.call(this);
  48612. }
  48613. this._cache._target.copyFrom(this._getTargetPosition());
  48614. this._cache.alpha = this.alpha;
  48615. this._cache.beta = this.beta;
  48616. this._cache.radius = this.radius;
  48617. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  48618. };
  48619. ArcRotateCamera.prototype._getTargetPosition = function () {
  48620. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  48621. var pos = this._targetHost.getAbsolutePosition();
  48622. if (this._targetBoundingCenter) {
  48623. pos.addToRef(this._targetBoundingCenter, this._target);
  48624. }
  48625. else {
  48626. this._target.copyFrom(pos);
  48627. }
  48628. }
  48629. var lockedTargetPosition = this._getLockedTargetPosition();
  48630. if (lockedTargetPosition) {
  48631. return lockedTargetPosition;
  48632. }
  48633. return this._target;
  48634. };
  48635. /**
  48636. * Stores the current state of the camera (alpha, beta, radius and target)
  48637. * @returns the camera itself
  48638. */
  48639. ArcRotateCamera.prototype.storeState = function () {
  48640. this._storedAlpha = this.alpha;
  48641. this._storedBeta = this.beta;
  48642. this._storedRadius = this.radius;
  48643. this._storedTarget = this._getTargetPosition().clone();
  48644. return _super.prototype.storeState.call(this);
  48645. };
  48646. /**
  48647. * @hidden
  48648. * Restored camera state. You must call storeState() first
  48649. */
  48650. ArcRotateCamera.prototype._restoreStateValues = function () {
  48651. if (!_super.prototype._restoreStateValues.call(this)) {
  48652. return false;
  48653. }
  48654. this.alpha = this._storedAlpha;
  48655. this.beta = this._storedBeta;
  48656. this.radius = this._storedRadius;
  48657. this.setTarget(this._storedTarget.clone());
  48658. this.inertialAlphaOffset = 0;
  48659. this.inertialBetaOffset = 0;
  48660. this.inertialRadiusOffset = 0;
  48661. this.inertialPanningX = 0;
  48662. this.inertialPanningY = 0;
  48663. return true;
  48664. };
  48665. // Synchronized
  48666. /** @hidden */
  48667. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  48668. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  48669. return false;
  48670. return this._cache._target.equals(this._getTargetPosition())
  48671. && this._cache.alpha === this.alpha
  48672. && this._cache.beta === this.beta
  48673. && this._cache.radius === this.radius
  48674. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  48675. };
  48676. /**
  48677. * Attached controls to the current camera.
  48678. * @param element Defines the element the controls should be listened from
  48679. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  48680. * @param useCtrlForPanning Defines whether ctrl is used for paning within the controls
  48681. * @param panningMouseButton Defines whether panning is allowed through mouse click button
  48682. */
  48683. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  48684. var _this = this;
  48685. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  48686. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  48687. this._useCtrlForPanning = useCtrlForPanning;
  48688. this._panningMouseButton = panningMouseButton;
  48689. this.inputs.attachElement(element, noPreventDefault);
  48690. this._reset = function () {
  48691. _this.inertialAlphaOffset = 0;
  48692. _this.inertialBetaOffset = 0;
  48693. _this.inertialRadiusOffset = 0;
  48694. _this.inertialPanningX = 0;
  48695. _this.inertialPanningY = 0;
  48696. };
  48697. };
  48698. /**
  48699. * Detach the current controls from the camera.
  48700. * The camera will stop reacting to inputs.
  48701. * @param element Defines the element to stop listening the inputs from
  48702. */
  48703. ArcRotateCamera.prototype.detachControl = function (element) {
  48704. this.inputs.detachElement(element);
  48705. if (this._reset) {
  48706. this._reset();
  48707. }
  48708. };
  48709. /** @hidden */
  48710. ArcRotateCamera.prototype._checkInputs = function () {
  48711. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  48712. if (this._collisionTriggered) {
  48713. return;
  48714. }
  48715. this.inputs.checkInputs();
  48716. // Inertia
  48717. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  48718. var inertialAlphaOffset = this.inertialAlphaOffset;
  48719. if (this.beta <= 0)
  48720. inertialAlphaOffset *= -1;
  48721. if (this.getScene().useRightHandedSystem)
  48722. inertialAlphaOffset *= -1;
  48723. if (this.parent && this.parent._getWorldMatrixDeterminant() < 0)
  48724. inertialAlphaOffset *= -1;
  48725. this.alpha += inertialAlphaOffset;
  48726. this.beta += this.inertialBetaOffset;
  48727. this.radius -= this.inertialRadiusOffset;
  48728. this.inertialAlphaOffset *= this.inertia;
  48729. this.inertialBetaOffset *= this.inertia;
  48730. this.inertialRadiusOffset *= this.inertia;
  48731. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  48732. this.inertialAlphaOffset = 0;
  48733. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  48734. this.inertialBetaOffset = 0;
  48735. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  48736. this.inertialRadiusOffset = 0;
  48737. }
  48738. // Panning inertia
  48739. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  48740. if (!this._localDirection) {
  48741. this._localDirection = BABYLON.Vector3.Zero();
  48742. this._transformedDirection = BABYLON.Vector3.Zero();
  48743. }
  48744. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  48745. this._localDirection.multiplyInPlace(this.panningAxis);
  48746. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  48747. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  48748. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  48749. if (!this.panningAxis.y) {
  48750. this._transformedDirection.y = 0;
  48751. }
  48752. if (!this._targetHost) {
  48753. if (this.panningDistanceLimit) {
  48754. this._transformedDirection.addInPlace(this._target);
  48755. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  48756. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  48757. this._target.copyFrom(this._transformedDirection);
  48758. }
  48759. }
  48760. else {
  48761. this._target.addInPlace(this._transformedDirection);
  48762. }
  48763. }
  48764. this.inertialPanningX *= this.panningInertia;
  48765. this.inertialPanningY *= this.panningInertia;
  48766. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  48767. this.inertialPanningX = 0;
  48768. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  48769. this.inertialPanningY = 0;
  48770. }
  48771. // Limits
  48772. this._checkLimits();
  48773. _super.prototype._checkInputs.call(this);
  48774. };
  48775. ArcRotateCamera.prototype._checkLimits = function () {
  48776. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  48777. if (this.allowUpsideDown && this.beta > Math.PI) {
  48778. this.beta = this.beta - (2 * Math.PI);
  48779. }
  48780. }
  48781. else {
  48782. if (this.beta < this.lowerBetaLimit) {
  48783. this.beta = this.lowerBetaLimit;
  48784. }
  48785. }
  48786. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  48787. if (this.allowUpsideDown && this.beta < -Math.PI) {
  48788. this.beta = this.beta + (2 * Math.PI);
  48789. }
  48790. }
  48791. else {
  48792. if (this.beta > this.upperBetaLimit) {
  48793. this.beta = this.upperBetaLimit;
  48794. }
  48795. }
  48796. if (this.lowerAlphaLimit !== null && this.alpha < this.lowerAlphaLimit) {
  48797. this.alpha = this.lowerAlphaLimit;
  48798. }
  48799. if (this.upperAlphaLimit !== null && this.alpha > this.upperAlphaLimit) {
  48800. this.alpha = this.upperAlphaLimit;
  48801. }
  48802. if (this.lowerRadiusLimit !== null && this.radius < this.lowerRadiusLimit) {
  48803. this.radius = this.lowerRadiusLimit;
  48804. }
  48805. if (this.upperRadiusLimit !== null && this.radius > this.upperRadiusLimit) {
  48806. this.radius = this.upperRadiusLimit;
  48807. }
  48808. };
  48809. /**
  48810. * Rebuilds angles (alpha, beta) and radius from the give position and target.
  48811. */
  48812. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  48813. this.position.subtractToRef(this._getTargetPosition(), this._computationVector);
  48814. this.radius = this._computationVector.length();
  48815. if (this.radius === 0) {
  48816. this.radius = 0.0001; // Just to avoid division by zero
  48817. }
  48818. // Alpha
  48819. this.alpha = Math.acos(this._computationVector.x / Math.sqrt(Math.pow(this._computationVector.x, 2) + Math.pow(this._computationVector.z, 2)));
  48820. if (this._computationVector.z < 0) {
  48821. this.alpha = 2 * Math.PI - this.alpha;
  48822. }
  48823. // Beta
  48824. this.beta = Math.acos(this._computationVector.y / this.radius);
  48825. this._checkLimits();
  48826. };
  48827. /**
  48828. * Use a position to define the current camera related information like aplha, beta and radius
  48829. * @param position Defines the position to set the camera at
  48830. */
  48831. ArcRotateCamera.prototype.setPosition = function (position) {
  48832. if (this.position.equals(position)) {
  48833. return;
  48834. }
  48835. this.position.copyFrom(position);
  48836. this.rebuildAnglesAndRadius();
  48837. };
  48838. /**
  48839. * Defines the target the camera should look at.
  48840. * This will automatically adapt alpha beta and radius to fit within the new target.
  48841. * @param target Defines the new target as a Vector or a mesh
  48842. * @param toBoundingCenter In case of a mesh target, defines wether to target the mesh position or its bounding information center
  48843. * @param allowSamePosition If false, prevents reapplying the new computed position if it is identical to the current one (optim)
  48844. */
  48845. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  48846. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  48847. if (allowSamePosition === void 0) { allowSamePosition = false; }
  48848. if (target.getBoundingInfo) {
  48849. if (toBoundingCenter) {
  48850. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  48851. }
  48852. else {
  48853. this._targetBoundingCenter = null;
  48854. }
  48855. this._targetHost = target;
  48856. this._target = this._getTargetPosition();
  48857. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  48858. }
  48859. else {
  48860. var newTarget = target;
  48861. var currentTarget = this._getTargetPosition();
  48862. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  48863. return;
  48864. }
  48865. this._targetHost = null;
  48866. this._target = newTarget;
  48867. this._targetBoundingCenter = null;
  48868. this.onMeshTargetChangedObservable.notifyObservers(null);
  48869. }
  48870. this.rebuildAnglesAndRadius();
  48871. };
  48872. /** @hidden */
  48873. ArcRotateCamera.prototype._getViewMatrix = function () {
  48874. // Compute
  48875. var cosa = Math.cos(this.alpha);
  48876. var sina = Math.sin(this.alpha);
  48877. var cosb = Math.cos(this.beta);
  48878. var sinb = Math.sin(this.beta);
  48879. if (sinb === 0) {
  48880. sinb = 0.0001;
  48881. }
  48882. var target = this._getTargetPosition();
  48883. this._computationVector.copyFromFloats(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb);
  48884. target.addToRef(this._computationVector, this._newPosition);
  48885. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  48886. if (!this._collider) {
  48887. this._collider = new BABYLON.Collider();
  48888. }
  48889. this._collider._radius = this.collisionRadius;
  48890. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  48891. this._collisionTriggered = true;
  48892. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  48893. }
  48894. else {
  48895. this.position.copyFrom(this._newPosition);
  48896. var up = this.upVector;
  48897. if (this.allowUpsideDown && sinb < 0) {
  48898. up = up.clone();
  48899. up = up.negate();
  48900. }
  48901. this._computeViewMatrix(this.position, target, up);
  48902. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  48903. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  48904. }
  48905. this._currentTarget = target;
  48906. return this._viewMatrix;
  48907. };
  48908. /**
  48909. * Zooms on a mesh to be at the min distance where we could see it fully in the current viewport.
  48910. * @param meshes Defines the mesh to zoom on
  48911. * @param doNotUpdateMaxZ Defines whether or not maxZ should be updated whilst zooming on the mesh (this can happen if the mesh is big and the maxradius pretty small for instance)
  48912. */
  48913. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  48914. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  48915. meshes = meshes || this.getScene().meshes;
  48916. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  48917. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  48918. this.radius = distance * this.zoomOnFactor;
  48919. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  48920. };
  48921. /**
  48922. * Focus on a mesh or a bounding box. This adapts the target and maxRadius if necessary but does not update the current radius.
  48923. * The target will be changed but the radius
  48924. * @param meshesOrMinMaxVectorAndDistance Defines the mesh or bounding info to focus on
  48925. * @param doNotUpdateMaxZ Defines whether or not maxZ should be updated whilst zooming on the mesh (this can happen if the mesh is big and the maxradius pretty small for instance)
  48926. */
  48927. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  48928. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  48929. var meshesOrMinMaxVector;
  48930. var distance;
  48931. if (meshesOrMinMaxVectorAndDistance.min === undefined) { // meshes
  48932. var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  48933. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshes);
  48934. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  48935. }
  48936. else { //minMaxVector and distance
  48937. var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
  48938. meshesOrMinMaxVector = minMaxVectorAndDistance;
  48939. distance = minMaxVectorAndDistance.distance;
  48940. }
  48941. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  48942. if (!doNotUpdateMaxZ) {
  48943. this.maxZ = distance * 2;
  48944. }
  48945. };
  48946. /**
  48947. * @override
  48948. * Override Camera.createRigCamera
  48949. */
  48950. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  48951. var alphaShift = 0;
  48952. switch (this.cameraRigMode) {
  48953. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  48954. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  48955. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  48956. case BABYLON.Camera.RIG_MODE_VR:
  48957. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  48958. break;
  48959. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  48960. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  48961. break;
  48962. }
  48963. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  48964. rigCam._cameraRigParams = {};
  48965. return rigCam;
  48966. };
  48967. /**
  48968. * @hidden
  48969. * @override
  48970. * Override Camera._updateRigCameras
  48971. */
  48972. ArcRotateCamera.prototype._updateRigCameras = function () {
  48973. var camLeft = this._rigCameras[0];
  48974. var camRight = this._rigCameras[1];
  48975. camLeft.beta = camRight.beta = this.beta;
  48976. camLeft.radius = camRight.radius = this.radius;
  48977. switch (this.cameraRigMode) {
  48978. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  48979. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  48980. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  48981. case BABYLON.Camera.RIG_MODE_VR:
  48982. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  48983. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  48984. break;
  48985. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  48986. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  48987. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  48988. break;
  48989. }
  48990. _super.prototype._updateRigCameras.call(this);
  48991. };
  48992. /**
  48993. * Destroy the camera and release the current resources hold by it.
  48994. */
  48995. ArcRotateCamera.prototype.dispose = function () {
  48996. this.inputs.clear();
  48997. _super.prototype.dispose.call(this);
  48998. };
  48999. /**
  49000. * Gets the current object class name.
  49001. * @return the class name
  49002. */
  49003. ArcRotateCamera.prototype.getClassName = function () {
  49004. return "ArcRotateCamera";
  49005. };
  49006. __decorate([
  49007. BABYLON.serialize()
  49008. ], ArcRotateCamera.prototype, "alpha", void 0);
  49009. __decorate([
  49010. BABYLON.serialize()
  49011. ], ArcRotateCamera.prototype, "beta", void 0);
  49012. __decorate([
  49013. BABYLON.serialize()
  49014. ], ArcRotateCamera.prototype, "radius", void 0);
  49015. __decorate([
  49016. BABYLON.serializeAsVector3("target")
  49017. ], ArcRotateCamera.prototype, "_target", void 0);
  49018. __decorate([
  49019. BABYLON.serialize()
  49020. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  49021. __decorate([
  49022. BABYLON.serialize()
  49023. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  49024. __decorate([
  49025. BABYLON.serialize()
  49026. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  49027. __decorate([
  49028. BABYLON.serialize()
  49029. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  49030. __decorate([
  49031. BABYLON.serialize()
  49032. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  49033. __decorate([
  49034. BABYLON.serialize()
  49035. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  49036. __decorate([
  49037. BABYLON.serialize()
  49038. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  49039. __decorate([
  49040. BABYLON.serialize()
  49041. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  49042. __decorate([
  49043. BABYLON.serialize()
  49044. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  49045. __decorate([
  49046. BABYLON.serialize()
  49047. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  49048. __decorate([
  49049. BABYLON.serialize()
  49050. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  49051. __decorate([
  49052. BABYLON.serialize()
  49053. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  49054. __decorate([
  49055. BABYLON.serialize()
  49056. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  49057. __decorate([
  49058. BABYLON.serializeAsVector3()
  49059. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  49060. __decorate([
  49061. BABYLON.serialize()
  49062. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  49063. __decorate([
  49064. BABYLON.serialize()
  49065. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  49066. __decorate([
  49067. BABYLON.serialize()
  49068. ], ArcRotateCamera.prototype, "targetScreenOffset", void 0);
  49069. __decorate([
  49070. BABYLON.serialize()
  49071. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  49072. __decorate([
  49073. BABYLON.serialize()
  49074. ], ArcRotateCamera.prototype, "useInputToRestoreState", void 0);
  49075. return ArcRotateCamera;
  49076. }(BABYLON.TargetCamera));
  49077. BABYLON.ArcRotateCamera = ArcRotateCamera;
  49078. })(BABYLON || (BABYLON = {}));
  49079. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  49080. var BABYLON;
  49081. (function (BABYLON) {
  49082. BABYLON.Node.AddNodeConstructor("Light_Type_3", function (name, scene) {
  49083. return function () { return new HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  49084. });
  49085. /**
  49086. * The HemisphericLight simulates the ambient environment light,
  49087. * so the passed direction is the light reflection direction, not the incoming direction.
  49088. */
  49089. var HemisphericLight = /** @class */ (function (_super) {
  49090. __extends(HemisphericLight, _super);
  49091. /**
  49092. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  49093. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  49094. * The HemisphericLight can't cast shadows.
  49095. * Documentation : http://doc.babylonjs.com/tutorials/lights
  49096. * @param name The friendly name of the light
  49097. * @param direction The direction of the light reflection
  49098. * @param scene The scene the light belongs to
  49099. */
  49100. function HemisphericLight(name, direction, scene) {
  49101. var _this = _super.call(this, name, scene) || this;
  49102. /**
  49103. * The groundColor is the light in the opposite direction to the one specified during creation.
  49104. * 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.
  49105. */
  49106. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  49107. _this.direction = direction || BABYLON.Vector3.Up();
  49108. return _this;
  49109. }
  49110. HemisphericLight.prototype._buildUniformLayout = function () {
  49111. this._uniformBuffer.addUniform("vLightData", 4);
  49112. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  49113. this._uniformBuffer.addUniform("vLightSpecular", 3);
  49114. this._uniformBuffer.addUniform("vLightGround", 3);
  49115. this._uniformBuffer.addUniform("shadowsInfo", 3);
  49116. this._uniformBuffer.addUniform("depthValues", 2);
  49117. this._uniformBuffer.create();
  49118. };
  49119. /**
  49120. * Returns the string "HemisphericLight".
  49121. * @return The class name
  49122. */
  49123. HemisphericLight.prototype.getClassName = function () {
  49124. return "HemisphericLight";
  49125. };
  49126. /**
  49127. * Sets the HemisphericLight direction towards the passed target (Vector3).
  49128. * Returns the updated direction.
  49129. * @param target The target the direction should point to
  49130. * @return The computed direction
  49131. */
  49132. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  49133. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  49134. return this.direction;
  49135. };
  49136. /**
  49137. * Returns the shadow generator associated to the light.
  49138. * @returns Always null for hemispheric lights because it does not support shadows.
  49139. */
  49140. HemisphericLight.prototype.getShadowGenerator = function () {
  49141. return null;
  49142. };
  49143. /**
  49144. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  49145. * @param effect The effect to update
  49146. * @param lightIndex The index of the light in the effect to update
  49147. * @returns The hemispheric light
  49148. */
  49149. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  49150. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  49151. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  49152. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  49153. return this;
  49154. };
  49155. /**
  49156. * Computes the world matrix of the node
  49157. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  49158. * @param useWasUpdatedFlag defines a reserved property
  49159. * @returns the world matrix
  49160. */
  49161. HemisphericLight.prototype.computeWorldMatrix = function (force, useWasUpdatedFlag) {
  49162. if (!this._worldMatrix) {
  49163. this._worldMatrix = BABYLON.Matrix.Identity();
  49164. }
  49165. return this._worldMatrix;
  49166. };
  49167. /**
  49168. * Returns the integer 3.
  49169. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  49170. */
  49171. HemisphericLight.prototype.getTypeID = function () {
  49172. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  49173. };
  49174. /**
  49175. * Prepares the list of defines specific to the light type.
  49176. * @param defines the list of defines
  49177. * @param lightIndex defines the index of the light for the effect
  49178. */
  49179. HemisphericLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
  49180. defines["HEMILIGHT" + lightIndex] = true;
  49181. };
  49182. __decorate([
  49183. BABYLON.serializeAsColor3()
  49184. ], HemisphericLight.prototype, "groundColor", void 0);
  49185. __decorate([
  49186. BABYLON.serializeAsVector3()
  49187. ], HemisphericLight.prototype, "direction", void 0);
  49188. return HemisphericLight;
  49189. }(BABYLON.Light));
  49190. BABYLON.HemisphericLight = HemisphericLight;
  49191. })(BABYLON || (BABYLON = {}));
  49192. //# sourceMappingURL=babylon.hemisphericLight.js.map
  49193. var BABYLON;
  49194. (function (BABYLON) {
  49195. /**
  49196. * Base implementation IShadowLight
  49197. * It groups all the common behaviour in order to reduce dupplication and better follow the DRY pattern.
  49198. */
  49199. var ShadowLight = /** @class */ (function (_super) {
  49200. __extends(ShadowLight, _super);
  49201. function ShadowLight() {
  49202. var _this = _super !== null && _super.apply(this, arguments) || this;
  49203. _this._needProjectionMatrixCompute = true;
  49204. return _this;
  49205. }
  49206. ShadowLight.prototype._setPosition = function (value) {
  49207. this._position = value;
  49208. };
  49209. Object.defineProperty(ShadowLight.prototype, "position", {
  49210. /**
  49211. * Sets the position the shadow will be casted from. Also use as the light position for both
  49212. * point and spot lights.
  49213. */
  49214. get: function () {
  49215. return this._position;
  49216. },
  49217. /**
  49218. * Sets the position the shadow will be casted from. Also use as the light position for both
  49219. * point and spot lights.
  49220. */
  49221. set: function (value) {
  49222. this._setPosition(value);
  49223. },
  49224. enumerable: true,
  49225. configurable: true
  49226. });
  49227. ShadowLight.prototype._setDirection = function (value) {
  49228. this._direction = value;
  49229. };
  49230. Object.defineProperty(ShadowLight.prototype, "direction", {
  49231. /**
  49232. * In 2d mode (needCube being false), gets the direction used to cast the shadow.
  49233. * Also use as the light direction on spot and directional lights.
  49234. */
  49235. get: function () {
  49236. return this._direction;
  49237. },
  49238. /**
  49239. * In 2d mode (needCube being false), sets the direction used to cast the shadow.
  49240. * Also use as the light direction on spot and directional lights.
  49241. */
  49242. set: function (value) {
  49243. this._setDirection(value);
  49244. },
  49245. enumerable: true,
  49246. configurable: true
  49247. });
  49248. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  49249. /**
  49250. * Gets the shadow projection clipping minimum z value.
  49251. */
  49252. get: function () {
  49253. return this._shadowMinZ;
  49254. },
  49255. /**
  49256. * Sets the shadow projection clipping minimum z value.
  49257. */
  49258. set: function (value) {
  49259. this._shadowMinZ = value;
  49260. this.forceProjectionMatrixCompute();
  49261. },
  49262. enumerable: true,
  49263. configurable: true
  49264. });
  49265. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  49266. /**
  49267. * Sets the shadow projection clipping maximum z value.
  49268. */
  49269. get: function () {
  49270. return this._shadowMaxZ;
  49271. },
  49272. /**
  49273. * Gets the shadow projection clipping maximum z value.
  49274. */
  49275. set: function (value) {
  49276. this._shadowMaxZ = value;
  49277. this.forceProjectionMatrixCompute();
  49278. },
  49279. enumerable: true,
  49280. configurable: true
  49281. });
  49282. /**
  49283. * Computes the transformed information (transformedPosition and transformedDirection in World space) of the current light
  49284. * @returns true if the information has been computed, false if it does not need to (no parenting)
  49285. */
  49286. ShadowLight.prototype.computeTransformedInformation = function () {
  49287. if (this.parent && this.parent.getWorldMatrix) {
  49288. if (!this.transformedPosition) {
  49289. this.transformedPosition = BABYLON.Vector3.Zero();
  49290. }
  49291. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  49292. // In case the direction is present.
  49293. if (this.direction) {
  49294. if (!this.transformedDirection) {
  49295. this.transformedDirection = BABYLON.Vector3.Zero();
  49296. }
  49297. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  49298. }
  49299. return true;
  49300. }
  49301. return false;
  49302. };
  49303. /**
  49304. * Return the depth scale used for the shadow map.
  49305. * @returns the depth scale.
  49306. */
  49307. ShadowLight.prototype.getDepthScale = function () {
  49308. return 50.0;
  49309. };
  49310. /**
  49311. * Get the direction to use to render the shadow map. In case of cube texture, the face index can be passed.
  49312. * @param faceIndex The index of the face we are computed the direction to generate shadow
  49313. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  49314. */
  49315. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  49316. return this.transformedDirection ? this.transformedDirection : this.direction;
  49317. };
  49318. /**
  49319. * Returns the ShadowLight absolute position in the World.
  49320. * @returns the position vector in world space
  49321. */
  49322. ShadowLight.prototype.getAbsolutePosition = function () {
  49323. return this.transformedPosition ? this.transformedPosition : this.position;
  49324. };
  49325. /**
  49326. * Sets the ShadowLight direction toward the passed target.
  49327. * @param target The point tot target in local space
  49328. * @returns the updated ShadowLight direction
  49329. */
  49330. ShadowLight.prototype.setDirectionToTarget = function (target) {
  49331. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  49332. return this.direction;
  49333. };
  49334. /**
  49335. * Returns the light rotation in euler definition.
  49336. * @returns the x y z rotation in local space.
  49337. */
  49338. ShadowLight.prototype.getRotation = function () {
  49339. this.direction.normalize();
  49340. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  49341. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  49342. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  49343. };
  49344. /**
  49345. * Returns whether or not the shadow generation require a cube texture or a 2d texture.
  49346. * @returns true if a cube texture needs to be use
  49347. */
  49348. ShadowLight.prototype.needCube = function () {
  49349. return false;
  49350. };
  49351. /**
  49352. * Detects if the projection matrix requires to be recomputed this frame.
  49353. * @returns true if it requires to be recomputed otherwise, false.
  49354. */
  49355. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  49356. return this._needProjectionMatrixCompute;
  49357. };
  49358. /**
  49359. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  49360. */
  49361. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  49362. this._needProjectionMatrixCompute = true;
  49363. };
  49364. /** @hidden */
  49365. ShadowLight.prototype._initCache = function () {
  49366. _super.prototype._initCache.call(this);
  49367. this._cache.position = BABYLON.Vector3.Zero();
  49368. };
  49369. /** @hidden */
  49370. ShadowLight.prototype._isSynchronized = function () {
  49371. if (!this._cache.position.equals(this.position))
  49372. return false;
  49373. return true;
  49374. };
  49375. /**
  49376. * Computes the world matrix of the node
  49377. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  49378. * @returns the world matrix
  49379. */
  49380. ShadowLight.prototype.computeWorldMatrix = function (force) {
  49381. if (!force && this.isSynchronized()) {
  49382. this._currentRenderId = this.getScene().getRenderId();
  49383. return this._worldMatrix;
  49384. }
  49385. this._updateCache();
  49386. this._cache.position.copyFrom(this.position);
  49387. if (!this._worldMatrix) {
  49388. this._worldMatrix = BABYLON.Matrix.Identity();
  49389. }
  49390. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  49391. if (this.parent && this.parent.getWorldMatrix) {
  49392. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  49393. this._markSyncedWithParent();
  49394. }
  49395. // Cache the determinant
  49396. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  49397. return this._worldMatrix;
  49398. };
  49399. /**
  49400. * Gets the minZ used for shadow according to both the scene and the light.
  49401. * @param activeCamera The camera we are returning the min for
  49402. * @returns the depth min z
  49403. */
  49404. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  49405. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  49406. };
  49407. /**
  49408. * Gets the maxZ used for shadow according to both the scene and the light.
  49409. * @param activeCamera The camera we are returning the max for
  49410. * @returns the depth max z
  49411. */
  49412. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  49413. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  49414. };
  49415. /**
  49416. * Sets the shadow projection matrix in parameter to the generated projection matrix.
  49417. * @param matrix The materix to updated with the projection information
  49418. * @param viewMatrix The transform matrix of the light
  49419. * @param renderList The list of mesh to render in the map
  49420. * @returns The current light
  49421. */
  49422. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49423. if (this.customProjectionMatrixBuilder) {
  49424. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  49425. }
  49426. else {
  49427. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  49428. }
  49429. return this;
  49430. };
  49431. __decorate([
  49432. BABYLON.serializeAsVector3()
  49433. ], ShadowLight.prototype, "position", null);
  49434. __decorate([
  49435. BABYLON.serializeAsVector3()
  49436. ], ShadowLight.prototype, "direction", null);
  49437. __decorate([
  49438. BABYLON.serialize()
  49439. ], ShadowLight.prototype, "shadowMinZ", null);
  49440. __decorate([
  49441. BABYLON.serialize()
  49442. ], ShadowLight.prototype, "shadowMaxZ", null);
  49443. return ShadowLight;
  49444. }(BABYLON.Light));
  49445. BABYLON.ShadowLight = ShadowLight;
  49446. })(BABYLON || (BABYLON = {}));
  49447. //# sourceMappingURL=babylon.shadowLight.js.map
  49448. var BABYLON;
  49449. (function (BABYLON) {
  49450. BABYLON.Node.AddNodeConstructor("Light_Type_0", function (name, scene) {
  49451. return function () { return new PointLight(name, BABYLON.Vector3.Zero(), scene); };
  49452. });
  49453. /**
  49454. * A point light is a light defined by an unique point in world space.
  49455. * The light is emitted in every direction from this point.
  49456. * A good example of a point light is a standard light bulb.
  49457. * Documentation: https://doc.babylonjs.com/babylon101/lights
  49458. */
  49459. var PointLight = /** @class */ (function (_super) {
  49460. __extends(PointLight, _super);
  49461. /**
  49462. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  49463. * A PointLight emits the light in every direction.
  49464. * It can cast shadows.
  49465. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  49466. * ```javascript
  49467. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  49468. * ```
  49469. * Documentation : http://doc.babylonjs.com/tutorials/lights
  49470. * @param name The light friendly name
  49471. * @param position The position of the point light in the scene
  49472. * @param scene The scene the lights belongs to
  49473. */
  49474. function PointLight(name, position, scene) {
  49475. var _this = _super.call(this, name, scene) || this;
  49476. _this._shadowAngle = Math.PI / 2;
  49477. _this.position = position;
  49478. return _this;
  49479. }
  49480. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  49481. /**
  49482. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  49483. * This specifies what angle the shadow will use to be created.
  49484. *
  49485. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  49486. */
  49487. get: function () {
  49488. return this._shadowAngle;
  49489. },
  49490. /**
  49491. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  49492. * This specifies what angle the shadow will use to be created.
  49493. *
  49494. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  49495. */
  49496. set: function (value) {
  49497. this._shadowAngle = value;
  49498. this.forceProjectionMatrixCompute();
  49499. },
  49500. enumerable: true,
  49501. configurable: true
  49502. });
  49503. Object.defineProperty(PointLight.prototype, "direction", {
  49504. /**
  49505. * Gets the direction if it has been set.
  49506. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  49507. */
  49508. get: function () {
  49509. return this._direction;
  49510. },
  49511. /**
  49512. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  49513. */
  49514. set: function (value) {
  49515. var previousNeedCube = this.needCube();
  49516. this._direction = value;
  49517. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  49518. this._shadowGenerator.recreateShadowMap();
  49519. }
  49520. },
  49521. enumerable: true,
  49522. configurable: true
  49523. });
  49524. /**
  49525. * Returns the string "PointLight"
  49526. * @returns the class name
  49527. */
  49528. PointLight.prototype.getClassName = function () {
  49529. return "PointLight";
  49530. };
  49531. /**
  49532. * Returns the integer 0.
  49533. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  49534. */
  49535. PointLight.prototype.getTypeID = function () {
  49536. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  49537. };
  49538. /**
  49539. * Specifies wether or not the shadowmap should be a cube texture.
  49540. * @returns true if the shadowmap needs to be a cube texture.
  49541. */
  49542. PointLight.prototype.needCube = function () {
  49543. return !this.direction;
  49544. };
  49545. /**
  49546. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  49547. * @param faceIndex The index of the face we are computed the direction to generate shadow
  49548. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  49549. */
  49550. PointLight.prototype.getShadowDirection = function (faceIndex) {
  49551. if (this.direction) {
  49552. return _super.prototype.getShadowDirection.call(this, faceIndex);
  49553. }
  49554. else {
  49555. switch (faceIndex) {
  49556. case 0:
  49557. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  49558. case 1:
  49559. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  49560. case 2:
  49561. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  49562. case 3:
  49563. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  49564. case 4:
  49565. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  49566. case 5:
  49567. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  49568. }
  49569. }
  49570. return BABYLON.Vector3.Zero();
  49571. };
  49572. /**
  49573. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  49574. * - fov = PI / 2
  49575. * - aspect ratio : 1.0
  49576. * - z-near and far equal to the active camera minZ and maxZ.
  49577. * Returns the PointLight.
  49578. */
  49579. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49580. var activeCamera = this.getScene().activeCamera;
  49581. if (!activeCamera) {
  49582. return;
  49583. }
  49584. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  49585. };
  49586. PointLight.prototype._buildUniformLayout = function () {
  49587. this._uniformBuffer.addUniform("vLightData", 4);
  49588. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  49589. this._uniformBuffer.addUniform("vLightSpecular", 3);
  49590. this._uniformBuffer.addUniform("vLightFalloff", 4);
  49591. this._uniformBuffer.addUniform("shadowsInfo", 3);
  49592. this._uniformBuffer.addUniform("depthValues", 2);
  49593. this._uniformBuffer.create();
  49594. };
  49595. /**
  49596. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  49597. * @param effect The effect to update
  49598. * @param lightIndex The index of the light in the effect to update
  49599. * @returns The point light
  49600. */
  49601. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  49602. if (this.computeTransformedInformation()) {
  49603. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  49604. }
  49605. else {
  49606. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  49607. }
  49608. this._uniformBuffer.updateFloat4("vLightFalloff", this.range, this._inverseSquaredRange, 0, 0, lightIndex);
  49609. return this;
  49610. };
  49611. /**
  49612. * Prepares the list of defines specific to the light type.
  49613. * @param defines the list of defines
  49614. * @param lightIndex defines the index of the light for the effect
  49615. */
  49616. PointLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
  49617. defines["POINTLIGHT" + lightIndex] = true;
  49618. };
  49619. __decorate([
  49620. BABYLON.serialize()
  49621. ], PointLight.prototype, "shadowAngle", null);
  49622. return PointLight;
  49623. }(BABYLON.ShadowLight));
  49624. BABYLON.PointLight = PointLight;
  49625. })(BABYLON || (BABYLON = {}));
  49626. //# sourceMappingURL=babylon.pointLight.js.map
  49627. var BABYLON;
  49628. (function (BABYLON) {
  49629. BABYLON.Node.AddNodeConstructor("Light_Type_1", function (name, scene) {
  49630. return function () { return new DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  49631. });
  49632. /**
  49633. * A directional light is defined by a direction (what a surprise!).
  49634. * The light is emitted from everywhere in the specified direction, and has an infinite range.
  49635. * 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.
  49636. * Documentation: https://doc.babylonjs.com/babylon101/lights
  49637. */
  49638. var DirectionalLight = /** @class */ (function (_super) {
  49639. __extends(DirectionalLight, _super);
  49640. /**
  49641. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  49642. * The directional light is emitted from everywhere in the given direction.
  49643. * It can cast shadows.
  49644. * Documentation : http://doc.babylonjs.com/tutorials/lights
  49645. * @param name The friendly name of the light
  49646. * @param direction The direction of the light
  49647. * @param scene The scene the light belongs to
  49648. */
  49649. function DirectionalLight(name, direction, scene) {
  49650. var _this = _super.call(this, name, scene) || this;
  49651. _this._shadowFrustumSize = 0;
  49652. _this._shadowOrthoScale = 0.1;
  49653. /**
  49654. * Automatically compute the projection matrix to best fit (including all the casters)
  49655. * on each frame.
  49656. */
  49657. _this.autoUpdateExtends = true;
  49658. // Cache
  49659. _this._orthoLeft = Number.MAX_VALUE;
  49660. _this._orthoRight = Number.MIN_VALUE;
  49661. _this._orthoTop = Number.MIN_VALUE;
  49662. _this._orthoBottom = Number.MAX_VALUE;
  49663. _this.position = direction.scale(-1.0);
  49664. _this.direction = direction;
  49665. return _this;
  49666. }
  49667. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  49668. /**
  49669. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  49670. */
  49671. get: function () {
  49672. return this._shadowFrustumSize;
  49673. },
  49674. /**
  49675. * Specifies a fix frustum size for the shadow generation.
  49676. */
  49677. set: function (value) {
  49678. this._shadowFrustumSize = value;
  49679. this.forceProjectionMatrixCompute();
  49680. },
  49681. enumerable: true,
  49682. configurable: true
  49683. });
  49684. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  49685. /**
  49686. * Gets the shadow projection scale against the optimal computed one.
  49687. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  49688. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  49689. */
  49690. get: function () {
  49691. return this._shadowOrthoScale;
  49692. },
  49693. /**
  49694. * Sets the shadow projection scale against the optimal computed one.
  49695. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  49696. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  49697. */
  49698. set: function (value) {
  49699. this._shadowOrthoScale = value;
  49700. this.forceProjectionMatrixCompute();
  49701. },
  49702. enumerable: true,
  49703. configurable: true
  49704. });
  49705. /**
  49706. * Returns the string "DirectionalLight".
  49707. * @return The class name
  49708. */
  49709. DirectionalLight.prototype.getClassName = function () {
  49710. return "DirectionalLight";
  49711. };
  49712. /**
  49713. * Returns the integer 1.
  49714. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  49715. */
  49716. DirectionalLight.prototype.getTypeID = function () {
  49717. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  49718. };
  49719. /**
  49720. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  49721. * Returns the DirectionalLight Shadow projection matrix.
  49722. */
  49723. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49724. if (this.shadowFrustumSize > 0) {
  49725. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  49726. }
  49727. else {
  49728. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  49729. }
  49730. };
  49731. /**
  49732. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  49733. * Returns the DirectionalLight Shadow projection matrix.
  49734. */
  49735. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  49736. var activeCamera = this.getScene().activeCamera;
  49737. if (!activeCamera) {
  49738. return;
  49739. }
  49740. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  49741. };
  49742. /**
  49743. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  49744. * Returns the DirectionalLight Shadow projection matrix.
  49745. */
  49746. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49747. var activeCamera = this.getScene().activeCamera;
  49748. if (!activeCamera) {
  49749. return;
  49750. }
  49751. // Check extends
  49752. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  49753. var tempVector3 = BABYLON.Vector3.Zero();
  49754. this._orthoLeft = Number.MAX_VALUE;
  49755. this._orthoRight = Number.MIN_VALUE;
  49756. this._orthoTop = Number.MIN_VALUE;
  49757. this._orthoBottom = Number.MAX_VALUE;
  49758. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  49759. var mesh = renderList[meshIndex];
  49760. if (!mesh) {
  49761. continue;
  49762. }
  49763. var boundingInfo = mesh.getBoundingInfo();
  49764. var boundingBox = boundingInfo.boundingBox;
  49765. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  49766. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  49767. if (tempVector3.x < this._orthoLeft)
  49768. this._orthoLeft = tempVector3.x;
  49769. if (tempVector3.y < this._orthoBottom)
  49770. this._orthoBottom = tempVector3.y;
  49771. if (tempVector3.x > this._orthoRight)
  49772. this._orthoRight = tempVector3.x;
  49773. if (tempVector3.y > this._orthoTop)
  49774. this._orthoTop = tempVector3.y;
  49775. }
  49776. }
  49777. }
  49778. var xOffset = this._orthoRight - this._orthoLeft;
  49779. var yOffset = this._orthoTop - this._orthoBottom;
  49780. 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);
  49781. };
  49782. DirectionalLight.prototype._buildUniformLayout = function () {
  49783. this._uniformBuffer.addUniform("vLightData", 4);
  49784. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  49785. this._uniformBuffer.addUniform("vLightSpecular", 3);
  49786. this._uniformBuffer.addUniform("shadowsInfo", 3);
  49787. this._uniformBuffer.addUniform("depthValues", 2);
  49788. this._uniformBuffer.create();
  49789. };
  49790. /**
  49791. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  49792. * @param effect The effect to update
  49793. * @param lightIndex The index of the light in the effect to update
  49794. * @returns The directional light
  49795. */
  49796. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  49797. if (this.computeTransformedInformation()) {
  49798. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  49799. return this;
  49800. }
  49801. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  49802. return this;
  49803. };
  49804. /**
  49805. * Gets the minZ used for shadow according to both the scene and the light.
  49806. *
  49807. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  49808. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  49809. * @param activeCamera The camera we are returning the min for
  49810. * @returns the depth min z
  49811. */
  49812. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  49813. return 1;
  49814. };
  49815. /**
  49816. * Gets the maxZ used for shadow according to both the scene and the light.
  49817. *
  49818. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  49819. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  49820. * @param activeCamera The camera we are returning the max for
  49821. * @returns the depth max z
  49822. */
  49823. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  49824. return 1;
  49825. };
  49826. /**
  49827. * Prepares the list of defines specific to the light type.
  49828. * @param defines the list of defines
  49829. * @param lightIndex defines the index of the light for the effect
  49830. */
  49831. DirectionalLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
  49832. defines["DIRLIGHT" + lightIndex] = true;
  49833. };
  49834. __decorate([
  49835. BABYLON.serialize()
  49836. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  49837. __decorate([
  49838. BABYLON.serialize()
  49839. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  49840. __decorate([
  49841. BABYLON.serialize()
  49842. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  49843. return DirectionalLight;
  49844. }(BABYLON.ShadowLight));
  49845. BABYLON.DirectionalLight = DirectionalLight;
  49846. })(BABYLON || (BABYLON = {}));
  49847. //# sourceMappingURL=babylon.directionalLight.js.map
  49848. var BABYLON;
  49849. (function (BABYLON) {
  49850. BABYLON.Node.AddNodeConstructor("Light_Type_2", function (name, scene) {
  49851. return function () { return new SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  49852. });
  49853. /**
  49854. * A spot light is defined by a position, a direction, an angle, and an exponent.
  49855. * These values define a cone of light starting from the position, emitting toward the direction.
  49856. * The angle, in radians, defines the size (field of illumination) of the spotlight's conical beam,
  49857. * and the exponent defines the speed of the decay of the light with distance (reach).
  49858. * Documentation: https://doc.babylonjs.com/babylon101/lights
  49859. */
  49860. var SpotLight = /** @class */ (function (_super) {
  49861. __extends(SpotLight, _super);
  49862. /**
  49863. * Creates a SpotLight object in the scene. A spot light is a simply light oriented cone.
  49864. * It can cast shadows.
  49865. * Documentation : http://doc.babylonjs.com/tutorials/lights
  49866. * @param name The light friendly name
  49867. * @param position The position of the spot light in the scene
  49868. * @param direction The direction of the light in the scene
  49869. * @param angle The cone angle of the light in Radians
  49870. * @param exponent The light decay speed with the distance from the emission spot
  49871. * @param scene The scene the lights belongs to
  49872. */
  49873. function SpotLight(name, position, direction, angle, exponent, scene) {
  49874. var _this = _super.call(this, name, scene) || this;
  49875. _this._innerAngle = 0;
  49876. _this._projectionTextureMatrix = BABYLON.Matrix.Zero();
  49877. _this._projectionTextureLightNear = 1e-6;
  49878. _this._projectionTextureLightFar = 1000.0;
  49879. _this._projectionTextureUpDirection = BABYLON.Vector3.Up();
  49880. _this._projectionTextureViewLightDirty = true;
  49881. _this._projectionTextureProjectionLightDirty = true;
  49882. _this._projectionTextureDirty = true;
  49883. _this._projectionTextureViewTargetVector = BABYLON.Vector3.Zero();
  49884. _this._projectionTextureViewLightMatrix = BABYLON.Matrix.Zero();
  49885. _this._projectionTextureProjectionLightMatrix = BABYLON.Matrix.Zero();
  49886. _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);
  49887. _this.position = position;
  49888. _this.direction = direction;
  49889. _this.angle = angle;
  49890. _this.exponent = exponent;
  49891. return _this;
  49892. }
  49893. Object.defineProperty(SpotLight.prototype, "angle", {
  49894. /**
  49895. * Gets the cone angle of the spot light in Radians.
  49896. */
  49897. get: function () {
  49898. return this._angle;
  49899. },
  49900. /**
  49901. * Sets the cone angle of the spot light in Radians.
  49902. */
  49903. set: function (value) {
  49904. this._angle = value;
  49905. this._cosHalfAngle = Math.cos(value * 0.5);
  49906. this._projectionTextureProjectionLightDirty = true;
  49907. this.forceProjectionMatrixCompute();
  49908. this._computeAngleValues();
  49909. },
  49910. enumerable: true,
  49911. configurable: true
  49912. });
  49913. Object.defineProperty(SpotLight.prototype, "innerAngle", {
  49914. /**
  49915. * Only used in gltf falloff mode, this defines the angle where
  49916. * the directional falloff will start before cutting at angle which could be seen
  49917. * as outer angle.
  49918. */
  49919. get: function () {
  49920. return this._innerAngle;
  49921. },
  49922. /**
  49923. * Only used in gltf falloff mode, this defines the angle where
  49924. * the directional falloff will start before cutting at angle which could be seen
  49925. * as outer angle.
  49926. */
  49927. set: function (value) {
  49928. this._innerAngle = value;
  49929. this._computeAngleValues();
  49930. },
  49931. enumerable: true,
  49932. configurable: true
  49933. });
  49934. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  49935. /**
  49936. * Allows scaling the angle of the light for shadow generation only.
  49937. */
  49938. get: function () {
  49939. return this._shadowAngleScale;
  49940. },
  49941. /**
  49942. * Allows scaling the angle of the light for shadow generation only.
  49943. */
  49944. set: function (value) {
  49945. this._shadowAngleScale = value;
  49946. this.forceProjectionMatrixCompute();
  49947. },
  49948. enumerable: true,
  49949. configurable: true
  49950. });
  49951. Object.defineProperty(SpotLight.prototype, "projectionTextureMatrix", {
  49952. /**
  49953. * Allows reading the projecton texture
  49954. */
  49955. get: function () {
  49956. return this._projectionTextureMatrix;
  49957. },
  49958. enumerable: true,
  49959. configurable: true
  49960. });
  49961. Object.defineProperty(SpotLight.prototype, "projectionTextureLightNear", {
  49962. /**
  49963. * Gets the near clip of the Spotlight for texture projection.
  49964. */
  49965. get: function () {
  49966. return this._projectionTextureLightNear;
  49967. },
  49968. /**
  49969. * Sets the near clip of the Spotlight for texture projection.
  49970. */
  49971. set: function (value) {
  49972. this._projectionTextureLightNear = value;
  49973. this._projectionTextureProjectionLightDirty = true;
  49974. },
  49975. enumerable: true,
  49976. configurable: true
  49977. });
  49978. Object.defineProperty(SpotLight.prototype, "projectionTextureLightFar", {
  49979. /**
  49980. * Gets the far clip of the Spotlight for texture projection.
  49981. */
  49982. get: function () {
  49983. return this._projectionTextureLightFar;
  49984. },
  49985. /**
  49986. * Sets the far clip of the Spotlight for texture projection.
  49987. */
  49988. set: function (value) {
  49989. this._projectionTextureLightFar = value;
  49990. this._projectionTextureProjectionLightDirty = true;
  49991. },
  49992. enumerable: true,
  49993. configurable: true
  49994. });
  49995. Object.defineProperty(SpotLight.prototype, "projectionTextureUpDirection", {
  49996. /**
  49997. * Gets the Up vector of the Spotlight for texture projection.
  49998. */
  49999. get: function () {
  50000. return this._projectionTextureUpDirection;
  50001. },
  50002. /**
  50003. * Sets the Up vector of the Spotlight for texture projection.
  50004. */
  50005. set: function (value) {
  50006. this._projectionTextureUpDirection = value;
  50007. this._projectionTextureProjectionLightDirty = true;
  50008. },
  50009. enumerable: true,
  50010. configurable: true
  50011. });
  50012. Object.defineProperty(SpotLight.prototype, "projectionTexture", {
  50013. /**
  50014. * Gets the projection texture of the light.
  50015. */
  50016. get: function () {
  50017. return this._projectionTexture;
  50018. },
  50019. /**
  50020. * Sets the projection texture of the light.
  50021. */
  50022. set: function (value) {
  50023. this._projectionTexture = value;
  50024. this._projectionTextureDirty = true;
  50025. },
  50026. enumerable: true,
  50027. configurable: true
  50028. });
  50029. /**
  50030. * Returns the string "SpotLight".
  50031. * @returns the class name
  50032. */
  50033. SpotLight.prototype.getClassName = function () {
  50034. return "SpotLight";
  50035. };
  50036. /**
  50037. * Returns the integer 2.
  50038. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  50039. */
  50040. SpotLight.prototype.getTypeID = function () {
  50041. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  50042. };
  50043. /**
  50044. * Overrides the direction setter to recompute the projection texture view light Matrix.
  50045. */
  50046. SpotLight.prototype._setDirection = function (value) {
  50047. _super.prototype._setDirection.call(this, value);
  50048. this._projectionTextureViewLightDirty = true;
  50049. };
  50050. /**
  50051. * Overrides the position setter to recompute the projection texture view light Matrix.
  50052. */
  50053. SpotLight.prototype._setPosition = function (value) {
  50054. _super.prototype._setPosition.call(this, value);
  50055. this._projectionTextureViewLightDirty = true;
  50056. };
  50057. /**
  50058. * 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.
  50059. * Returns the SpotLight.
  50060. */
  50061. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  50062. var activeCamera = this.getScene().activeCamera;
  50063. if (!activeCamera) {
  50064. return;
  50065. }
  50066. this._shadowAngleScale = this._shadowAngleScale || 1;
  50067. var angle = this._shadowAngleScale * this._angle;
  50068. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  50069. };
  50070. SpotLight.prototype._computeProjectionTextureViewLightMatrix = function () {
  50071. this._projectionTextureViewLightDirty = false;
  50072. this._projectionTextureDirty = true;
  50073. this.position.addToRef(this.direction, this._projectionTextureViewTargetVector);
  50074. BABYLON.Matrix.LookAtLHToRef(this.position, this._projectionTextureViewTargetVector, this._projectionTextureUpDirection, this._projectionTextureViewLightMatrix);
  50075. };
  50076. SpotLight.prototype._computeProjectionTextureProjectionLightMatrix = function () {
  50077. this._projectionTextureProjectionLightDirty = false;
  50078. this._projectionTextureDirty = true;
  50079. var light_far = this.projectionTextureLightFar;
  50080. var light_near = this.projectionTextureLightNear;
  50081. var P = light_far / (light_far - light_near);
  50082. var Q = -P * light_near;
  50083. var S = 1.0 / Math.tan(this._angle / 2.0);
  50084. var A = 1.0;
  50085. 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);
  50086. };
  50087. /**
  50088. * Main function for light texture projection matrix computing.
  50089. */
  50090. SpotLight.prototype._computeProjectionTextureMatrix = function () {
  50091. this._projectionTextureDirty = false;
  50092. this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix, this._projectionTextureMatrix);
  50093. this._projectionTextureMatrix.multiplyToRef(this._projectionTextureScalingMatrix, this._projectionTextureMatrix);
  50094. };
  50095. SpotLight.prototype._buildUniformLayout = function () {
  50096. this._uniformBuffer.addUniform("vLightData", 4);
  50097. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  50098. this._uniformBuffer.addUniform("vLightSpecular", 3);
  50099. this._uniformBuffer.addUniform("vLightDirection", 3);
  50100. this._uniformBuffer.addUniform("vLightFalloff", 4);
  50101. this._uniformBuffer.addUniform("shadowsInfo", 3);
  50102. this._uniformBuffer.addUniform("depthValues", 2);
  50103. this._uniformBuffer.create();
  50104. };
  50105. SpotLight.prototype._computeAngleValues = function () {
  50106. this._lightAngleScale = 1.0 / Math.max(0.001, (Math.cos(this._innerAngle * 0.5) - this._cosHalfAngle));
  50107. this._lightAngleOffset = -this._cosHalfAngle * this._lightAngleScale;
  50108. };
  50109. /**
  50110. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  50111. * @param effect The effect to update
  50112. * @param lightIndex The index of the light in the effect to update
  50113. * @returns The spot light
  50114. */
  50115. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  50116. var normalizeDirection;
  50117. if (this.computeTransformedInformation()) {
  50118. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  50119. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  50120. }
  50121. else {
  50122. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  50123. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  50124. }
  50125. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, this._cosHalfAngle, lightIndex);
  50126. this._uniformBuffer.updateFloat4("vLightFalloff", this.range, this._inverseSquaredRange, this._lightAngleScale, this._lightAngleOffset, lightIndex);
  50127. if (this.projectionTexture && this.projectionTexture.isReady()) {
  50128. if (this._projectionTextureViewLightDirty) {
  50129. this._computeProjectionTextureViewLightMatrix();
  50130. }
  50131. if (this._projectionTextureProjectionLightDirty) {
  50132. this._computeProjectionTextureProjectionLightMatrix();
  50133. }
  50134. if (this._projectionTextureDirty) {
  50135. this._computeProjectionTextureMatrix();
  50136. }
  50137. effect.setMatrix("textureProjectionMatrix" + lightIndex, this._projectionTextureMatrix);
  50138. effect.setTexture("projectionLightSampler" + lightIndex, this.projectionTexture);
  50139. }
  50140. return this;
  50141. };
  50142. /**
  50143. * Disposes the light and the associated resources.
  50144. */
  50145. SpotLight.prototype.dispose = function () {
  50146. _super.prototype.dispose.call(this);
  50147. if (this._projectionTexture) {
  50148. this._projectionTexture.dispose();
  50149. }
  50150. };
  50151. /**
  50152. * Prepares the list of defines specific to the light type.
  50153. * @param defines the list of defines
  50154. * @param lightIndex defines the index of the light for the effect
  50155. */
  50156. SpotLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
  50157. defines["SPOTLIGHT" + lightIndex] = true;
  50158. defines["PROJECTEDLIGHTTEXTURE" + lightIndex] = this.projectionTexture ? true : false;
  50159. };
  50160. __decorate([
  50161. BABYLON.serialize()
  50162. ], SpotLight.prototype, "angle", null);
  50163. __decorate([
  50164. BABYLON.serialize()
  50165. ], SpotLight.prototype, "innerAngle", null);
  50166. __decorate([
  50167. BABYLON.serialize()
  50168. ], SpotLight.prototype, "shadowAngleScale", null);
  50169. __decorate([
  50170. BABYLON.serialize()
  50171. ], SpotLight.prototype, "exponent", void 0);
  50172. __decorate([
  50173. BABYLON.serialize()
  50174. ], SpotLight.prototype, "projectionTextureLightNear", null);
  50175. __decorate([
  50176. BABYLON.serialize()
  50177. ], SpotLight.prototype, "projectionTextureLightFar", null);
  50178. __decorate([
  50179. BABYLON.serialize()
  50180. ], SpotLight.prototype, "projectionTextureUpDirection", null);
  50181. __decorate([
  50182. BABYLON.serializeAsTexture("projectedLightTexture")
  50183. ], SpotLight.prototype, "_projectionTexture", void 0);
  50184. return SpotLight;
  50185. }(BABYLON.ShadowLight));
  50186. BABYLON.SpotLight = SpotLight;
  50187. })(BABYLON || (BABYLON = {}));
  50188. //# sourceMappingURL=babylon.spotLight.js.map
  50189. var BABYLON;
  50190. (function (BABYLON) {
  50191. /**
  50192. * Class used to override all child animations of a given target
  50193. */
  50194. var AnimationPropertiesOverride = /** @class */ (function () {
  50195. function AnimationPropertiesOverride() {
  50196. /**
  50197. * Gets or sets a value indicating if animation blending must be used
  50198. */
  50199. this.enableBlending = false;
  50200. /**
  50201. * Gets or sets the blending speed to use when enableBlending is true
  50202. */
  50203. this.blendingSpeed = 0.01;
  50204. /**
  50205. * Gets or sets the default loop mode to use
  50206. */
  50207. this.loopMode = BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE;
  50208. }
  50209. return AnimationPropertiesOverride;
  50210. }());
  50211. BABYLON.AnimationPropertiesOverride = AnimationPropertiesOverride;
  50212. })(BABYLON || (BABYLON = {}));
  50213. //# sourceMappingURL=babylon.animationPropertiesOverride.js.map
  50214. var BABYLON;
  50215. (function (BABYLON) {
  50216. /**
  50217. * Represents the range of an animation
  50218. */
  50219. var AnimationRange = /** @class */ (function () {
  50220. /**
  50221. * Initializes the range of an animation
  50222. * @param name The name of the animation range
  50223. * @param from The starting frame of the animation
  50224. * @param to The ending frame of the animation
  50225. */
  50226. function AnimationRange(
  50227. /**The name of the animation range**/
  50228. name,
  50229. /**The starting frame of the animation */
  50230. from,
  50231. /**The ending frame of the animation*/
  50232. to) {
  50233. this.name = name;
  50234. this.from = from;
  50235. this.to = to;
  50236. }
  50237. /**
  50238. * Makes a copy of the animation range
  50239. * @returns A copy of the animation range
  50240. */
  50241. AnimationRange.prototype.clone = function () {
  50242. return new AnimationRange(this.name, this.from, this.to);
  50243. };
  50244. return AnimationRange;
  50245. }());
  50246. BABYLON.AnimationRange = AnimationRange;
  50247. /**
  50248. * Composed of a frame, and an action function
  50249. */
  50250. var AnimationEvent = /** @class */ (function () {
  50251. /**
  50252. * Initializes the animation event
  50253. * @param frame The frame for which the event is triggered
  50254. * @param action The event to perform when triggered
  50255. * @param onlyOnce Specifies if the event should be triggered only once
  50256. */
  50257. function AnimationEvent(
  50258. /** The frame for which the event is triggered **/
  50259. frame,
  50260. /** The event to perform when triggered **/
  50261. action,
  50262. /** Specifies if the event should be triggered only once**/
  50263. onlyOnce) {
  50264. this.frame = frame;
  50265. this.action = action;
  50266. this.onlyOnce = onlyOnce;
  50267. /**
  50268. * Specifies if the animation event is done
  50269. */
  50270. this.isDone = false;
  50271. }
  50272. /** @hidden */
  50273. AnimationEvent.prototype._clone = function () {
  50274. return new AnimationEvent(this.frame, this.action, this.onlyOnce);
  50275. };
  50276. return AnimationEvent;
  50277. }());
  50278. BABYLON.AnimationEvent = AnimationEvent;
  50279. /**
  50280. * A cursor which tracks a point on a path
  50281. */
  50282. var PathCursor = /** @class */ (function () {
  50283. /**
  50284. * Initializes the path cursor
  50285. * @param path The path to track
  50286. */
  50287. function PathCursor(path) {
  50288. this.path = path;
  50289. /**
  50290. * Stores path cursor callbacks for when an onchange event is triggered
  50291. */
  50292. this._onchange = new Array();
  50293. /**
  50294. * The value of the path cursor
  50295. */
  50296. this.value = 0;
  50297. /**
  50298. * The animation array of the path cursor
  50299. */
  50300. this.animations = new Array();
  50301. }
  50302. /**
  50303. * Gets the cursor point on the path
  50304. * @returns A point on the path cursor at the cursor location
  50305. */
  50306. PathCursor.prototype.getPoint = function () {
  50307. var point = this.path.getPointAtLengthPosition(this.value);
  50308. return new BABYLON.Vector3(point.x, 0, point.y);
  50309. };
  50310. /**
  50311. * Moves the cursor ahead by the step amount
  50312. * @param step The amount to move the cursor forward
  50313. * @returns This path cursor
  50314. */
  50315. PathCursor.prototype.moveAhead = function (step) {
  50316. if (step === void 0) { step = 0.002; }
  50317. this.move(step);
  50318. return this;
  50319. };
  50320. /**
  50321. * Moves the cursor behind by the step amount
  50322. * @param step The amount to move the cursor back
  50323. * @returns This path cursor
  50324. */
  50325. PathCursor.prototype.moveBack = function (step) {
  50326. if (step === void 0) { step = 0.002; }
  50327. this.move(-step);
  50328. return this;
  50329. };
  50330. /**
  50331. * Moves the cursor by the step amount
  50332. * If the step amount is greater than one, an exception is thrown
  50333. * @param step The amount to move the cursor
  50334. * @returns This path cursor
  50335. */
  50336. PathCursor.prototype.move = function (step) {
  50337. if (Math.abs(step) > 1) {
  50338. throw "step size should be less than 1.";
  50339. }
  50340. this.value += step;
  50341. this.ensureLimits();
  50342. this.raiseOnChange();
  50343. return this;
  50344. };
  50345. /**
  50346. * Ensures that the value is limited between zero and one
  50347. * @returns This path cursor
  50348. */
  50349. PathCursor.prototype.ensureLimits = function () {
  50350. while (this.value > 1) {
  50351. this.value -= 1;
  50352. }
  50353. while (this.value < 0) {
  50354. this.value += 1;
  50355. }
  50356. return this;
  50357. };
  50358. /**
  50359. * Runs onchange callbacks on change (used by the animation engine)
  50360. * @returns This path cursor
  50361. */
  50362. PathCursor.prototype.raiseOnChange = function () {
  50363. var _this = this;
  50364. this._onchange.forEach(function (f) { return f(_this); });
  50365. return this;
  50366. };
  50367. /**
  50368. * Executes a function on change
  50369. * @param f A path cursor onchange callback
  50370. * @returns This path cursor
  50371. */
  50372. PathCursor.prototype.onchange = function (f) {
  50373. this._onchange.push(f);
  50374. return this;
  50375. };
  50376. return PathCursor;
  50377. }());
  50378. BABYLON.PathCursor = PathCursor;
  50379. /**
  50380. * Enum for the animation key frame interpolation type
  50381. */
  50382. var AnimationKeyInterpolation;
  50383. (function (AnimationKeyInterpolation) {
  50384. /**
  50385. * Do not interpolate between keys and use the start key value only. Tangents are ignored
  50386. */
  50387. AnimationKeyInterpolation[AnimationKeyInterpolation["STEP"] = 1] = "STEP";
  50388. })(AnimationKeyInterpolation = BABYLON.AnimationKeyInterpolation || (BABYLON.AnimationKeyInterpolation = {}));
  50389. /**
  50390. * Class used to store any kind of animation
  50391. */
  50392. var Animation = /** @class */ (function () {
  50393. /**
  50394. * Initializes the animation
  50395. * @param name Name of the animation
  50396. * @param targetProperty Property to animate
  50397. * @param framePerSecond The frames per second of the animation
  50398. * @param dataType The data type of the animation
  50399. * @param loopMode The loop mode of the animation
  50400. * @param enableBlendings Specifies if blending should be enabled
  50401. */
  50402. function Animation(
  50403. /**Name of the animation */
  50404. name,
  50405. /**Property to animate */
  50406. targetProperty,
  50407. /**The frames per second of the animation */
  50408. framePerSecond,
  50409. /**The data type of the animation */
  50410. dataType,
  50411. /**The loop mode of the animation */
  50412. loopMode,
  50413. /**Specifies if blending should be enabled */
  50414. enableBlending) {
  50415. this.name = name;
  50416. this.targetProperty = targetProperty;
  50417. this.framePerSecond = framePerSecond;
  50418. this.dataType = dataType;
  50419. this.loopMode = loopMode;
  50420. this.enableBlending = enableBlending;
  50421. /**
  50422. * @hidden Internal use only
  50423. */
  50424. this._runtimeAnimations = new Array();
  50425. /**
  50426. * The set of event that will be linked to this animation
  50427. */
  50428. this._events = new Array();
  50429. /**
  50430. * Stores the blending speed of the animation
  50431. */
  50432. this.blendingSpeed = 0.01;
  50433. /**
  50434. * Stores the animation ranges for the animation
  50435. */
  50436. this._ranges = {};
  50437. this.targetPropertyPath = targetProperty.split(".");
  50438. this.dataType = dataType;
  50439. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  50440. }
  50441. /**
  50442. * @hidden Internal use
  50443. */
  50444. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  50445. var dataType = undefined;
  50446. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  50447. dataType = Animation.ANIMATIONTYPE_FLOAT;
  50448. }
  50449. else if (from instanceof BABYLON.Quaternion) {
  50450. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  50451. }
  50452. else if (from instanceof BABYLON.Vector3) {
  50453. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  50454. }
  50455. else if (from instanceof BABYLON.Vector2) {
  50456. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  50457. }
  50458. else if (from instanceof BABYLON.Color3) {
  50459. dataType = Animation.ANIMATIONTYPE_COLOR3;
  50460. }
  50461. else if (from instanceof BABYLON.Size) {
  50462. dataType = Animation.ANIMATIONTYPE_SIZE;
  50463. }
  50464. if (dataType == undefined) {
  50465. return null;
  50466. }
  50467. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  50468. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  50469. animation.setKeys(keys);
  50470. if (easingFunction !== undefined) {
  50471. animation.setEasingFunction(easingFunction);
  50472. }
  50473. return animation;
  50474. };
  50475. /**
  50476. * Sets up an animation
  50477. * @param property The property to animate
  50478. * @param animationType The animation type to apply
  50479. * @param framePerSecond The frames per second of the animation
  50480. * @param easingFunction The easing function used in the animation
  50481. * @returns The created animation
  50482. */
  50483. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  50484. var animation = new Animation(property + "Animation", property, framePerSecond, animationType, Animation.ANIMATIONLOOPMODE_CONSTANT);
  50485. animation.setEasingFunction(easingFunction);
  50486. return animation;
  50487. };
  50488. /**
  50489. * Create and start an animation on a node
  50490. * @param name defines the name of the global animation that will be run on all nodes
  50491. * @param node defines the root node where the animation will take place
  50492. * @param targetProperty defines property to animate
  50493. * @param framePerSecond defines the number of frame per second yo use
  50494. * @param totalFrame defines the number of frames in total
  50495. * @param from defines the initial value
  50496. * @param to defines the final value
  50497. * @param loopMode defines which loop mode you want to use (off by default)
  50498. * @param easingFunction defines the easing function to use (linear by default)
  50499. * @param onAnimationEnd defines the callback to call when animation end
  50500. * @returns the animatable created for this animation
  50501. */
  50502. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  50503. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  50504. if (!animation) {
  50505. return null;
  50506. }
  50507. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  50508. };
  50509. /**
  50510. * Create and start an animation on a node and its descendants
  50511. * @param name defines the name of the global animation that will be run on all nodes
  50512. * @param node defines the root node where the animation will take place
  50513. * @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
  50514. * @param targetProperty defines property to animate
  50515. * @param framePerSecond defines the number of frame per second to use
  50516. * @param totalFrame defines the number of frames in total
  50517. * @param from defines the initial value
  50518. * @param to defines the final value
  50519. * @param loopMode defines which loop mode you want to use (off by default)
  50520. * @param easingFunction defines the easing function to use (linear by default)
  50521. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  50522. * @returns the list of animatables created for all nodes
  50523. * @example https://www.babylonjs-playground.com/#MH0VLI
  50524. */
  50525. Animation.CreateAndStartHierarchyAnimation = function (name, node, directDescendantsOnly, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  50526. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  50527. if (!animation) {
  50528. return null;
  50529. }
  50530. var scene = node.getScene();
  50531. return scene.beginDirectHierarchyAnimation(node, directDescendantsOnly, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  50532. };
  50533. /**
  50534. * Creates a new animation, merges it with the existing animations and starts it
  50535. * @param name Name of the animation
  50536. * @param node Node which contains the scene that begins the animations
  50537. * @param targetProperty Specifies which property to animate
  50538. * @param framePerSecond The frames per second of the animation
  50539. * @param totalFrame The total number of frames
  50540. * @param from The frame at the beginning of the animation
  50541. * @param to The frame at the end of the animation
  50542. * @param loopMode Specifies the loop mode of the animation
  50543. * @param easingFunction (Optional) The easing function of the animation, which allow custom mathematical formulas for animations
  50544. * @param onAnimationEnd Callback to run once the animation is complete
  50545. * @returns Nullable animation
  50546. */
  50547. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  50548. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  50549. if (!animation) {
  50550. return null;
  50551. }
  50552. node.animations.push(animation);
  50553. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  50554. };
  50555. /**
  50556. * Transition property of an host to the target Value
  50557. * @param property The property to transition
  50558. * @param targetValue The target Value of the property
  50559. * @param host The object where the property to animate belongs
  50560. * @param scene Scene used to run the animation
  50561. * @param frameRate Framerate (in frame/s) to use
  50562. * @param transition The transition type we want to use
  50563. * @param duration The duration of the animation, in milliseconds
  50564. * @param onAnimationEnd Callback trigger at the end of the animation
  50565. * @returns Nullable animation
  50566. */
  50567. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  50568. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  50569. if (duration <= 0) {
  50570. host[property] = targetValue;
  50571. if (onAnimationEnd) {
  50572. onAnimationEnd();
  50573. }
  50574. return null;
  50575. }
  50576. var endFrame = frameRate * (duration / 1000);
  50577. transition.setKeys([{
  50578. frame: 0,
  50579. value: host[property].clone ? host[property].clone() : host[property]
  50580. },
  50581. {
  50582. frame: endFrame,
  50583. value: targetValue
  50584. }]);
  50585. if (!host.animations) {
  50586. host.animations = [];
  50587. }
  50588. host.animations.push(transition);
  50589. var animation = scene.beginAnimation(host, 0, endFrame, false);
  50590. animation.onAnimationEnd = onAnimationEnd;
  50591. return animation;
  50592. };
  50593. Object.defineProperty(Animation.prototype, "runtimeAnimations", {
  50594. /**
  50595. * Return the array of runtime animations currently using this animation
  50596. */
  50597. get: function () {
  50598. return this._runtimeAnimations;
  50599. },
  50600. enumerable: true,
  50601. configurable: true
  50602. });
  50603. Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
  50604. /**
  50605. * Specifies if any of the runtime animations are currently running
  50606. */
  50607. get: function () {
  50608. for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
  50609. var runtimeAnimation = _a[_i];
  50610. if (!runtimeAnimation.isStopped) {
  50611. return true;
  50612. }
  50613. }
  50614. return false;
  50615. },
  50616. enumerable: true,
  50617. configurable: true
  50618. });
  50619. // Methods
  50620. /**
  50621. * Converts the animation to a string
  50622. * @param fullDetails support for multiple levels of logging within scene loading
  50623. * @returns String form of the animation
  50624. */
  50625. Animation.prototype.toString = function (fullDetails) {
  50626. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  50627. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  50628. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  50629. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  50630. if (fullDetails) {
  50631. ret += ", Ranges: {";
  50632. var first = true;
  50633. for (var name in this._ranges) {
  50634. if (first) {
  50635. ret += ", ";
  50636. first = false;
  50637. }
  50638. ret += name;
  50639. }
  50640. ret += "}";
  50641. }
  50642. return ret;
  50643. };
  50644. /**
  50645. * Add an event to this animation
  50646. * @param event Event to add
  50647. */
  50648. Animation.prototype.addEvent = function (event) {
  50649. this._events.push(event);
  50650. };
  50651. /**
  50652. * Remove all events found at the given frame
  50653. * @param frame The frame to remove events from
  50654. */
  50655. Animation.prototype.removeEvents = function (frame) {
  50656. for (var index = 0; index < this._events.length; index++) {
  50657. if (this._events[index].frame === frame) {
  50658. this._events.splice(index, 1);
  50659. index--;
  50660. }
  50661. }
  50662. };
  50663. /**
  50664. * Retrieves all the events from the animation
  50665. * @returns Events from the animation
  50666. */
  50667. Animation.prototype.getEvents = function () {
  50668. return this._events;
  50669. };
  50670. /**
  50671. * Creates an animation range
  50672. * @param name Name of the animation range
  50673. * @param from Starting frame of the animation range
  50674. * @param to Ending frame of the animation
  50675. */
  50676. Animation.prototype.createRange = function (name, from, to) {
  50677. // check name not already in use; could happen for bones after serialized
  50678. if (!this._ranges[name]) {
  50679. this._ranges[name] = new AnimationRange(name, from, to);
  50680. }
  50681. };
  50682. /**
  50683. * Deletes an animation range by name
  50684. * @param name Name of the animation range to delete
  50685. * @param deleteFrames Specifies if the key frames for the range should also be deleted (true) or not (false)
  50686. */
  50687. Animation.prototype.deleteRange = function (name, deleteFrames) {
  50688. if (deleteFrames === void 0) { deleteFrames = true; }
  50689. var range = this._ranges[name];
  50690. if (!range) {
  50691. return;
  50692. }
  50693. if (deleteFrames) {
  50694. var from = range.from;
  50695. var to = range.to;
  50696. // this loop MUST go high to low for multiple splices to work
  50697. for (var key = this._keys.length - 1; key >= 0; key--) {
  50698. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  50699. this._keys.splice(key, 1);
  50700. }
  50701. }
  50702. }
  50703. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  50704. };
  50705. /**
  50706. * Gets the animation range by name, or null if not defined
  50707. * @param name Name of the animation range
  50708. * @returns Nullable animation range
  50709. */
  50710. Animation.prototype.getRange = function (name) {
  50711. return this._ranges[name];
  50712. };
  50713. /**
  50714. * Gets the key frames from the animation
  50715. * @returns The key frames of the animation
  50716. */
  50717. Animation.prototype.getKeys = function () {
  50718. return this._keys;
  50719. };
  50720. /**
  50721. * Gets the highest frame rate of the animation
  50722. * @returns Highest frame rate of the animation
  50723. */
  50724. Animation.prototype.getHighestFrame = function () {
  50725. var ret = 0;
  50726. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  50727. if (ret < this._keys[key].frame) {
  50728. ret = this._keys[key].frame;
  50729. }
  50730. }
  50731. return ret;
  50732. };
  50733. /**
  50734. * Gets the easing function of the animation
  50735. * @returns Easing function of the animation
  50736. */
  50737. Animation.prototype.getEasingFunction = function () {
  50738. return this._easingFunction;
  50739. };
  50740. /**
  50741. * Sets the easing function of the animation
  50742. * @param easingFunction A custom mathematical formula for animation
  50743. */
  50744. Animation.prototype.setEasingFunction = function (easingFunction) {
  50745. this._easingFunction = easingFunction;
  50746. };
  50747. /**
  50748. * Interpolates a scalar linearly
  50749. * @param startValue Start value of the animation curve
  50750. * @param endValue End value of the animation curve
  50751. * @param gradient Scalar amount to interpolate
  50752. * @returns Interpolated scalar value
  50753. */
  50754. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  50755. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  50756. };
  50757. /**
  50758. * Interpolates a scalar cubically
  50759. * @param startValue Start value of the animation curve
  50760. * @param outTangent End tangent of the animation
  50761. * @param endValue End value of the animation curve
  50762. * @param inTangent Start tangent of the animation curve
  50763. * @param gradient Scalar amount to interpolate
  50764. * @returns Interpolated scalar value
  50765. */
  50766. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  50767. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  50768. };
  50769. /**
  50770. * Interpolates a quaternion using a spherical linear interpolation
  50771. * @param startValue Start value of the animation curve
  50772. * @param endValue End value of the animation curve
  50773. * @param gradient Scalar amount to interpolate
  50774. * @returns Interpolated quaternion value
  50775. */
  50776. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  50777. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  50778. };
  50779. /**
  50780. * Interpolates a quaternion cubically
  50781. * @param startValue Start value of the animation curve
  50782. * @param outTangent End tangent of the animation curve
  50783. * @param endValue End value of the animation curve
  50784. * @param inTangent Start tangent of the animation curve
  50785. * @param gradient Scalar amount to interpolate
  50786. * @returns Interpolated quaternion value
  50787. */
  50788. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  50789. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  50790. };
  50791. /**
  50792. * Interpolates a Vector3 linearl
  50793. * @param startValue Start value of the animation curve
  50794. * @param endValue End value of the animation curve
  50795. * @param gradient Scalar amount to interpolate
  50796. * @returns Interpolated scalar value
  50797. */
  50798. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  50799. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  50800. };
  50801. /**
  50802. * Interpolates a Vector3 cubically
  50803. * @param startValue Start value of the animation curve
  50804. * @param outTangent End tangent of the animation
  50805. * @param endValue End value of the animation curve
  50806. * @param inTangent Start tangent of the animation curve
  50807. * @param gradient Scalar amount to interpolate
  50808. * @returns InterpolatedVector3 value
  50809. */
  50810. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  50811. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  50812. };
  50813. /**
  50814. * Interpolates a Vector2 linearly
  50815. * @param startValue Start value of the animation curve
  50816. * @param endValue End value of the animation curve
  50817. * @param gradient Scalar amount to interpolate
  50818. * @returns Interpolated Vector2 value
  50819. */
  50820. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  50821. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  50822. };
  50823. /**
  50824. * Interpolates a Vector2 cubically
  50825. * @param startValue Start value of the animation curve
  50826. * @param outTangent End tangent of the animation
  50827. * @param endValue End value of the animation curve
  50828. * @param inTangent Start tangent of the animation curve
  50829. * @param gradient Scalar amount to interpolate
  50830. * @returns Interpolated Vector2 value
  50831. */
  50832. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  50833. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  50834. };
  50835. /**
  50836. * Interpolates a size linearly
  50837. * @param startValue Start value of the animation curve
  50838. * @param endValue End value of the animation curve
  50839. * @param gradient Scalar amount to interpolate
  50840. * @returns Interpolated Size value
  50841. */
  50842. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  50843. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  50844. };
  50845. /**
  50846. * Interpolates a Color3 linearly
  50847. * @param startValue Start value of the animation curve
  50848. * @param endValue End value of the animation curve
  50849. * @param gradient Scalar amount to interpolate
  50850. * @returns Interpolated Color3 value
  50851. */
  50852. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  50853. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  50854. };
  50855. /**
  50856. * @hidden Internal use only
  50857. */
  50858. Animation.prototype._getKeyValue = function (value) {
  50859. if (typeof value === "function") {
  50860. return value();
  50861. }
  50862. return value;
  50863. };
  50864. /**
  50865. * @hidden Internal use only
  50866. */
  50867. Animation.prototype._interpolate = function (currentFrame, repeatCount, workValue, loopMode, offsetValue, highLimitValue) {
  50868. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  50869. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  50870. }
  50871. var keys = this.getKeys();
  50872. // Try to get a hash to find the right key
  50873. 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));
  50874. if (keys[startKeyIndex].frame >= currentFrame) {
  50875. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  50876. startKeyIndex--;
  50877. }
  50878. }
  50879. for (var key = startKeyIndex; key < keys.length; key++) {
  50880. var endKey = keys[key + 1];
  50881. if (endKey.frame >= currentFrame) {
  50882. var startKey = keys[key];
  50883. var startValue = this._getKeyValue(startKey.value);
  50884. if (startKey.interpolation === AnimationKeyInterpolation.STEP) {
  50885. return startValue;
  50886. }
  50887. var endValue = this._getKeyValue(endKey.value);
  50888. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  50889. var frameDelta = endKey.frame - startKey.frame;
  50890. // gradient : percent of currentFrame between the frame inf and the frame sup
  50891. var gradient = (currentFrame - startKey.frame) / frameDelta;
  50892. // check for easingFunction and correction of gradient
  50893. var easingFunction = this.getEasingFunction();
  50894. if (easingFunction != null) {
  50895. gradient = easingFunction.ease(gradient);
  50896. }
  50897. switch (this.dataType) {
  50898. // Float
  50899. case Animation.ANIMATIONTYPE_FLOAT:
  50900. var floatValue = useTangent ? this.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this.floatInterpolateFunction(startValue, endValue, gradient);
  50901. switch (loopMode) {
  50902. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50903. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50904. return floatValue;
  50905. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50906. return offsetValue * repeatCount + floatValue;
  50907. }
  50908. break;
  50909. // Quaternion
  50910. case Animation.ANIMATIONTYPE_QUATERNION:
  50911. var quatValue = useTangent ? this.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.quaternionInterpolateFunction(startValue, endValue, gradient);
  50912. switch (loopMode) {
  50913. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50914. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50915. return quatValue;
  50916. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50917. return quatValue.addInPlace(offsetValue.scale(repeatCount));
  50918. }
  50919. return quatValue;
  50920. // Vector3
  50921. case Animation.ANIMATIONTYPE_VECTOR3:
  50922. var vec3Value = useTangent ? this.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector3InterpolateFunction(startValue, endValue, gradient);
  50923. switch (loopMode) {
  50924. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50925. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50926. return vec3Value;
  50927. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50928. return vec3Value.add(offsetValue.scale(repeatCount));
  50929. }
  50930. // Vector2
  50931. case Animation.ANIMATIONTYPE_VECTOR2:
  50932. var vec2Value = useTangent ? this.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector2InterpolateFunction(startValue, endValue, gradient);
  50933. switch (loopMode) {
  50934. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50935. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50936. return vec2Value;
  50937. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50938. return vec2Value.add(offsetValue.scale(repeatCount));
  50939. }
  50940. // Size
  50941. case Animation.ANIMATIONTYPE_SIZE:
  50942. switch (loopMode) {
  50943. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50944. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50945. return this.sizeInterpolateFunction(startValue, endValue, gradient);
  50946. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50947. return this.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  50948. }
  50949. // Color3
  50950. case Animation.ANIMATIONTYPE_COLOR3:
  50951. switch (loopMode) {
  50952. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50953. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50954. return this.color3InterpolateFunction(startValue, endValue, gradient);
  50955. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50956. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  50957. }
  50958. // Matrix
  50959. case Animation.ANIMATIONTYPE_MATRIX:
  50960. switch (loopMode) {
  50961. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50962. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50963. if (Animation.AllowMatricesInterpolation) {
  50964. return this.matrixInterpolateFunction(startValue, endValue, gradient, workValue);
  50965. }
  50966. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50967. return startValue;
  50968. }
  50969. default:
  50970. break;
  50971. }
  50972. break;
  50973. }
  50974. }
  50975. return this._getKeyValue(keys[keys.length - 1].value);
  50976. };
  50977. /**
  50978. * Defines the function to use to interpolate matrices
  50979. * @param startValue defines the start matrix
  50980. * @param endValue defines the end matrix
  50981. * @param gradient defines the gradient between both matrices
  50982. * @param result defines an optional target matrix where to store the interpolation
  50983. * @returns the interpolated matrix
  50984. */
  50985. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient, result) {
  50986. if (Animation.AllowMatrixDecomposeForInterpolation) {
  50987. if (result) {
  50988. BABYLON.Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
  50989. return result;
  50990. }
  50991. return BABYLON.Matrix.DecomposeLerp(startValue, endValue, gradient);
  50992. }
  50993. if (result) {
  50994. BABYLON.Matrix.LerpToRef(startValue, endValue, gradient, result);
  50995. return result;
  50996. }
  50997. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  50998. };
  50999. /**
  51000. * Makes a copy of the animation
  51001. * @returns Cloned animation
  51002. */
  51003. Animation.prototype.clone = function () {
  51004. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  51005. clone.enableBlending = this.enableBlending;
  51006. clone.blendingSpeed = this.blendingSpeed;
  51007. if (this._keys) {
  51008. clone.setKeys(this._keys);
  51009. }
  51010. if (this._ranges) {
  51011. clone._ranges = {};
  51012. for (var name in this._ranges) {
  51013. var range = this._ranges[name];
  51014. if (!range) {
  51015. continue;
  51016. }
  51017. clone._ranges[name] = range.clone();
  51018. }
  51019. }
  51020. return clone;
  51021. };
  51022. /**
  51023. * Sets the key frames of the animation
  51024. * @param values The animation key frames to set
  51025. */
  51026. Animation.prototype.setKeys = function (values) {
  51027. this._keys = values.slice(0);
  51028. };
  51029. /**
  51030. * Serializes the animation to an object
  51031. * @returns Serialized object
  51032. */
  51033. Animation.prototype.serialize = function () {
  51034. var serializationObject = {};
  51035. serializationObject.name = this.name;
  51036. serializationObject.property = this.targetProperty;
  51037. serializationObject.framePerSecond = this.framePerSecond;
  51038. serializationObject.dataType = this.dataType;
  51039. serializationObject.loopBehavior = this.loopMode;
  51040. serializationObject.enableBlending = this.enableBlending;
  51041. serializationObject.blendingSpeed = this.blendingSpeed;
  51042. var dataType = this.dataType;
  51043. serializationObject.keys = [];
  51044. var keys = this.getKeys();
  51045. for (var index = 0; index < keys.length; index++) {
  51046. var animationKey = keys[index];
  51047. var key = {};
  51048. key.frame = animationKey.frame;
  51049. switch (dataType) {
  51050. case Animation.ANIMATIONTYPE_FLOAT:
  51051. key.values = [animationKey.value];
  51052. break;
  51053. case Animation.ANIMATIONTYPE_QUATERNION:
  51054. case Animation.ANIMATIONTYPE_MATRIX:
  51055. case Animation.ANIMATIONTYPE_VECTOR3:
  51056. case Animation.ANIMATIONTYPE_COLOR3:
  51057. key.values = animationKey.value.asArray();
  51058. break;
  51059. }
  51060. serializationObject.keys.push(key);
  51061. }
  51062. serializationObject.ranges = [];
  51063. for (var name in this._ranges) {
  51064. var source = this._ranges[name];
  51065. if (!source) {
  51066. continue;
  51067. }
  51068. var range = {};
  51069. range.name = name;
  51070. range.from = source.from;
  51071. range.to = source.to;
  51072. serializationObject.ranges.push(range);
  51073. }
  51074. return serializationObject;
  51075. };
  51076. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  51077. /**
  51078. * Get the float animation type
  51079. */
  51080. get: function () {
  51081. return Animation._ANIMATIONTYPE_FLOAT;
  51082. },
  51083. enumerable: true,
  51084. configurable: true
  51085. });
  51086. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  51087. /**
  51088. * Get the Vector3 animation type
  51089. */
  51090. get: function () {
  51091. return Animation._ANIMATIONTYPE_VECTOR3;
  51092. },
  51093. enumerable: true,
  51094. configurable: true
  51095. });
  51096. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  51097. /**
  51098. * Get the Vector2 animation type
  51099. */
  51100. get: function () {
  51101. return Animation._ANIMATIONTYPE_VECTOR2;
  51102. },
  51103. enumerable: true,
  51104. configurable: true
  51105. });
  51106. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  51107. /**
  51108. * Get the Size animation type
  51109. */
  51110. get: function () {
  51111. return Animation._ANIMATIONTYPE_SIZE;
  51112. },
  51113. enumerable: true,
  51114. configurable: true
  51115. });
  51116. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  51117. /**
  51118. * Get the Quaternion animation type
  51119. */
  51120. get: function () {
  51121. return Animation._ANIMATIONTYPE_QUATERNION;
  51122. },
  51123. enumerable: true,
  51124. configurable: true
  51125. });
  51126. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  51127. /**
  51128. * Get the Matrix animation type
  51129. */
  51130. get: function () {
  51131. return Animation._ANIMATIONTYPE_MATRIX;
  51132. },
  51133. enumerable: true,
  51134. configurable: true
  51135. });
  51136. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  51137. /**
  51138. * Get the Color3 animation type
  51139. */
  51140. get: function () {
  51141. return Animation._ANIMATIONTYPE_COLOR3;
  51142. },
  51143. enumerable: true,
  51144. configurable: true
  51145. });
  51146. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  51147. /**
  51148. * Get the Relative Loop Mode
  51149. */
  51150. get: function () {
  51151. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  51152. },
  51153. enumerable: true,
  51154. configurable: true
  51155. });
  51156. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  51157. /**
  51158. * Get the Cycle Loop Mode
  51159. */
  51160. get: function () {
  51161. return Animation._ANIMATIONLOOPMODE_CYCLE;
  51162. },
  51163. enumerable: true,
  51164. configurable: true
  51165. });
  51166. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  51167. /**
  51168. * Get the Constant Loop Mode
  51169. */
  51170. get: function () {
  51171. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  51172. },
  51173. enumerable: true,
  51174. configurable: true
  51175. });
  51176. /** @hidden */
  51177. Animation._UniversalLerp = function (left, right, amount) {
  51178. var constructor = left.constructor;
  51179. if (constructor.Lerp) { // Lerp supported
  51180. return constructor.Lerp(left, right, amount);
  51181. }
  51182. else if (constructor.Slerp) { // Slerp supported
  51183. return constructor.Slerp(left, right, amount);
  51184. }
  51185. else if (left.toFixed) { // Number
  51186. return left * (1.0 - amount) + amount * right;
  51187. }
  51188. else { // Blending not supported
  51189. return right;
  51190. }
  51191. };
  51192. /**
  51193. * Parses an animation object and creates an animation
  51194. * @param parsedAnimation Parsed animation object
  51195. * @returns Animation object
  51196. */
  51197. Animation.Parse = function (parsedAnimation) {
  51198. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  51199. var dataType = parsedAnimation.dataType;
  51200. var keys = [];
  51201. var data;
  51202. var index;
  51203. if (parsedAnimation.enableBlending) {
  51204. animation.enableBlending = parsedAnimation.enableBlending;
  51205. }
  51206. if (parsedAnimation.blendingSpeed) {
  51207. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  51208. }
  51209. for (index = 0; index < parsedAnimation.keys.length; index++) {
  51210. var key = parsedAnimation.keys[index];
  51211. var inTangent;
  51212. var outTangent;
  51213. switch (dataType) {
  51214. case Animation.ANIMATIONTYPE_FLOAT:
  51215. data = key.values[0];
  51216. if (key.values.length >= 1) {
  51217. inTangent = key.values[1];
  51218. }
  51219. if (key.values.length >= 2) {
  51220. outTangent = key.values[2];
  51221. }
  51222. break;
  51223. case Animation.ANIMATIONTYPE_QUATERNION:
  51224. data = BABYLON.Quaternion.FromArray(key.values);
  51225. if (key.values.length >= 8) {
  51226. var _inTangent = BABYLON.Quaternion.FromArray(key.values.slice(4, 8));
  51227. if (!_inTangent.equals(BABYLON.Quaternion.Zero())) {
  51228. inTangent = _inTangent;
  51229. }
  51230. }
  51231. if (key.values.length >= 12) {
  51232. var _outTangent = BABYLON.Quaternion.FromArray(key.values.slice(8, 12));
  51233. if (!_outTangent.equals(BABYLON.Quaternion.Zero())) {
  51234. outTangent = _outTangent;
  51235. }
  51236. }
  51237. break;
  51238. case Animation.ANIMATIONTYPE_MATRIX:
  51239. data = BABYLON.Matrix.FromArray(key.values);
  51240. break;
  51241. case Animation.ANIMATIONTYPE_COLOR3:
  51242. data = BABYLON.Color3.FromArray(key.values);
  51243. break;
  51244. case Animation.ANIMATIONTYPE_VECTOR3:
  51245. default:
  51246. data = BABYLON.Vector3.FromArray(key.values);
  51247. break;
  51248. }
  51249. var keyData = {};
  51250. keyData.frame = key.frame;
  51251. keyData.value = data;
  51252. if (inTangent != undefined) {
  51253. keyData.inTangent = inTangent;
  51254. }
  51255. if (outTangent != undefined) {
  51256. keyData.outTangent = outTangent;
  51257. }
  51258. keys.push(keyData);
  51259. }
  51260. animation.setKeys(keys);
  51261. if (parsedAnimation.ranges) {
  51262. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  51263. data = parsedAnimation.ranges[index];
  51264. animation.createRange(data.name, data.from, data.to);
  51265. }
  51266. }
  51267. return animation;
  51268. };
  51269. /**
  51270. * Appends the serialized animations from the source animations
  51271. * @param source Source containing the animations
  51272. * @param destination Target to store the animations
  51273. */
  51274. Animation.AppendSerializedAnimations = function (source, destination) {
  51275. if (source.animations) {
  51276. destination.animations = [];
  51277. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  51278. var animation = source.animations[animationIndex];
  51279. destination.animations.push(animation.serialize());
  51280. }
  51281. }
  51282. };
  51283. /**
  51284. * Use matrix interpolation instead of using direct key value when animating matrices
  51285. */
  51286. Animation.AllowMatricesInterpolation = false;
  51287. /**
  51288. * When matrix interpolation is enabled, this boolean forces the system to use Matrix.DecomposeLerp instead of Matrix.Lerp. Interpolation is more precise but slower
  51289. */
  51290. Animation.AllowMatrixDecomposeForInterpolation = true;
  51291. // Statics
  51292. /**
  51293. * Float animation type
  51294. */
  51295. Animation._ANIMATIONTYPE_FLOAT = 0;
  51296. /**
  51297. * Vector3 animation type
  51298. */
  51299. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  51300. /**
  51301. * Quaternion animation type
  51302. */
  51303. Animation._ANIMATIONTYPE_QUATERNION = 2;
  51304. /**
  51305. * Matrix animation type
  51306. */
  51307. Animation._ANIMATIONTYPE_MATRIX = 3;
  51308. /**
  51309. * Color3 animation type
  51310. */
  51311. Animation._ANIMATIONTYPE_COLOR3 = 4;
  51312. /**
  51313. * Vector2 animation type
  51314. */
  51315. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  51316. /**
  51317. * Size animation type
  51318. */
  51319. Animation._ANIMATIONTYPE_SIZE = 6;
  51320. /**
  51321. * Relative Loop Mode
  51322. */
  51323. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  51324. /**
  51325. * Cycle Loop Mode
  51326. */
  51327. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  51328. /**
  51329. * Constant Loop Mode
  51330. */
  51331. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  51332. return Animation;
  51333. }());
  51334. BABYLON.Animation = Animation;
  51335. })(BABYLON || (BABYLON = {}));
  51336. //# sourceMappingURL=babylon.animation.js.map
  51337. var BABYLON;
  51338. (function (BABYLON) {
  51339. /**
  51340. * This class defines the direct association between an animation and a target
  51341. */
  51342. var TargetedAnimation = /** @class */ (function () {
  51343. function TargetedAnimation() {
  51344. }
  51345. return TargetedAnimation;
  51346. }());
  51347. BABYLON.TargetedAnimation = TargetedAnimation;
  51348. /**
  51349. * Use this class to create coordinated animations on multiple targets
  51350. */
  51351. var AnimationGroup = /** @class */ (function () {
  51352. /**
  51353. * Instantiates a new Animation Group.
  51354. * This helps managing several animations at once.
  51355. * @see http://doc.babylonjs.com/how_to/group
  51356. * @param name Defines the name of the group
  51357. * @param scene Defines the scene the group belongs to
  51358. */
  51359. function AnimationGroup(
  51360. /** The name of the animation group */
  51361. name, scene) {
  51362. if (scene === void 0) { scene = null; }
  51363. this.name = name;
  51364. this._targetedAnimations = new Array();
  51365. this._animatables = new Array();
  51366. this._from = Number.MAX_VALUE;
  51367. this._to = -Number.MAX_VALUE;
  51368. this._speedRatio = 1;
  51369. /**
  51370. * This observable will notify when one animation have ended.
  51371. */
  51372. this.onAnimationEndObservable = new BABYLON.Observable();
  51373. /**
  51374. * This observable will notify when all animations have ended.
  51375. */
  51376. this.onAnimationGroupEndObservable = new BABYLON.Observable();
  51377. /**
  51378. * This observable will notify when all animations have paused.
  51379. */
  51380. this.onAnimationGroupPauseObservable = new BABYLON.Observable();
  51381. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  51382. this._scene.animationGroups.push(this);
  51383. }
  51384. Object.defineProperty(AnimationGroup.prototype, "from", {
  51385. /**
  51386. * Gets the first frame
  51387. */
  51388. get: function () {
  51389. return this._from;
  51390. },
  51391. enumerable: true,
  51392. configurable: true
  51393. });
  51394. Object.defineProperty(AnimationGroup.prototype, "to", {
  51395. /**
  51396. * Gets the last frame
  51397. */
  51398. get: function () {
  51399. return this._to;
  51400. },
  51401. enumerable: true,
  51402. configurable: true
  51403. });
  51404. Object.defineProperty(AnimationGroup.prototype, "isStarted", {
  51405. /**
  51406. * Define if the animations are started
  51407. */
  51408. get: function () {
  51409. return this._isStarted;
  51410. },
  51411. enumerable: true,
  51412. configurable: true
  51413. });
  51414. Object.defineProperty(AnimationGroup.prototype, "speedRatio", {
  51415. /**
  51416. * Gets or sets the speed ratio to use for all animations
  51417. */
  51418. get: function () {
  51419. return this._speedRatio;
  51420. },
  51421. /**
  51422. * Gets or sets the speed ratio to use for all animations
  51423. */
  51424. set: function (value) {
  51425. if (this._speedRatio === value) {
  51426. return;
  51427. }
  51428. this._speedRatio = value;
  51429. for (var index = 0; index < this._animatables.length; index++) {
  51430. var animatable = this._animatables[index];
  51431. animatable.speedRatio = this._speedRatio;
  51432. }
  51433. },
  51434. enumerable: true,
  51435. configurable: true
  51436. });
  51437. Object.defineProperty(AnimationGroup.prototype, "targetedAnimations", {
  51438. /**
  51439. * Gets the targeted animations for this animation group
  51440. */
  51441. get: function () {
  51442. return this._targetedAnimations;
  51443. },
  51444. enumerable: true,
  51445. configurable: true
  51446. });
  51447. Object.defineProperty(AnimationGroup.prototype, "animatables", {
  51448. /**
  51449. * returning the list of animatables controlled by this animation group.
  51450. */
  51451. get: function () {
  51452. return this._animatables;
  51453. },
  51454. enumerable: true,
  51455. configurable: true
  51456. });
  51457. /**
  51458. * Add an animation (with its target) in the group
  51459. * @param animation defines the animation we want to add
  51460. * @param target defines the target of the animation
  51461. * @returns the {BABYLON.TargetedAnimation} object
  51462. */
  51463. AnimationGroup.prototype.addTargetedAnimation = function (animation, target) {
  51464. var targetedAnimation = {
  51465. animation: animation,
  51466. target: target
  51467. };
  51468. var keys = animation.getKeys();
  51469. if (this._from > keys[0].frame) {
  51470. this._from = keys[0].frame;
  51471. }
  51472. if (this._to < keys[keys.length - 1].frame) {
  51473. this._to = keys[keys.length - 1].frame;
  51474. }
  51475. this._targetedAnimations.push(targetedAnimation);
  51476. return targetedAnimation;
  51477. };
  51478. /**
  51479. * This function will normalize every animation in the group to make sure they all go from beginFrame to endFrame
  51480. * It can add constant keys at begin or end
  51481. * @param beginFrame defines the new begin frame for all animations or the smallest begin frame of all animations if null (defaults to null)
  51482. * @param endFrame defines the new end frame for all animations or the largest end frame of all animations if null (defaults to null)
  51483. * @returns the animation group
  51484. */
  51485. AnimationGroup.prototype.normalize = function (beginFrame, endFrame) {
  51486. if (beginFrame === void 0) { beginFrame = null; }
  51487. if (endFrame === void 0) { endFrame = null; }
  51488. if (beginFrame == null)
  51489. beginFrame = this._from;
  51490. if (endFrame == null)
  51491. endFrame = this._to;
  51492. for (var index = 0; index < this._targetedAnimations.length; index++) {
  51493. var targetedAnimation = this._targetedAnimations[index];
  51494. var keys = targetedAnimation.animation.getKeys();
  51495. var startKey = keys[0];
  51496. var endKey = keys[keys.length - 1];
  51497. if (startKey.frame > beginFrame) {
  51498. var newKey = {
  51499. frame: beginFrame,
  51500. value: startKey.value,
  51501. inTangent: startKey.inTangent,
  51502. outTangent: startKey.outTangent,
  51503. interpolation: startKey.interpolation
  51504. };
  51505. keys.splice(0, 0, newKey);
  51506. }
  51507. if (endKey.frame < endFrame) {
  51508. var newKey = {
  51509. frame: endFrame,
  51510. value: endKey.value,
  51511. inTangent: endKey.outTangent,
  51512. outTangent: endKey.outTangent,
  51513. interpolation: endKey.interpolation
  51514. };
  51515. keys.push(newKey);
  51516. }
  51517. }
  51518. this._from = beginFrame;
  51519. this._to = endFrame;
  51520. return this;
  51521. };
  51522. /**
  51523. * Start all animations on given targets
  51524. * @param loop defines if animations must loop
  51525. * @param speedRatio defines the ratio to apply to animation speed (1 by default)
  51526. * @param from defines the from key (optional)
  51527. * @param to defines the to key (optional)
  51528. * @returns the current animation group
  51529. */
  51530. AnimationGroup.prototype.start = function (loop, speedRatio, from, to) {
  51531. var _this = this;
  51532. if (loop === void 0) { loop = false; }
  51533. if (speedRatio === void 0) { speedRatio = 1; }
  51534. if (this._isStarted || this._targetedAnimations.length === 0) {
  51535. return this;
  51536. }
  51537. var _loop_1 = function (targetedAnimation) {
  51538. var animatable = this_1._scene.beginDirectAnimation(targetedAnimation.target, [targetedAnimation.animation], from !== undefined ? from : this_1._from, to !== undefined ? to : this_1._to, loop, speedRatio);
  51539. animatable.onAnimationEnd = function () {
  51540. _this.onAnimationEndObservable.notifyObservers(targetedAnimation);
  51541. _this._checkAnimationGroupEnded(animatable);
  51542. };
  51543. this_1._animatables.push(animatable);
  51544. };
  51545. var this_1 = this;
  51546. for (var _i = 0, _a = this._targetedAnimations; _i < _a.length; _i++) {
  51547. var targetedAnimation = _a[_i];
  51548. _loop_1(targetedAnimation);
  51549. }
  51550. this._speedRatio = speedRatio;
  51551. this._isStarted = true;
  51552. return this;
  51553. };
  51554. /**
  51555. * Pause all animations
  51556. * @returns the animation group
  51557. */
  51558. AnimationGroup.prototype.pause = function () {
  51559. if (!this._isStarted) {
  51560. return this;
  51561. }
  51562. for (var index = 0; index < this._animatables.length; index++) {
  51563. var animatable = this._animatables[index];
  51564. animatable.pause();
  51565. }
  51566. this.onAnimationGroupPauseObservable.notifyObservers(this);
  51567. return this;
  51568. };
  51569. /**
  51570. * Play all animations to initial state
  51571. * This function will start() the animations if they were not started or will restart() them if they were paused
  51572. * @param loop defines if animations must loop
  51573. * @returns the animation group
  51574. */
  51575. AnimationGroup.prototype.play = function (loop) {
  51576. // only if all animatables are ready and exist
  51577. if (this.isStarted && this._animatables.length === this._targetedAnimations.length) {
  51578. if (loop !== undefined) {
  51579. for (var index = 0; index < this._animatables.length; index++) {
  51580. var animatable = this._animatables[index];
  51581. animatable.loopAnimation = loop;
  51582. }
  51583. }
  51584. this.restart();
  51585. }
  51586. else {
  51587. this.stop();
  51588. this.start(loop, this._speedRatio);
  51589. }
  51590. return this;
  51591. };
  51592. /**
  51593. * Reset all animations to initial state
  51594. * @returns the animation group
  51595. */
  51596. AnimationGroup.prototype.reset = function () {
  51597. if (!this._isStarted) {
  51598. return this;
  51599. }
  51600. for (var index = 0; index < this._animatables.length; index++) {
  51601. var animatable = this._animatables[index];
  51602. animatable.reset();
  51603. }
  51604. return this;
  51605. };
  51606. /**
  51607. * Restart animations from key 0
  51608. * @returns the animation group
  51609. */
  51610. AnimationGroup.prototype.restart = function () {
  51611. if (!this._isStarted) {
  51612. return this;
  51613. }
  51614. for (var index = 0; index < this._animatables.length; index++) {
  51615. var animatable = this._animatables[index];
  51616. animatable.restart();
  51617. }
  51618. return this;
  51619. };
  51620. /**
  51621. * Stop all animations
  51622. * @returns the animation group
  51623. */
  51624. AnimationGroup.prototype.stop = function () {
  51625. if (!this._isStarted) {
  51626. return this;
  51627. }
  51628. var list = this._animatables.slice();
  51629. for (var index = 0; index < list.length; index++) {
  51630. list[index].stop();
  51631. }
  51632. this._isStarted = false;
  51633. return this;
  51634. };
  51635. /**
  51636. * Set animation weight for all animatables
  51637. * @param weight defines the weight to use
  51638. * @return the animationGroup
  51639. * @see http://doc.babylonjs.com/babylon101/animations#animation-weights
  51640. */
  51641. AnimationGroup.prototype.setWeightForAllAnimatables = function (weight) {
  51642. for (var index = 0; index < this._animatables.length; index++) {
  51643. var animatable = this._animatables[index];
  51644. animatable.weight = weight;
  51645. }
  51646. return this;
  51647. };
  51648. /**
  51649. * Synchronize and normalize all animatables with a source animatable
  51650. * @param root defines the root animatable to synchronize with
  51651. * @return the animationGroup
  51652. * @see http://doc.babylonjs.com/babylon101/animations#animation-weights
  51653. */
  51654. AnimationGroup.prototype.syncAllAnimationsWith = function (root) {
  51655. for (var index = 0; index < this._animatables.length; index++) {
  51656. var animatable = this._animatables[index];
  51657. animatable.syncWith(root);
  51658. }
  51659. return this;
  51660. };
  51661. /**
  51662. * Goes to a specific frame in this animation group
  51663. * @param frame the frame number to go to
  51664. * @return the animationGroup
  51665. */
  51666. AnimationGroup.prototype.goToFrame = function (frame) {
  51667. if (!this._isStarted) {
  51668. return this;
  51669. }
  51670. for (var index = 0; index < this._animatables.length; index++) {
  51671. var animatable = this._animatables[index];
  51672. animatable.goToFrame(frame);
  51673. }
  51674. return this;
  51675. };
  51676. /**
  51677. * Dispose all associated resources
  51678. */
  51679. AnimationGroup.prototype.dispose = function () {
  51680. this._targetedAnimations = [];
  51681. this._animatables = [];
  51682. var index = this._scene.animationGroups.indexOf(this);
  51683. if (index > -1) {
  51684. this._scene.animationGroups.splice(index, 1);
  51685. }
  51686. };
  51687. AnimationGroup.prototype._checkAnimationGroupEnded = function (animatable) {
  51688. // animatable should be taken out of the array
  51689. var idx = this._animatables.indexOf(animatable);
  51690. if (idx > -1) {
  51691. this._animatables.splice(idx, 1);
  51692. }
  51693. // all animatables were removed? animation group ended!
  51694. if (this._animatables.length === 0) {
  51695. this._isStarted = false;
  51696. this.onAnimationGroupEndObservable.notifyObservers(this);
  51697. }
  51698. };
  51699. // Statics
  51700. /**
  51701. * Returns a new AnimationGroup object parsed from the source provided.
  51702. * @param parsedAnimationGroup defines the source
  51703. * @param scene defines the scene that will receive the animationGroup
  51704. * @returns a new AnimationGroup
  51705. */
  51706. AnimationGroup.Parse = function (parsedAnimationGroup, scene) {
  51707. var animationGroup = new BABYLON.AnimationGroup(parsedAnimationGroup.name, scene);
  51708. for (var i = 0; i < parsedAnimationGroup.targetedAnimations.length; i++) {
  51709. var targetedAnimation = parsedAnimationGroup.targetedAnimations[i];
  51710. var animation = BABYLON.Animation.Parse(targetedAnimation.animation);
  51711. var id = targetedAnimation.targetId;
  51712. var targetNode = scene.getNodeByID(id);
  51713. if (targetNode != null)
  51714. animationGroup.addTargetedAnimation(animation, targetNode);
  51715. }
  51716. if (parsedAnimationGroup.from !== null && parsedAnimationGroup.from !== null)
  51717. animationGroup.normalize(parsedAnimationGroup.from, parsedAnimationGroup.to);
  51718. return animationGroup;
  51719. };
  51720. /**
  51721. * Returns the string "AnimationGroup"
  51722. * @returns "AnimationGroup"
  51723. */
  51724. AnimationGroup.prototype.getClassName = function () {
  51725. return "AnimationGroup";
  51726. };
  51727. /**
  51728. * Creates a detailled string about the object
  51729. * @param fullDetails defines if the output string will support multiple levels of logging within scene loading
  51730. * @returns a string representing the object
  51731. */
  51732. AnimationGroup.prototype.toString = function (fullDetails) {
  51733. var ret = "Name: " + this.name;
  51734. ret += ", type: " + this.getClassName();
  51735. if (fullDetails) {
  51736. ret += ", from: " + this._from;
  51737. ret += ", to: " + this._to;
  51738. ret += ", isStarted: " + this._isStarted;
  51739. ret += ", speedRatio: " + this._speedRatio;
  51740. ret += ", targetedAnimations length: " + this._targetedAnimations.length;
  51741. ret += ", animatables length: " + this._animatables;
  51742. }
  51743. return ret;
  51744. };
  51745. return AnimationGroup;
  51746. }());
  51747. BABYLON.AnimationGroup = AnimationGroup;
  51748. })(BABYLON || (BABYLON = {}));
  51749. //# sourceMappingURL=babylon.animationGroup.js.map
  51750. var BABYLON;
  51751. (function (BABYLON) {
  51752. // Static values to help the garbage collector
  51753. // Quaternion
  51754. var _staticOffsetValueQuaternion = Object.freeze(new BABYLON.Quaternion(0, 0, 0, 0));
  51755. // Vector3
  51756. var _staticOffsetValueVector3 = Object.freeze(BABYLON.Vector3.Zero());
  51757. // Vector2
  51758. var _staticOffsetValueVector2 = Object.freeze(BABYLON.Vector2.Zero());
  51759. // Size
  51760. var _staticOffsetValueSize = Object.freeze(BABYLON.Size.Zero());
  51761. // Color3
  51762. var _staticOffsetValueColor3 = Object.freeze(BABYLON.Color3.Black());
  51763. /**
  51764. * Defines a runtime animation
  51765. */
  51766. var RuntimeAnimation = /** @class */ (function () {
  51767. /**
  51768. * Create a new RuntimeAnimation object
  51769. * @param target defines the target of the animation
  51770. * @param animation defines the source animation object
  51771. * @param scene defines the hosting scene
  51772. * @param host defines the initiating Animatable
  51773. */
  51774. function RuntimeAnimation(target, animation, scene, host) {
  51775. var _this = this;
  51776. this._events = new Array();
  51777. /**
  51778. * The current frame of the runtime animation
  51779. */
  51780. this._currentFrame = 0;
  51781. /**
  51782. * The original value of the runtime animation
  51783. */
  51784. this._originalValue = new Array();
  51785. /**
  51786. * The offsets cache of the runtime animation
  51787. */
  51788. this._offsetsCache = {};
  51789. /**
  51790. * The high limits cache of the runtime animation
  51791. */
  51792. this._highLimitsCache = {};
  51793. /**
  51794. * Specifies if the runtime animation has been stopped
  51795. */
  51796. this._stopped = false;
  51797. /**
  51798. * The blending factor of the runtime animation
  51799. */
  51800. this._blendingFactor = 0;
  51801. /**
  51802. * The target path of the runtime animation
  51803. */
  51804. this._targetPath = "";
  51805. /**
  51806. * The weight of the runtime animation
  51807. */
  51808. this._weight = 1.0;
  51809. /**
  51810. * The ratio offset of the runtime animation
  51811. */
  51812. this._ratioOffset = 0;
  51813. /**
  51814. * The previous delay of the runtime animation
  51815. */
  51816. this._previousDelay = 0;
  51817. /**
  51818. * The previous ratio of the runtime animation
  51819. */
  51820. this._previousRatio = 0;
  51821. this._animation = animation;
  51822. this._target = target;
  51823. this._scene = scene;
  51824. this._host = host;
  51825. animation._runtimeAnimations.push(this);
  51826. // Cloning events locally
  51827. var events = animation.getEvents();
  51828. if (events && events.length > 0) {
  51829. events.forEach(function (e) {
  51830. _this._events.push(e._clone());
  51831. });
  51832. }
  51833. }
  51834. Object.defineProperty(RuntimeAnimation.prototype, "currentFrame", {
  51835. /**
  51836. * Gets the current frame of the runtime animation
  51837. */
  51838. get: function () {
  51839. return this._currentFrame;
  51840. },
  51841. enumerable: true,
  51842. configurable: true
  51843. });
  51844. Object.defineProperty(RuntimeAnimation.prototype, "weight", {
  51845. /**
  51846. * Gets the weight of the runtime animation
  51847. */
  51848. get: function () {
  51849. return this._weight;
  51850. },
  51851. enumerable: true,
  51852. configurable: true
  51853. });
  51854. Object.defineProperty(RuntimeAnimation.prototype, "currentValue", {
  51855. /**
  51856. * Gets the current value of the runtime animation
  51857. */
  51858. get: function () {
  51859. return this._currentValue;
  51860. },
  51861. enumerable: true,
  51862. configurable: true
  51863. });
  51864. Object.defineProperty(RuntimeAnimation.prototype, "targetPath", {
  51865. /**
  51866. * Gets the target path of the runtime animation
  51867. */
  51868. get: function () {
  51869. return this._targetPath;
  51870. },
  51871. enumerable: true,
  51872. configurable: true
  51873. });
  51874. Object.defineProperty(RuntimeAnimation.prototype, "target", {
  51875. /**
  51876. * Gets the actual target of the runtime animation
  51877. */
  51878. get: function () {
  51879. return this._activeTarget;
  51880. },
  51881. enumerable: true,
  51882. configurable: true
  51883. });
  51884. Object.defineProperty(RuntimeAnimation.prototype, "animation", {
  51885. /**
  51886. * Gets the animation from the runtime animation
  51887. */
  51888. get: function () {
  51889. return this._animation;
  51890. },
  51891. enumerable: true,
  51892. configurable: true
  51893. });
  51894. /**
  51895. * Resets the runtime animation to the beginning
  51896. * @param restoreOriginal defines whether to restore the target property to the original value
  51897. */
  51898. RuntimeAnimation.prototype.reset = function (restoreOriginal) {
  51899. if (restoreOriginal === void 0) { restoreOriginal = false; }
  51900. if (restoreOriginal) {
  51901. if (this._target instanceof Array) {
  51902. var index = 0;
  51903. for (var _i = 0, _a = this._target; _i < _a.length; _i++) {
  51904. var target = _a[_i];
  51905. if (this._originalValue[index] !== undefined) {
  51906. this._setValue(target, this._originalValue[index], -1);
  51907. }
  51908. index++;
  51909. }
  51910. }
  51911. else {
  51912. if (this._originalValue[0] !== undefined) {
  51913. this._setValue(this._target, this._originalValue[0], -1);
  51914. }
  51915. }
  51916. }
  51917. this._offsetsCache = {};
  51918. this._highLimitsCache = {};
  51919. this._currentFrame = 0;
  51920. this._blendingFactor = 0;
  51921. this._originalValue = new Array();
  51922. // Events
  51923. for (var index = 0; index < this._events.length; index++) {
  51924. this._events[index].isDone = false;
  51925. }
  51926. };
  51927. /**
  51928. * Specifies if the runtime animation is stopped
  51929. * @returns Boolean specifying if the runtime animation is stopped
  51930. */
  51931. RuntimeAnimation.prototype.isStopped = function () {
  51932. return this._stopped;
  51933. };
  51934. /**
  51935. * Disposes of the runtime animation
  51936. */
  51937. RuntimeAnimation.prototype.dispose = function () {
  51938. var index = this._animation.runtimeAnimations.indexOf(this);
  51939. if (index > -1) {
  51940. this._animation.runtimeAnimations.splice(index, 1);
  51941. }
  51942. };
  51943. /**
  51944. * Interpolates the animation from the current frame
  51945. * @param currentFrame The frame to interpolate the animation to
  51946. * @param repeatCount The number of times that the animation should loop
  51947. * @param loopMode The type of looping mode to use
  51948. * @param offsetValue Animation offset value
  51949. * @param highLimitValue The high limit value
  51950. * @returns The interpolated value
  51951. */
  51952. RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  51953. this._currentFrame = currentFrame;
  51954. if (this._animation.dataType === BABYLON.Animation.ANIMATIONTYPE_MATRIX && !this._workValue) {
  51955. this._workValue = BABYLON.Matrix.Zero();
  51956. }
  51957. return this._animation._interpolate(currentFrame, repeatCount, this._workValue, loopMode, offsetValue, highLimitValue);
  51958. };
  51959. /**
  51960. * Apply the interpolated value to the target
  51961. * @param currentValue defines the value computed by the animation
  51962. * @param weight defines the weight to apply to this value (Defaults to 1.0)
  51963. */
  51964. RuntimeAnimation.prototype.setValue = function (currentValue, weight) {
  51965. if (weight === void 0) { weight = 1.0; }
  51966. if (this._target instanceof Array) {
  51967. var index = 0;
  51968. for (var _i = 0, _a = this._target; _i < _a.length; _i++) {
  51969. var target = _a[_i];
  51970. this._setValue(target, currentValue, weight, index);
  51971. index++;
  51972. }
  51973. }
  51974. else {
  51975. this._setValue(this._target, currentValue, weight);
  51976. }
  51977. };
  51978. RuntimeAnimation.prototype._setValue = function (target, currentValue, weight, targetIndex) {
  51979. if (targetIndex === void 0) { targetIndex = 0; }
  51980. // Set value
  51981. var path;
  51982. var destination;
  51983. var targetPropertyPath = this._animation.targetPropertyPath;
  51984. if (targetPropertyPath.length > 1) {
  51985. var property = target[targetPropertyPath[0]];
  51986. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  51987. property = property[targetPropertyPath[index]];
  51988. }
  51989. path = targetPropertyPath[targetPropertyPath.length - 1];
  51990. destination = property;
  51991. }
  51992. else {
  51993. path = targetPropertyPath[0];
  51994. destination = target;
  51995. }
  51996. this._targetPath = path;
  51997. this._activeTarget = destination;
  51998. this._weight = weight;
  51999. if (this._originalValue[targetIndex] === undefined) {
  52000. var originalValue = void 0;
  52001. if (destination.getRestPose && path === "_matrix") { // For bones
  52002. originalValue = destination.getRestPose();
  52003. }
  52004. else {
  52005. originalValue = destination[path];
  52006. }
  52007. if (originalValue && originalValue.clone) {
  52008. this._originalValue[targetIndex] = originalValue.clone();
  52009. }
  52010. else {
  52011. this._originalValue[targetIndex] = originalValue;
  52012. }
  52013. }
  52014. // Blending
  52015. var enableBlending = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.enableBlending : this._animation.enableBlending;
  52016. if (enableBlending && this._blendingFactor <= 1.0) {
  52017. if (!this._originalBlendValue) {
  52018. var originalValue = destination[path];
  52019. if (originalValue.clone) {
  52020. this._originalBlendValue = originalValue.clone();
  52021. }
  52022. else {
  52023. this._originalBlendValue = originalValue;
  52024. }
  52025. }
  52026. if (this._originalBlendValue.m) { // Matrix
  52027. if (BABYLON.Animation.AllowMatrixDecomposeForInterpolation) {
  52028. if (this._currentValue) {
  52029. BABYLON.Matrix.DecomposeLerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  52030. }
  52031. else {
  52032. this._currentValue = BABYLON.Matrix.DecomposeLerp(this._originalBlendValue, currentValue, this._blendingFactor);
  52033. }
  52034. }
  52035. else {
  52036. if (this._currentValue) {
  52037. BABYLON.Matrix.LerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  52038. }
  52039. else {
  52040. this._currentValue = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  52041. }
  52042. }
  52043. }
  52044. else {
  52045. this._currentValue = BABYLON.Animation._UniversalLerp(this._originalBlendValue, currentValue, this._blendingFactor);
  52046. }
  52047. var blendingSpeed = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.blendingSpeed : this._animation.blendingSpeed;
  52048. this._blendingFactor += blendingSpeed;
  52049. }
  52050. else {
  52051. this._currentValue = currentValue;
  52052. }
  52053. if (weight !== -1.0) {
  52054. this._scene._registerTargetForLateAnimationBinding(this, this._originalValue[targetIndex]);
  52055. }
  52056. else {
  52057. destination[path] = this._currentValue;
  52058. }
  52059. if (target.markAsDirty) {
  52060. target.markAsDirty(this._animation.targetProperty);
  52061. }
  52062. };
  52063. /**
  52064. * Gets the loop pmode of the runtime animation
  52065. * @returns Loop Mode
  52066. */
  52067. RuntimeAnimation.prototype._getCorrectLoopMode = function () {
  52068. if (this._target && this._target.animationPropertiesOverride) {
  52069. return this._target.animationPropertiesOverride.loopMode;
  52070. }
  52071. return this._animation.loopMode;
  52072. };
  52073. /**
  52074. * Move the current animation to a given frame
  52075. * @param frame defines the frame to move to
  52076. */
  52077. RuntimeAnimation.prototype.goToFrame = function (frame) {
  52078. var keys = this._animation.getKeys();
  52079. if (frame < keys[0].frame) {
  52080. frame = keys[0].frame;
  52081. }
  52082. else if (frame > keys[keys.length - 1].frame) {
  52083. frame = keys[keys.length - 1].frame;
  52084. }
  52085. var currentValue = this._interpolate(frame, 0, this._getCorrectLoopMode());
  52086. this.setValue(currentValue, -1);
  52087. };
  52088. /**
  52089. * @hidden Internal use only
  52090. */
  52091. RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {
  52092. var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  52093. this._ratioOffset = this._previousRatio - newRatio;
  52094. };
  52095. /**
  52096. * Execute the current animation
  52097. * @param delay defines the delay to add to the current frame
  52098. * @param from defines the lower bound of the animation range
  52099. * @param to defines the upper bound of the animation range
  52100. * @param loop defines if the current animation must loop
  52101. * @param speedRatio defines the current speed ratio
  52102. * @param weight defines the weight of the animation (default is -1 so no weight)
  52103. * @returns a boolean indicating if the animation is running
  52104. */
  52105. RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, weight) {
  52106. if (weight === void 0) { weight = -1.0; }
  52107. var targetPropertyPath = this._animation.targetPropertyPath;
  52108. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  52109. this._stopped = true;
  52110. return false;
  52111. }
  52112. var returnValue = true;
  52113. var keys = this._animation.getKeys();
  52114. // Adding a start key at frame 0 if missing
  52115. if (keys[0].frame !== 0) {
  52116. var newKey = { frame: 0, value: keys[0].value };
  52117. keys.splice(0, 0, newKey);
  52118. }
  52119. // Adding a duplicate key when there is only one key at frame zero
  52120. else if (keys.length === 1) {
  52121. var newKey = { frame: 0.001, value: keys[0].value };
  52122. keys.push(newKey);
  52123. }
  52124. // Check limits
  52125. if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
  52126. from = keys[0].frame;
  52127. }
  52128. if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
  52129. to = keys[keys.length - 1].frame;
  52130. }
  52131. //to and from cannot be the same key
  52132. if (from === to) {
  52133. if (from > keys[0].frame) {
  52134. from--;
  52135. }
  52136. else if (to < keys[keys.length - 1].frame) {
  52137. to++;
  52138. }
  52139. }
  52140. // Compute ratio
  52141. var range = to - from;
  52142. var offsetValue;
  52143. // ratio represents the frame delta between from and to
  52144. var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  52145. var highLimitValue = 0;
  52146. this._previousDelay = delay;
  52147. this._previousRatio = ratio;
  52148. if (((to > from && ratio >= range) || (from > to && ratio <= range)) && !loop) { // If we are out of range and not looping get back to caller
  52149. returnValue = false;
  52150. highLimitValue = this._animation._getKeyValue(keys[keys.length - 1].value);
  52151. }
  52152. else {
  52153. // Get max value if required
  52154. if (this._getCorrectLoopMode() !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {
  52155. var keyOffset = to.toString() + from.toString();
  52156. if (!this._offsetsCache[keyOffset]) {
  52157. var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  52158. var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  52159. switch (this._animation.dataType) {
  52160. // Float
  52161. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  52162. this._offsetsCache[keyOffset] = toValue - fromValue;
  52163. break;
  52164. // Quaternion
  52165. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  52166. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  52167. break;
  52168. // Vector3
  52169. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  52170. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  52171. // Vector2
  52172. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  52173. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  52174. // Size
  52175. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  52176. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  52177. // Color3
  52178. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  52179. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  52180. default:
  52181. break;
  52182. }
  52183. this._highLimitsCache[keyOffset] = toValue;
  52184. }
  52185. highLimitValue = this._highLimitsCache[keyOffset];
  52186. offsetValue = this._offsetsCache[keyOffset];
  52187. }
  52188. }
  52189. if (offsetValue === undefined) {
  52190. switch (this._animation.dataType) {
  52191. // Float
  52192. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  52193. offsetValue = 0;
  52194. break;
  52195. // Quaternion
  52196. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  52197. offsetValue = _staticOffsetValueQuaternion;
  52198. break;
  52199. // Vector3
  52200. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  52201. offsetValue = _staticOffsetValueVector3;
  52202. break;
  52203. // Vector2
  52204. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  52205. offsetValue = _staticOffsetValueVector2;
  52206. break;
  52207. // Size
  52208. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  52209. offsetValue = _staticOffsetValueSize;
  52210. break;
  52211. // Color3
  52212. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  52213. offsetValue = _staticOffsetValueColor3;
  52214. }
  52215. }
  52216. // Compute value
  52217. var repeatCount = (ratio / range) >> 0;
  52218. var currentFrame = returnValue ? from + ratio % range : to;
  52219. // Need to normalize?
  52220. if (this._host && this._host.syncRoot) {
  52221. var syncRoot = this._host.syncRoot;
  52222. var hostNormalizedFrame = (syncRoot.masterFrame - syncRoot.fromFrame) / (syncRoot.toFrame - syncRoot.fromFrame);
  52223. currentFrame = from + (to - from) * hostNormalizedFrame;
  52224. }
  52225. // Reset events if looping
  52226. var events = this._events;
  52227. if (range > 0 && this.currentFrame > currentFrame ||
  52228. range < 0 && this.currentFrame < currentFrame) {
  52229. // Need to reset animation events
  52230. for (var index = 0; index < events.length; index++) {
  52231. if (!events[index].onlyOnce) {
  52232. // reset event, the animation is looping
  52233. events[index].isDone = false;
  52234. }
  52235. }
  52236. }
  52237. var currentValue = this._interpolate(currentFrame, repeatCount, this._getCorrectLoopMode(), offsetValue, highLimitValue);
  52238. // Set value
  52239. this.setValue(currentValue, weight);
  52240. // Check events
  52241. for (var index = 0; index < events.length; index++) {
  52242. // Make sure current frame has passed event frame and that event frame is within the current range
  52243. // Also, handle both forward and reverse animations
  52244. if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  52245. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {
  52246. var event = events[index];
  52247. if (!event.isDone) {
  52248. // If event should be done only once, remove it.
  52249. if (event.onlyOnce) {
  52250. events.splice(index, 1);
  52251. index--;
  52252. }
  52253. event.isDone = true;
  52254. event.action(currentFrame);
  52255. } // Don't do anything if the event has already be done.
  52256. }
  52257. }
  52258. if (!returnValue) {
  52259. this._stopped = true;
  52260. }
  52261. return returnValue;
  52262. };
  52263. return RuntimeAnimation;
  52264. }());
  52265. BABYLON.RuntimeAnimation = RuntimeAnimation;
  52266. })(BABYLON || (BABYLON = {}));
  52267. //# sourceMappingURL=babylon.runtimeAnimation.js.map
  52268. var BABYLON;
  52269. (function (BABYLON) {
  52270. /**
  52271. * Class used to store an actual running animation
  52272. */
  52273. var Animatable = /** @class */ (function () {
  52274. /**
  52275. * Creates a new Animatable
  52276. * @param scene defines the hosting scene
  52277. * @param target defines the target object
  52278. * @param fromFrame defines the starting frame number (default is 0)
  52279. * @param toFrame defines the ending frame number (default is 100)
  52280. * @param loopAnimation defines if the animation must loop (default is false)
  52281. * @param speedRatio defines the factor to apply to animation speed (default is 1)
  52282. * @param onAnimationEnd defines a callback to call when animation ends if it is not looping
  52283. * @param animations defines a group of animation to add to the new Animatable
  52284. */
  52285. function Animatable(scene,
  52286. /** defines the target object */
  52287. target,
  52288. /** defines the starting frame number (default is 0) */
  52289. fromFrame,
  52290. /** defines the ending frame number (default is 100) */
  52291. toFrame,
  52292. /** defines if the animation must loop (default is false) */
  52293. loopAnimation, speedRatio,
  52294. /** defines a callback to call when animation ends if it is not looping */
  52295. onAnimationEnd, animations) {
  52296. if (fromFrame === void 0) { fromFrame = 0; }
  52297. if (toFrame === void 0) { toFrame = 100; }
  52298. if (loopAnimation === void 0) { loopAnimation = false; }
  52299. if (speedRatio === void 0) { speedRatio = 1.0; }
  52300. this.target = target;
  52301. this.fromFrame = fromFrame;
  52302. this.toFrame = toFrame;
  52303. this.loopAnimation = loopAnimation;
  52304. this.onAnimationEnd = onAnimationEnd;
  52305. this._localDelayOffset = null;
  52306. this._pausedDelay = null;
  52307. this._runtimeAnimations = new Array();
  52308. this._paused = false;
  52309. this._speedRatio = 1;
  52310. this._weight = -1.0;
  52311. /**
  52312. * Gets or sets a boolean indicating if the animatable must be disposed and removed at the end of the animation.
  52313. * This will only apply for non looping animation (default is true)
  52314. */
  52315. this.disposeOnEnd = true;
  52316. /**
  52317. * Gets a boolean indicating if the animation has started
  52318. */
  52319. this.animationStarted = false;
  52320. /**
  52321. * Observer raised when the animation ends
  52322. */
  52323. this.onAnimationEndObservable = new BABYLON.Observable();
  52324. this._scene = scene;
  52325. if (animations) {
  52326. this.appendAnimations(target, animations);
  52327. }
  52328. this._speedRatio = speedRatio;
  52329. scene._activeAnimatables.push(this);
  52330. }
  52331. Object.defineProperty(Animatable.prototype, "syncRoot", {
  52332. /**
  52333. * Gets the root Animatable used to synchronize and normalize animations
  52334. */
  52335. get: function () {
  52336. return this._syncRoot;
  52337. },
  52338. enumerable: true,
  52339. configurable: true
  52340. });
  52341. Object.defineProperty(Animatable.prototype, "masterFrame", {
  52342. /**
  52343. * Gets the current frame of the first RuntimeAnimation
  52344. * Used to synchronize Animatables
  52345. */
  52346. get: function () {
  52347. if (this._runtimeAnimations.length === 0) {
  52348. return 0;
  52349. }
  52350. return this._runtimeAnimations[0].currentFrame;
  52351. },
  52352. enumerable: true,
  52353. configurable: true
  52354. });
  52355. Object.defineProperty(Animatable.prototype, "weight", {
  52356. /**
  52357. * Gets or sets the animatable weight (-1.0 by default meaning not weighted)
  52358. */
  52359. get: function () {
  52360. return this._weight;
  52361. },
  52362. set: function (value) {
  52363. if (value === -1) { // -1 is ok and means no weight
  52364. this._weight = -1;
  52365. return;
  52366. }
  52367. // Else weight must be in [0, 1] range
  52368. this._weight = Math.min(Math.max(value, 0), 1.0);
  52369. },
  52370. enumerable: true,
  52371. configurable: true
  52372. });
  52373. Object.defineProperty(Animatable.prototype, "speedRatio", {
  52374. /**
  52375. * Gets or sets the speed ratio to apply to the animatable (1.0 by default)
  52376. */
  52377. get: function () {
  52378. return this._speedRatio;
  52379. },
  52380. set: function (value) {
  52381. for (var index = 0; index < this._runtimeAnimations.length; index++) {
  52382. var animation = this._runtimeAnimations[index];
  52383. animation._prepareForSpeedRatioChange(value);
  52384. }
  52385. this._speedRatio = value;
  52386. },
  52387. enumerable: true,
  52388. configurable: true
  52389. });
  52390. // Methods
  52391. /**
  52392. * Synchronize and normalize current Animatable with a source Animatable
  52393. * This is useful when using animation weights and when animations are not of the same length
  52394. * @param root defines the root Animatable to synchronize with
  52395. * @returns the current Animatable
  52396. */
  52397. Animatable.prototype.syncWith = function (root) {
  52398. this._syncRoot = root;
  52399. if (root) {
  52400. // Make sure this animatable will animate after the root
  52401. var index = this._scene._activeAnimatables.indexOf(this);
  52402. if (index > -1) {
  52403. this._scene._activeAnimatables.splice(index, 1);
  52404. this._scene._activeAnimatables.push(this);
  52405. }
  52406. }
  52407. return this;
  52408. };
  52409. /**
  52410. * Gets the list of runtime animations
  52411. * @returns an array of RuntimeAnimation
  52412. */
  52413. Animatable.prototype.getAnimations = function () {
  52414. return this._runtimeAnimations;
  52415. };
  52416. /**
  52417. * Adds more animations to the current animatable
  52418. * @param target defines the target of the animations
  52419. * @param animations defines the new animations to add
  52420. */
  52421. Animatable.prototype.appendAnimations = function (target, animations) {
  52422. for (var index = 0; index < animations.length; index++) {
  52423. var animation = animations[index];
  52424. this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation, this._scene, this));
  52425. }
  52426. };
  52427. /**
  52428. * Gets the source animation for a specific property
  52429. * @param property defines the propertyu to look for
  52430. * @returns null or the source animation for the given property
  52431. */
  52432. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  52433. var runtimeAnimations = this._runtimeAnimations;
  52434. for (var index = 0; index < runtimeAnimations.length; index++) {
  52435. if (runtimeAnimations[index].animation.targetProperty === property) {
  52436. return runtimeAnimations[index].animation;
  52437. }
  52438. }
  52439. return null;
  52440. };
  52441. /**
  52442. * Gets the runtime animation for a specific property
  52443. * @param property defines the propertyu to look for
  52444. * @returns null or the runtime animation for the given property
  52445. */
  52446. Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {
  52447. var runtimeAnimations = this._runtimeAnimations;
  52448. for (var index = 0; index < runtimeAnimations.length; index++) {
  52449. if (runtimeAnimations[index].animation.targetProperty === property) {
  52450. return runtimeAnimations[index];
  52451. }
  52452. }
  52453. return null;
  52454. };
  52455. /**
  52456. * Resets the animatable to its original state
  52457. */
  52458. Animatable.prototype.reset = function () {
  52459. var runtimeAnimations = this._runtimeAnimations;
  52460. for (var index = 0; index < runtimeAnimations.length; index++) {
  52461. runtimeAnimations[index].reset(true);
  52462. }
  52463. this._localDelayOffset = null;
  52464. this._pausedDelay = null;
  52465. };
  52466. /**
  52467. * Allows the animatable to blend with current running animations
  52468. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  52469. * @param blendingSpeed defines the blending speed to use
  52470. */
  52471. Animatable.prototype.enableBlending = function (blendingSpeed) {
  52472. var runtimeAnimations = this._runtimeAnimations;
  52473. for (var index = 0; index < runtimeAnimations.length; index++) {
  52474. runtimeAnimations[index].animation.enableBlending = true;
  52475. runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
  52476. }
  52477. };
  52478. /**
  52479. * Disable animation blending
  52480. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  52481. */
  52482. Animatable.prototype.disableBlending = function () {
  52483. var runtimeAnimations = this._runtimeAnimations;
  52484. for (var index = 0; index < runtimeAnimations.length; index++) {
  52485. runtimeAnimations[index].animation.enableBlending = false;
  52486. }
  52487. };
  52488. /**
  52489. * Jump directly to a given frame
  52490. * @param frame defines the frame to jump to
  52491. */
  52492. Animatable.prototype.goToFrame = function (frame) {
  52493. var runtimeAnimations = this._runtimeAnimations;
  52494. if (runtimeAnimations[0]) {
  52495. var fps = runtimeAnimations[0].animation.framePerSecond;
  52496. var currentFrame = runtimeAnimations[0].currentFrame;
  52497. var adjustTime = frame - currentFrame;
  52498. var delay = adjustTime * 1000 / (fps * this.speedRatio);
  52499. if (this._localDelayOffset === null) {
  52500. this._localDelayOffset = 0;
  52501. }
  52502. this._localDelayOffset -= delay;
  52503. }
  52504. for (var index = 0; index < runtimeAnimations.length; index++) {
  52505. runtimeAnimations[index].goToFrame(frame);
  52506. }
  52507. };
  52508. /**
  52509. * Pause the animation
  52510. */
  52511. Animatable.prototype.pause = function () {
  52512. if (this._paused) {
  52513. return;
  52514. }
  52515. this._paused = true;
  52516. };
  52517. /**
  52518. * Restart the animation
  52519. */
  52520. Animatable.prototype.restart = function () {
  52521. this._paused = false;
  52522. };
  52523. Animatable.prototype._raiseOnAnimationEnd = function () {
  52524. if (this.onAnimationEnd) {
  52525. this.onAnimationEnd();
  52526. }
  52527. this.onAnimationEndObservable.notifyObservers(this);
  52528. };
  52529. /**
  52530. * Stop and delete the current animation
  52531. * @param animationName defines a string used to only stop some of the runtime animations instead of all
  52532. * @param targetMask - a function that determines if the animation should be stopped based on its target (all animations will be stopped if both this and animationName are empty)
  52533. */
  52534. Animatable.prototype.stop = function (animationName, targetMask) {
  52535. if (animationName || targetMask) {
  52536. var idx = this._scene._activeAnimatables.indexOf(this);
  52537. if (idx > -1) {
  52538. var runtimeAnimations = this._runtimeAnimations;
  52539. for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
  52540. var runtimeAnimation = runtimeAnimations[index];
  52541. if (animationName && runtimeAnimation.animation.name != animationName) {
  52542. continue;
  52543. }
  52544. if (targetMask && !targetMask(runtimeAnimation.target)) {
  52545. continue;
  52546. }
  52547. runtimeAnimation.dispose();
  52548. runtimeAnimations.splice(index, 1);
  52549. }
  52550. if (runtimeAnimations.length == 0) {
  52551. this._scene._activeAnimatables.splice(idx, 1);
  52552. this._raiseOnAnimationEnd();
  52553. }
  52554. }
  52555. }
  52556. else {
  52557. var index = this._scene._activeAnimatables.indexOf(this);
  52558. if (index > -1) {
  52559. this._scene._activeAnimatables.splice(index, 1);
  52560. var runtimeAnimations = this._runtimeAnimations;
  52561. for (var index = 0; index < runtimeAnimations.length; index++) {
  52562. runtimeAnimations[index].dispose();
  52563. }
  52564. this._raiseOnAnimationEnd();
  52565. }
  52566. }
  52567. };
  52568. /**
  52569. * Wait asynchronously for the animation to end
  52570. * @returns a promise which will be fullfilled when the animation ends
  52571. */
  52572. Animatable.prototype.waitAsync = function () {
  52573. var _this = this;
  52574. return new Promise(function (resolve, reject) {
  52575. _this.onAnimationEndObservable.add(function () {
  52576. resolve(_this);
  52577. }, undefined, undefined, _this, true);
  52578. });
  52579. };
  52580. /** @hidden */
  52581. Animatable.prototype._animate = function (delay) {
  52582. if (this._paused) {
  52583. this.animationStarted = false;
  52584. if (this._pausedDelay === null) {
  52585. this._pausedDelay = delay;
  52586. }
  52587. return true;
  52588. }
  52589. if (this._localDelayOffset === null) {
  52590. this._localDelayOffset = delay;
  52591. this._pausedDelay = null;
  52592. }
  52593. else if (this._pausedDelay !== null) {
  52594. this._localDelayOffset += delay - this._pausedDelay;
  52595. this._pausedDelay = null;
  52596. }
  52597. if (this._weight === 0) { // We consider that an animation with a weight === 0 is "actively" paused
  52598. return true;
  52599. }
  52600. // Animating
  52601. var running = false;
  52602. var runtimeAnimations = this._runtimeAnimations;
  52603. var index;
  52604. for (index = 0; index < runtimeAnimations.length; index++) {
  52605. var animation = runtimeAnimations[index];
  52606. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio, this._weight);
  52607. running = running || isRunning;
  52608. }
  52609. this.animationStarted = running;
  52610. if (!running) {
  52611. if (this.disposeOnEnd) {
  52612. // Remove from active animatables
  52613. index = this._scene._activeAnimatables.indexOf(this);
  52614. this._scene._activeAnimatables.splice(index, 1);
  52615. // Dispose all runtime animations
  52616. for (index = 0; index < runtimeAnimations.length; index++) {
  52617. runtimeAnimations[index].dispose();
  52618. }
  52619. }
  52620. this._raiseOnAnimationEnd();
  52621. if (this.disposeOnEnd) {
  52622. this.onAnimationEnd = null;
  52623. this.onAnimationEndObservable.clear();
  52624. }
  52625. }
  52626. return running;
  52627. };
  52628. return Animatable;
  52629. }());
  52630. BABYLON.Animatable = Animatable;
  52631. })(BABYLON || (BABYLON = {}));
  52632. //# sourceMappingURL=babylon.animatable.js.map
  52633. var BABYLON;
  52634. (function (BABYLON) {
  52635. /**
  52636. * Base class used for every default easing function.
  52637. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  52638. */
  52639. var EasingFunction = /** @class */ (function () {
  52640. function EasingFunction() {
  52641. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  52642. }
  52643. /**
  52644. * Sets the easing mode of the current function.
  52645. * @param easingMode Defines the willing mode (EASINGMODE_EASEIN, EASINGMODE_EASEOUT or EASINGMODE_EASEINOUT)
  52646. */
  52647. EasingFunction.prototype.setEasingMode = function (easingMode) {
  52648. var n = Math.min(Math.max(easingMode, 0), 2);
  52649. this._easingMode = n;
  52650. };
  52651. /**
  52652. * Gets the current easing mode.
  52653. * @returns the easing mode
  52654. */
  52655. EasingFunction.prototype.getEasingMode = function () {
  52656. return this._easingMode;
  52657. };
  52658. /**
  52659. * @hidden
  52660. */
  52661. EasingFunction.prototype.easeInCore = function (gradient) {
  52662. throw new Error('You must implement this method');
  52663. };
  52664. /**
  52665. * Given an input gradient between 0 and 1, this returns the corrseponding value
  52666. * of the easing function.
  52667. * @param gradient Defines the value between 0 and 1 we want the easing value for
  52668. * @returns the corresponding value on the curve defined by the easing function
  52669. */
  52670. EasingFunction.prototype.ease = function (gradient) {
  52671. switch (this._easingMode) {
  52672. case EasingFunction.EASINGMODE_EASEIN:
  52673. return this.easeInCore(gradient);
  52674. case EasingFunction.EASINGMODE_EASEOUT:
  52675. return (1 - this.easeInCore(1 - gradient));
  52676. }
  52677. if (gradient >= 0.5) {
  52678. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  52679. }
  52680. return (this.easeInCore(gradient * 2) * 0.5);
  52681. };
  52682. /**
  52683. * Interpolation follows the mathematical formula associated with the easing function.
  52684. */
  52685. EasingFunction.EASINGMODE_EASEIN = 0;
  52686. /**
  52687. * Interpolation follows 100% interpolation minus the output of the formula associated with the easing function.
  52688. */
  52689. EasingFunction.EASINGMODE_EASEOUT = 1;
  52690. /**
  52691. * Interpolation uses EaseIn for the first half of the animation and EaseOut for the second half.
  52692. */
  52693. EasingFunction.EASINGMODE_EASEINOUT = 2;
  52694. return EasingFunction;
  52695. }());
  52696. BABYLON.EasingFunction = EasingFunction;
  52697. /**
  52698. * Easing function with a circle shape (see link below).
  52699. * @see https://easings.net/#easeInCirc
  52700. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  52701. */
  52702. var CircleEase = /** @class */ (function (_super) {
  52703. __extends(CircleEase, _super);
  52704. function CircleEase() {
  52705. return _super !== null && _super.apply(this, arguments) || this;
  52706. }
  52707. /** @hidden */
  52708. CircleEase.prototype.easeInCore = function (gradient) {
  52709. gradient = Math.max(0, Math.min(1, gradient));
  52710. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  52711. };
  52712. return CircleEase;
  52713. }(EasingFunction));
  52714. BABYLON.CircleEase = CircleEase;
  52715. /**
  52716. * Easing function with a ease back shape (see link below).
  52717. * @see https://easings.net/#easeInBack
  52718. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  52719. */
  52720. var BackEase = /** @class */ (function (_super) {
  52721. __extends(BackEase, _super);
  52722. /**
  52723. * Instantiates a back ease easing
  52724. * @see https://easings.net/#easeInBack
  52725. * @param amplitude Defines the amplitude of the function
  52726. */
  52727. function BackEase(
  52728. /** Defines the amplitude of the function */
  52729. amplitude) {
  52730. if (amplitude === void 0) { amplitude = 1; }
  52731. var _this = _super.call(this) || this;
  52732. _this.amplitude = amplitude;
  52733. return _this;
  52734. }
  52735. /** @hidden */
  52736. BackEase.prototype.easeInCore = function (gradient) {
  52737. var num = Math.max(0, this.amplitude);
  52738. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  52739. };
  52740. return BackEase;
  52741. }(EasingFunction));
  52742. BABYLON.BackEase = BackEase;
  52743. /**
  52744. * Easing function with a bouncing shape (see link below).
  52745. * @see https://easings.net/#easeInBounce
  52746. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  52747. */
  52748. var BounceEase = /** @class */ (function (_super) {
  52749. __extends(BounceEase, _super);
  52750. /**
  52751. * Instantiates a bounce easing
  52752. * @see https://easings.net/#easeInBounce
  52753. * @param bounces Defines the number of bounces
  52754. * @param bounciness Defines the amplitude of the bounce
  52755. */
  52756. function BounceEase(
  52757. /** Defines the number of bounces */
  52758. bounces,
  52759. /** Defines the amplitude of the bounce */
  52760. bounciness) {
  52761. if (bounces === void 0) { bounces = 3; }
  52762. if (bounciness === void 0) { bounciness = 2; }
  52763. var _this = _super.call(this) || this;
  52764. _this.bounces = bounces;
  52765. _this.bounciness = bounciness;
  52766. return _this;
  52767. }
  52768. /** @hidden */
  52769. BounceEase.prototype.easeInCore = function (gradient) {
  52770. var y = Math.max(0.0, this.bounces);
  52771. var bounciness = this.bounciness;
  52772. if (bounciness <= 1.0) {
  52773. bounciness = 1.001;
  52774. }
  52775. var num9 = Math.pow(bounciness, y);
  52776. var num5 = 1.0 - bounciness;
  52777. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  52778. var num15 = gradient * num4;
  52779. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  52780. var num3 = Math.floor(num65);
  52781. var num13 = num3 + 1.0;
  52782. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  52783. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  52784. var num7 = (num8 + num12) * 0.5;
  52785. var num6 = gradient - num7;
  52786. var num2 = num7 - num8;
  52787. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  52788. };
  52789. return BounceEase;
  52790. }(EasingFunction));
  52791. BABYLON.BounceEase = BounceEase;
  52792. /**
  52793. * Easing function with a power of 3 shape (see link below).
  52794. * @see https://easings.net/#easeInCubic
  52795. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  52796. */
  52797. var CubicEase = /** @class */ (function (_super) {
  52798. __extends(CubicEase, _super);
  52799. function CubicEase() {
  52800. return _super !== null && _super.apply(this, arguments) || this;
  52801. }
  52802. /** @hidden */
  52803. CubicEase.prototype.easeInCore = function (gradient) {
  52804. return (gradient * gradient * gradient);
  52805. };
  52806. return CubicEase;
  52807. }(EasingFunction));
  52808. BABYLON.CubicEase = CubicEase;
  52809. /**
  52810. * Easing function with an elastic shape (see link below).
  52811. * @see https://easings.net/#easeInElastic
  52812. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  52813. */
  52814. var ElasticEase = /** @class */ (function (_super) {
  52815. __extends(ElasticEase, _super);
  52816. /**
  52817. * Instantiates an elastic easing function
  52818. * @see https://easings.net/#easeInElastic
  52819. * @param oscillations Defines the number of oscillations
  52820. * @param springiness Defines the amplitude of the oscillations
  52821. */
  52822. function ElasticEase(
  52823. /** Defines the number of oscillations*/
  52824. oscillations,
  52825. /** Defines the amplitude of the oscillations*/
  52826. springiness) {
  52827. if (oscillations === void 0) { oscillations = 3; }
  52828. if (springiness === void 0) { springiness = 3; }
  52829. var _this = _super.call(this) || this;
  52830. _this.oscillations = oscillations;
  52831. _this.springiness = springiness;
  52832. return _this;
  52833. }
  52834. /** @hidden */
  52835. ElasticEase.prototype.easeInCore = function (gradient) {
  52836. var num2;
  52837. var num3 = Math.max(0.0, this.oscillations);
  52838. var num = Math.max(0.0, this.springiness);
  52839. if (num == 0) {
  52840. num2 = gradient;
  52841. }
  52842. else {
  52843. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  52844. }
  52845. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  52846. };
  52847. return ElasticEase;
  52848. }(EasingFunction));
  52849. BABYLON.ElasticEase = ElasticEase;
  52850. /**
  52851. * Easing function with an exponential shape (see link below).
  52852. * @see https://easings.net/#easeInExpo
  52853. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  52854. */
  52855. var ExponentialEase = /** @class */ (function (_super) {
  52856. __extends(ExponentialEase, _super);
  52857. /**
  52858. * Instantiates an exponential easing function
  52859. * @see https://easings.net/#easeInExpo
  52860. * @param exponent Defines the exponent of the function
  52861. */
  52862. function ExponentialEase(
  52863. /** Defines the exponent of the function */
  52864. exponent) {
  52865. if (exponent === void 0) { exponent = 2; }
  52866. var _this = _super.call(this) || this;
  52867. _this.exponent = exponent;
  52868. return _this;
  52869. }
  52870. /** @hidden */
  52871. ExponentialEase.prototype.easeInCore = function (gradient) {
  52872. if (this.exponent <= 0) {
  52873. return gradient;
  52874. }
  52875. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  52876. };
  52877. return ExponentialEase;
  52878. }(EasingFunction));
  52879. BABYLON.ExponentialEase = ExponentialEase;
  52880. /**
  52881. * Easing function with a power shape (see link below).
  52882. * @see https://easings.net/#easeInQuad
  52883. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  52884. */
  52885. var PowerEase = /** @class */ (function (_super) {
  52886. __extends(PowerEase, _super);
  52887. /**
  52888. * Instantiates an power base easing function
  52889. * @see https://easings.net/#easeInQuad
  52890. * @param power Defines the power of the function
  52891. */
  52892. function PowerEase(
  52893. /** Defines the power of the function */
  52894. power) {
  52895. if (power === void 0) { power = 2; }
  52896. var _this = _super.call(this) || this;
  52897. _this.power = power;
  52898. return _this;
  52899. }
  52900. /** @hidden */
  52901. PowerEase.prototype.easeInCore = function (gradient) {
  52902. var y = Math.max(0.0, this.power);
  52903. return Math.pow(gradient, y);
  52904. };
  52905. return PowerEase;
  52906. }(EasingFunction));
  52907. BABYLON.PowerEase = PowerEase;
  52908. /**
  52909. * Easing function with a power of 2 shape (see link below).
  52910. * @see https://easings.net/#easeInQuad
  52911. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  52912. */
  52913. var QuadraticEase = /** @class */ (function (_super) {
  52914. __extends(QuadraticEase, _super);
  52915. function QuadraticEase() {
  52916. return _super !== null && _super.apply(this, arguments) || this;
  52917. }
  52918. /** @hidden */
  52919. QuadraticEase.prototype.easeInCore = function (gradient) {
  52920. return (gradient * gradient);
  52921. };
  52922. return QuadraticEase;
  52923. }(EasingFunction));
  52924. BABYLON.QuadraticEase = QuadraticEase;
  52925. /**
  52926. * Easing function with a power of 4 shape (see link below).
  52927. * @see https://easings.net/#easeInQuart
  52928. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  52929. */
  52930. var QuarticEase = /** @class */ (function (_super) {
  52931. __extends(QuarticEase, _super);
  52932. function QuarticEase() {
  52933. return _super !== null && _super.apply(this, arguments) || this;
  52934. }
  52935. /** @hidden */
  52936. QuarticEase.prototype.easeInCore = function (gradient) {
  52937. return (gradient * gradient * gradient * gradient);
  52938. };
  52939. return QuarticEase;
  52940. }(EasingFunction));
  52941. BABYLON.QuarticEase = QuarticEase;
  52942. /**
  52943. * Easing function with a power of 5 shape (see link below).
  52944. * @see https://easings.net/#easeInQuint
  52945. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  52946. */
  52947. var QuinticEase = /** @class */ (function (_super) {
  52948. __extends(QuinticEase, _super);
  52949. function QuinticEase() {
  52950. return _super !== null && _super.apply(this, arguments) || this;
  52951. }
  52952. /** @hidden */
  52953. QuinticEase.prototype.easeInCore = function (gradient) {
  52954. return (gradient * gradient * gradient * gradient * gradient);
  52955. };
  52956. return QuinticEase;
  52957. }(EasingFunction));
  52958. BABYLON.QuinticEase = QuinticEase;
  52959. /**
  52960. * Easing function with a sin shape (see link below).
  52961. * @see https://easings.net/#easeInSine
  52962. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  52963. */
  52964. var SineEase = /** @class */ (function (_super) {
  52965. __extends(SineEase, _super);
  52966. function SineEase() {
  52967. return _super !== null && _super.apply(this, arguments) || this;
  52968. }
  52969. /** @hidden */
  52970. SineEase.prototype.easeInCore = function (gradient) {
  52971. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  52972. };
  52973. return SineEase;
  52974. }(EasingFunction));
  52975. BABYLON.SineEase = SineEase;
  52976. /**
  52977. * Easing function with a bezier shape (see link below).
  52978. * @see http://cubic-bezier.com/#.17,.67,.83,.67
  52979. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  52980. */
  52981. var BezierCurveEase = /** @class */ (function (_super) {
  52982. __extends(BezierCurveEase, _super);
  52983. /**
  52984. * Instantiates a bezier function
  52985. * @see http://cubic-bezier.com/#.17,.67,.83,.67
  52986. * @param x1 Defines the x component of the start tangent in the bezier curve
  52987. * @param y1 Defines the y component of the start tangent in the bezier curve
  52988. * @param x2 Defines the x component of the end tangent in the bezier curve
  52989. * @param y2 Defines the y component of the end tangent in the bezier curve
  52990. */
  52991. function BezierCurveEase(
  52992. /** Defines the x component of the start tangent in the bezier curve */
  52993. x1,
  52994. /** Defines the y component of the start tangent in the bezier curve */
  52995. y1,
  52996. /** Defines the x component of the end tangent in the bezier curve */
  52997. x2,
  52998. /** Defines the y component of the end tangent in the bezier curve */
  52999. y2) {
  53000. if (x1 === void 0) { x1 = 0; }
  53001. if (y1 === void 0) { y1 = 0; }
  53002. if (x2 === void 0) { x2 = 1; }
  53003. if (y2 === void 0) { y2 = 1; }
  53004. var _this = _super.call(this) || this;
  53005. _this.x1 = x1;
  53006. _this.y1 = y1;
  53007. _this.x2 = x2;
  53008. _this.y2 = y2;
  53009. return _this;
  53010. }
  53011. /** @hidden */
  53012. BezierCurveEase.prototype.easeInCore = function (gradient) {
  53013. return BABYLON.BezierCurve.Interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  53014. };
  53015. return BezierCurveEase;
  53016. }(EasingFunction));
  53017. BABYLON.BezierCurveEase = BezierCurveEase;
  53018. })(BABYLON || (BABYLON = {}));
  53019. //# sourceMappingURL=babylon.easing.js.map
  53020. var BABYLON;
  53021. (function (BABYLON) {
  53022. /**
  53023. * A Condition applied to an Action
  53024. */
  53025. var Condition = /** @class */ (function () {
  53026. /**
  53027. * Creates a new Condition
  53028. * @param actionManager the manager of the action the condition is applied to
  53029. */
  53030. function Condition(actionManager) {
  53031. this._actionManager = actionManager;
  53032. }
  53033. /**
  53034. * Check if the current condition is valid
  53035. * @returns a boolean
  53036. */
  53037. Condition.prototype.isValid = function () {
  53038. return true;
  53039. };
  53040. /**
  53041. * Internal only
  53042. * @hidden
  53043. */
  53044. Condition.prototype._getProperty = function (propertyPath) {
  53045. return this._actionManager._getProperty(propertyPath);
  53046. };
  53047. /**
  53048. * Internal only
  53049. * @hidden
  53050. */
  53051. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  53052. return this._actionManager._getEffectiveTarget(target, propertyPath);
  53053. };
  53054. /**
  53055. * Serialize placeholder for child classes
  53056. * @returns the serialized object
  53057. */
  53058. Condition.prototype.serialize = function () {
  53059. };
  53060. /**
  53061. * Internal only
  53062. * @hidden
  53063. */
  53064. Condition.prototype._serialize = function (serializedCondition) {
  53065. return {
  53066. type: 2,
  53067. children: [],
  53068. name: serializedCondition.name,
  53069. properties: serializedCondition.properties
  53070. };
  53071. };
  53072. return Condition;
  53073. }());
  53074. BABYLON.Condition = Condition;
  53075. /**
  53076. * Defines specific conditional operators as extensions of Condition
  53077. */
  53078. var ValueCondition = /** @class */ (function (_super) {
  53079. __extends(ValueCondition, _super);
  53080. /**
  53081. * Creates a new ValueCondition
  53082. * @param actionManager manager for the action the condition applies to
  53083. * @param target for the action
  53084. * @param propertyPath path to specify the property of the target the conditional operator uses
  53085. * @param value the value compared by the conditional operator against the current value of the property
  53086. * @param operator the conditional operator, default ValueCondition.IsEqual
  53087. */
  53088. function ValueCondition(actionManager, target,
  53089. /** path to specify the property of the target the conditional operator uses */
  53090. propertyPath,
  53091. /** the value compared by the conditional operator against the current value of the property */
  53092. value,
  53093. /** the conditional operator, default ValueCondition.IsEqual */
  53094. operator) {
  53095. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  53096. var _this = _super.call(this, actionManager) || this;
  53097. _this.propertyPath = propertyPath;
  53098. _this.value = value;
  53099. _this.operator = operator;
  53100. _this._target = target;
  53101. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  53102. _this._property = _this._getProperty(_this.propertyPath);
  53103. return _this;
  53104. }
  53105. Object.defineProperty(ValueCondition, "IsEqual", {
  53106. /**
  53107. * returns the number for IsEqual
  53108. */
  53109. get: function () {
  53110. return ValueCondition._IsEqual;
  53111. },
  53112. enumerable: true,
  53113. configurable: true
  53114. });
  53115. Object.defineProperty(ValueCondition, "IsDifferent", {
  53116. /**
  53117. * Returns the number for IsDifferent
  53118. */
  53119. get: function () {
  53120. return ValueCondition._IsDifferent;
  53121. },
  53122. enumerable: true,
  53123. configurable: true
  53124. });
  53125. Object.defineProperty(ValueCondition, "IsGreater", {
  53126. /**
  53127. * Returns the number for IsGreater
  53128. */
  53129. get: function () {
  53130. return ValueCondition._IsGreater;
  53131. },
  53132. enumerable: true,
  53133. configurable: true
  53134. });
  53135. Object.defineProperty(ValueCondition, "IsLesser", {
  53136. /**
  53137. * Returns the number for IsLesser
  53138. */
  53139. get: function () {
  53140. return ValueCondition._IsLesser;
  53141. },
  53142. enumerable: true,
  53143. configurable: true
  53144. });
  53145. /**
  53146. * Compares the given value with the property value for the specified conditional operator
  53147. * @returns the result of the comparison
  53148. */
  53149. ValueCondition.prototype.isValid = function () {
  53150. switch (this.operator) {
  53151. case ValueCondition.IsGreater:
  53152. return this._effectiveTarget[this._property] > this.value;
  53153. case ValueCondition.IsLesser:
  53154. return this._effectiveTarget[this._property] < this.value;
  53155. case ValueCondition.IsEqual:
  53156. case ValueCondition.IsDifferent:
  53157. var check;
  53158. if (this.value.equals) {
  53159. check = this.value.equals(this._effectiveTarget[this._property]);
  53160. }
  53161. else {
  53162. check = this.value === this._effectiveTarget[this._property];
  53163. }
  53164. return this.operator === ValueCondition.IsEqual ? check : !check;
  53165. }
  53166. return false;
  53167. };
  53168. /**
  53169. * Serialize the ValueCondition into a JSON compatible object
  53170. * @returns serialization object
  53171. */
  53172. ValueCondition.prototype.serialize = function () {
  53173. return this._serialize({
  53174. name: "ValueCondition",
  53175. properties: [
  53176. BABYLON.Action._GetTargetProperty(this._target),
  53177. { name: "propertyPath", value: this.propertyPath },
  53178. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  53179. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  53180. ]
  53181. });
  53182. };
  53183. /**
  53184. * Gets the name of the conditional operator for the ValueCondition
  53185. * @param operator the conditional operator
  53186. * @returns the name
  53187. */
  53188. ValueCondition.GetOperatorName = function (operator) {
  53189. switch (operator) {
  53190. case ValueCondition._IsEqual: return "IsEqual";
  53191. case ValueCondition._IsDifferent: return "IsDifferent";
  53192. case ValueCondition._IsGreater: return "IsGreater";
  53193. case ValueCondition._IsLesser: return "IsLesser";
  53194. default: return "";
  53195. }
  53196. };
  53197. /**
  53198. * Internal only
  53199. * @hidden
  53200. */
  53201. ValueCondition._IsEqual = 0;
  53202. /**
  53203. * Internal only
  53204. * @hidden
  53205. */
  53206. ValueCondition._IsDifferent = 1;
  53207. /**
  53208. * Internal only
  53209. * @hidden
  53210. */
  53211. ValueCondition._IsGreater = 2;
  53212. /**
  53213. * Internal only
  53214. * @hidden
  53215. */
  53216. ValueCondition._IsLesser = 3;
  53217. return ValueCondition;
  53218. }(Condition));
  53219. BABYLON.ValueCondition = ValueCondition;
  53220. /**
  53221. * Defines a predicate condition as an extension of Condition
  53222. */
  53223. var PredicateCondition = /** @class */ (function (_super) {
  53224. __extends(PredicateCondition, _super);
  53225. /**
  53226. * Creates a new PredicateCondition
  53227. * @param actionManager manager for the action the condition applies to
  53228. * @param predicate defines the predicate function used to validate the condition
  53229. */
  53230. function PredicateCondition(actionManager,
  53231. /** defines the predicate function used to validate the condition */
  53232. predicate) {
  53233. var _this = _super.call(this, actionManager) || this;
  53234. _this.predicate = predicate;
  53235. return _this;
  53236. }
  53237. /**
  53238. * @returns the validity of the predicate condition
  53239. */
  53240. PredicateCondition.prototype.isValid = function () {
  53241. return this.predicate();
  53242. };
  53243. return PredicateCondition;
  53244. }(Condition));
  53245. BABYLON.PredicateCondition = PredicateCondition;
  53246. /**
  53247. * Defines a state condition as an extension of Condition
  53248. */
  53249. var StateCondition = /** @class */ (function (_super) {
  53250. __extends(StateCondition, _super);
  53251. /**
  53252. * Creates a new StateCondition
  53253. * @param actionManager manager for the action the condition applies to
  53254. * @param target of the condition
  53255. * @param value to compare with target state
  53256. */
  53257. function StateCondition(actionManager, target, value) {
  53258. var _this = _super.call(this, actionManager) || this;
  53259. _this.value = value;
  53260. _this._target = target;
  53261. return _this;
  53262. }
  53263. /**
  53264. * @returns the validity of the state
  53265. */
  53266. StateCondition.prototype.isValid = function () {
  53267. return this._target.state === this.value;
  53268. };
  53269. /**
  53270. * Serialize the StateCondition into a JSON compatible object
  53271. * @returns serialization object
  53272. */
  53273. StateCondition.prototype.serialize = function () {
  53274. return this._serialize({
  53275. name: "StateCondition",
  53276. properties: [
  53277. BABYLON.Action._GetTargetProperty(this._target),
  53278. { name: "value", value: this.value }
  53279. ]
  53280. });
  53281. };
  53282. return StateCondition;
  53283. }(Condition));
  53284. BABYLON.StateCondition = StateCondition;
  53285. })(BABYLON || (BABYLON = {}));
  53286. //# sourceMappingURL=babylon.condition.js.map
  53287. var BABYLON;
  53288. (function (BABYLON) {
  53289. /**
  53290. * The action to be carried out following a trigger
  53291. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#available-actions
  53292. */
  53293. var Action = /** @class */ (function () {
  53294. /**
  53295. * Creates a new Action
  53296. * @param triggerOptions the trigger, with or without parameters, for the action
  53297. * @param condition an optional determinant of action
  53298. */
  53299. function Action(
  53300. /** the trigger, with or without parameters, for the action */
  53301. triggerOptions, condition) {
  53302. this.triggerOptions = triggerOptions;
  53303. /**
  53304. * An event triggered prior to action being executed.
  53305. */
  53306. this.onBeforeExecuteObservable = new BABYLON.Observable();
  53307. if (triggerOptions.parameter) {
  53308. this.trigger = triggerOptions.trigger;
  53309. this._triggerParameter = triggerOptions.parameter;
  53310. }
  53311. else if (triggerOptions.trigger) {
  53312. this.trigger = triggerOptions.trigger;
  53313. }
  53314. else {
  53315. this.trigger = triggerOptions;
  53316. }
  53317. this._nextActiveAction = this;
  53318. this._condition = condition;
  53319. }
  53320. /**
  53321. * Internal only
  53322. * @hidden
  53323. */
  53324. Action.prototype._prepare = function () {
  53325. };
  53326. /**
  53327. * Gets the trigger parameters
  53328. * @returns the trigger parameters
  53329. */
  53330. Action.prototype.getTriggerParameter = function () {
  53331. return this._triggerParameter;
  53332. };
  53333. /**
  53334. * Internal only - executes current action event
  53335. * @hidden
  53336. */
  53337. Action.prototype._executeCurrent = function (evt) {
  53338. if (this._nextActiveAction._condition) {
  53339. var condition = this._nextActiveAction._condition;
  53340. var currentRenderId = this._actionManager.getScene().getRenderId();
  53341. // We cache the current evaluation for the current frame
  53342. if (condition._evaluationId === currentRenderId) {
  53343. if (!condition._currentResult) {
  53344. return;
  53345. }
  53346. }
  53347. else {
  53348. condition._evaluationId = currentRenderId;
  53349. if (!condition.isValid()) {
  53350. condition._currentResult = false;
  53351. return;
  53352. }
  53353. condition._currentResult = true;
  53354. }
  53355. }
  53356. this.onBeforeExecuteObservable.notifyObservers(this);
  53357. this._nextActiveAction.execute(evt);
  53358. this.skipToNextActiveAction();
  53359. };
  53360. /**
  53361. * Execute placeholder for child classes
  53362. * @param evt optional action event
  53363. */
  53364. Action.prototype.execute = function (evt) {
  53365. };
  53366. /**
  53367. * Skips to next active action
  53368. */
  53369. Action.prototype.skipToNextActiveAction = function () {
  53370. if (this._nextActiveAction._child) {
  53371. if (!this._nextActiveAction._child._actionManager) {
  53372. this._nextActiveAction._child._actionManager = this._actionManager;
  53373. }
  53374. this._nextActiveAction = this._nextActiveAction._child;
  53375. }
  53376. else {
  53377. this._nextActiveAction = this;
  53378. }
  53379. };
  53380. /**
  53381. * Adds action to chain of actions, may be a DoNothingAction
  53382. * @param action defines the next action to execute
  53383. * @returns The action passed in
  53384. * @see https://www.babylonjs-playground.com/#1T30HR#0
  53385. */
  53386. Action.prototype.then = function (action) {
  53387. this._child = action;
  53388. action._actionManager = this._actionManager;
  53389. action._prepare();
  53390. return action;
  53391. };
  53392. /**
  53393. * Internal only
  53394. * @hidden
  53395. */
  53396. Action.prototype._getProperty = function (propertyPath) {
  53397. return this._actionManager._getProperty(propertyPath);
  53398. };
  53399. /**
  53400. * Internal only
  53401. * @hidden
  53402. */
  53403. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  53404. return this._actionManager._getEffectiveTarget(target, propertyPath);
  53405. };
  53406. /**
  53407. * Serialize placeholder for child classes
  53408. * @param parent of child
  53409. * @returns the serialized object
  53410. */
  53411. Action.prototype.serialize = function (parent) {
  53412. };
  53413. /**
  53414. * Internal only called by serialize
  53415. * @hidden
  53416. */
  53417. Action.prototype._serialize = function (serializedAction, parent) {
  53418. var serializationObject = {
  53419. type: 1,
  53420. children: [],
  53421. name: serializedAction.name,
  53422. properties: serializedAction.properties || []
  53423. };
  53424. // Serialize child
  53425. if (this._child) {
  53426. this._child.serialize(serializationObject);
  53427. }
  53428. // Check if "this" has a condition
  53429. if (this._condition) {
  53430. var serializedCondition = this._condition.serialize();
  53431. serializedCondition.children.push(serializationObject);
  53432. if (parent) {
  53433. parent.children.push(serializedCondition);
  53434. }
  53435. return serializedCondition;
  53436. }
  53437. if (parent) {
  53438. parent.children.push(serializationObject);
  53439. }
  53440. return serializationObject;
  53441. };
  53442. /**
  53443. * Internal only
  53444. * @hidden
  53445. */
  53446. Action._SerializeValueAsString = function (value) {
  53447. if (typeof value === "number") {
  53448. return value.toString();
  53449. }
  53450. if (typeof value === "boolean") {
  53451. return value ? "true" : "false";
  53452. }
  53453. if (value instanceof BABYLON.Vector2) {
  53454. return value.x + ", " + value.y;
  53455. }
  53456. if (value instanceof BABYLON.Vector3) {
  53457. return value.x + ", " + value.y + ", " + value.z;
  53458. }
  53459. if (value instanceof BABYLON.Color3) {
  53460. return value.r + ", " + value.g + ", " + value.b;
  53461. }
  53462. if (value instanceof BABYLON.Color4) {
  53463. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  53464. }
  53465. return value; // string
  53466. };
  53467. /**
  53468. * Internal only
  53469. * @hidden
  53470. */
  53471. Action._GetTargetProperty = function (target) {
  53472. return {
  53473. name: "target",
  53474. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  53475. : target instanceof BABYLON.Light ? "LightProperties"
  53476. : target instanceof BABYLON.Camera ? "CameraProperties"
  53477. : "SceneProperties",
  53478. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  53479. };
  53480. };
  53481. return Action;
  53482. }());
  53483. BABYLON.Action = Action;
  53484. })(BABYLON || (BABYLON = {}));
  53485. //# sourceMappingURL=babylon.action.js.map
  53486. var BABYLON;
  53487. (function (BABYLON) {
  53488. /**
  53489. * ActionEvent is the event being sent when an action is triggered.
  53490. */
  53491. var ActionEvent = /** @class */ (function () {
  53492. /**
  53493. * Creates a new ActionEvent
  53494. * @param source The mesh or sprite that triggered the action
  53495. * @param pointerX The X mouse cursor position at the time of the event
  53496. * @param pointerY The Y mouse cursor position at the time of the event
  53497. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  53498. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  53499. * @param additionalData additional data for the event
  53500. */
  53501. function ActionEvent(
  53502. /** The mesh or sprite that triggered the action */
  53503. source,
  53504. /** The X mouse cursor position at the time of the event */
  53505. pointerX,
  53506. /** The Y mouse cursor position at the time of the event */
  53507. pointerY,
  53508. /** The mesh that is currently pointed at (can be null) */
  53509. meshUnderPointer,
  53510. /** the original (browser) event that triggered the ActionEvent */
  53511. sourceEvent,
  53512. /** additional data for the event */
  53513. additionalData) {
  53514. this.source = source;
  53515. this.pointerX = pointerX;
  53516. this.pointerY = pointerY;
  53517. this.meshUnderPointer = meshUnderPointer;
  53518. this.sourceEvent = sourceEvent;
  53519. this.additionalData = additionalData;
  53520. }
  53521. /**
  53522. * Helper function to auto-create an ActionEvent from a source mesh.
  53523. * @param source The source mesh that triggered the event
  53524. * @param evt The original (browser) event
  53525. * @param additionalData additional data for the event
  53526. * @returns the new ActionEvent
  53527. */
  53528. ActionEvent.CreateNew = function (source, evt, additionalData) {
  53529. var scene = source.getScene();
  53530. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  53531. };
  53532. /**
  53533. * Helper function to auto-create an ActionEvent from a source sprite
  53534. * @param source The source sprite that triggered the event
  53535. * @param scene Scene associated with the sprite
  53536. * @param evt The original (browser) event
  53537. * @param additionalData additional data for the event
  53538. * @returns the new ActionEvent
  53539. */
  53540. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  53541. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  53542. };
  53543. /**
  53544. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  53545. * @param scene the scene where the event occurred
  53546. * @param evt The original (browser) event
  53547. * @returns the new ActionEvent
  53548. */
  53549. ActionEvent.CreateNewFromScene = function (scene, evt) {
  53550. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  53551. };
  53552. /**
  53553. * Helper function to auto-create an ActionEvent from a primitive
  53554. * @param prim defines the target primitive
  53555. * @param pointerPos defines the pointer position
  53556. * @param evt The original (browser) event
  53557. * @param additionalData additional data for the event
  53558. * @returns the new ActionEvent
  53559. */
  53560. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  53561. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  53562. };
  53563. return ActionEvent;
  53564. }());
  53565. BABYLON.ActionEvent = ActionEvent;
  53566. /**
  53567. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  53568. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  53569. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  53570. */
  53571. var ActionManager = /** @class */ (function () {
  53572. /**
  53573. * Creates a new action manager
  53574. * @param scene defines the hosting scene
  53575. */
  53576. function ActionManager(scene) {
  53577. // Members
  53578. /** Gets the list of actions */
  53579. this.actions = new Array();
  53580. /** Gets the cursor to use when hovering items */
  53581. this.hoverCursor = '';
  53582. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  53583. scene.actionManagers.push(this);
  53584. }
  53585. // Methods
  53586. /**
  53587. * Releases all associated resources
  53588. */
  53589. ActionManager.prototype.dispose = function () {
  53590. var index = this._scene.actionManagers.indexOf(this);
  53591. for (var i = 0; i < this.actions.length; i++) {
  53592. var action = this.actions[i];
  53593. ActionManager.Triggers[action.trigger]--;
  53594. if (ActionManager.Triggers[action.trigger] === 0) {
  53595. delete ActionManager.Triggers[action.trigger];
  53596. }
  53597. }
  53598. if (index > -1) {
  53599. this._scene.actionManagers.splice(index, 1);
  53600. }
  53601. };
  53602. /**
  53603. * Gets hosting scene
  53604. * @returns the hosting scene
  53605. */
  53606. ActionManager.prototype.getScene = function () {
  53607. return this._scene;
  53608. };
  53609. /**
  53610. * Does this action manager handles actions of any of the given triggers
  53611. * @param triggers defines the triggers to be tested
  53612. * @return a boolean indicating whether one (or more) of the triggers is handled
  53613. */
  53614. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  53615. for (var index = 0; index < this.actions.length; index++) {
  53616. var action = this.actions[index];
  53617. if (triggers.indexOf(action.trigger) > -1) {
  53618. return true;
  53619. }
  53620. }
  53621. return false;
  53622. };
  53623. /**
  53624. * Does this action manager handles actions of any of the given triggers. This function takes two arguments for
  53625. * speed.
  53626. * @param triggerA defines the trigger to be tested
  53627. * @param triggerB defines the trigger to be tested
  53628. * @return a boolean indicating whether one (or more) of the triggers is handled
  53629. */
  53630. ActionManager.prototype.hasSpecificTriggers2 = function (triggerA, triggerB) {
  53631. for (var index = 0; index < this.actions.length; index++) {
  53632. var action = this.actions[index];
  53633. if (triggerA == action.trigger || triggerB == action.trigger) {
  53634. return true;
  53635. }
  53636. }
  53637. return false;
  53638. };
  53639. /**
  53640. * Does this action manager handles actions of a given trigger
  53641. * @param trigger defines the trigger to be tested
  53642. * @param parameterPredicate defines an optional predicate to filter triggers by parameter
  53643. * @return whether the trigger is handled
  53644. */
  53645. ActionManager.prototype.hasSpecificTrigger = function (trigger, parameterPredicate) {
  53646. for (var index = 0; index < this.actions.length; index++) {
  53647. var action = this.actions[index];
  53648. if (action.trigger === trigger) {
  53649. if (parameterPredicate) {
  53650. if (parameterPredicate(action.getTriggerParameter())) {
  53651. return true;
  53652. }
  53653. }
  53654. else {
  53655. return true;
  53656. }
  53657. }
  53658. }
  53659. return false;
  53660. };
  53661. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  53662. /**
  53663. * Does this action manager has pointer triggers
  53664. */
  53665. get: function () {
  53666. for (var index = 0; index < this.actions.length; index++) {
  53667. var action = this.actions[index];
  53668. if (action.trigger >= ActionManager.OnPickTrigger && action.trigger <= ActionManager.OnPointerOutTrigger) {
  53669. return true;
  53670. }
  53671. }
  53672. return false;
  53673. },
  53674. enumerable: true,
  53675. configurable: true
  53676. });
  53677. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  53678. /**
  53679. * Does this action manager has pick triggers
  53680. */
  53681. get: function () {
  53682. for (var index = 0; index < this.actions.length; index++) {
  53683. var action = this.actions[index];
  53684. if (action.trigger >= ActionManager.OnPickTrigger && action.trigger <= ActionManager.OnPickUpTrigger) {
  53685. return true;
  53686. }
  53687. }
  53688. return false;
  53689. },
  53690. enumerable: true,
  53691. configurable: true
  53692. });
  53693. Object.defineProperty(ActionManager, "HasTriggers", {
  53694. /**
  53695. * Does exist one action manager with at least one trigger
  53696. **/
  53697. get: function () {
  53698. for (var t in ActionManager.Triggers) {
  53699. if (ActionManager.Triggers.hasOwnProperty(t)) {
  53700. return true;
  53701. }
  53702. }
  53703. return false;
  53704. },
  53705. enumerable: true,
  53706. configurable: true
  53707. });
  53708. Object.defineProperty(ActionManager, "HasPickTriggers", {
  53709. /**
  53710. * Does exist one action manager with at least one pick trigger
  53711. **/
  53712. get: function () {
  53713. for (var t in ActionManager.Triggers) {
  53714. if (ActionManager.Triggers.hasOwnProperty(t)) {
  53715. var t_int = parseInt(t);
  53716. if (t_int >= ActionManager.OnPickTrigger && t_int <= ActionManager.OnPickUpTrigger) {
  53717. return true;
  53718. }
  53719. }
  53720. }
  53721. return false;
  53722. },
  53723. enumerable: true,
  53724. configurable: true
  53725. });
  53726. /**
  53727. * Does exist one action manager that handles actions of a given trigger
  53728. * @param trigger defines the trigger to be tested
  53729. * @return a boolean indicating whether the trigger is handeled by at least one action manager
  53730. **/
  53731. ActionManager.HasSpecificTrigger = function (trigger) {
  53732. for (var t in ActionManager.Triggers) {
  53733. if (ActionManager.Triggers.hasOwnProperty(t)) {
  53734. var t_int = parseInt(t);
  53735. if (t_int === trigger) {
  53736. return true;
  53737. }
  53738. }
  53739. }
  53740. return false;
  53741. };
  53742. /**
  53743. * Registers an action to this action manager
  53744. * @param action defines the action to be registered
  53745. * @return the action amended (prepared) after registration
  53746. */
  53747. ActionManager.prototype.registerAction = function (action) {
  53748. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  53749. if (this.getScene().actionManager !== this) {
  53750. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  53751. return null;
  53752. }
  53753. }
  53754. this.actions.push(action);
  53755. if (ActionManager.Triggers[action.trigger]) {
  53756. ActionManager.Triggers[action.trigger]++;
  53757. }
  53758. else {
  53759. ActionManager.Triggers[action.trigger] = 1;
  53760. }
  53761. action._actionManager = this;
  53762. action._prepare();
  53763. return action;
  53764. };
  53765. /**
  53766. * Unregisters an action to this action manager
  53767. * @param action defines the action to be unregistered
  53768. * @return a boolean indicating whether the action has been unregistered
  53769. */
  53770. ActionManager.prototype.unregisterAction = function (action) {
  53771. var index = this.actions.indexOf(action);
  53772. if (index !== -1) {
  53773. this.actions.splice(index, 1);
  53774. ActionManager.Triggers[action.trigger] -= 1;
  53775. if (ActionManager.Triggers[action.trigger] === 0) {
  53776. delete ActionManager.Triggers[action.trigger];
  53777. }
  53778. delete action._actionManager;
  53779. return true;
  53780. }
  53781. return false;
  53782. };
  53783. /**
  53784. * Process a specific trigger
  53785. * @param trigger defines the trigger to process
  53786. * @param evt defines the event details to be processed
  53787. */
  53788. ActionManager.prototype.processTrigger = function (trigger, evt) {
  53789. for (var index = 0; index < this.actions.length; index++) {
  53790. var action = this.actions[index];
  53791. if (action.trigger === trigger) {
  53792. if (evt) {
  53793. if (trigger === ActionManager.OnKeyUpTrigger
  53794. || trigger === ActionManager.OnKeyDownTrigger) {
  53795. var parameter = action.getTriggerParameter();
  53796. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  53797. if (!parameter.toLowerCase) {
  53798. continue;
  53799. }
  53800. var lowerCase = parameter.toLowerCase();
  53801. if (lowerCase !== evt.sourceEvent.key) {
  53802. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  53803. var actualkey = String.fromCharCode(unicode).toLowerCase();
  53804. if (actualkey !== lowerCase) {
  53805. continue;
  53806. }
  53807. }
  53808. }
  53809. }
  53810. }
  53811. action._executeCurrent(evt);
  53812. }
  53813. }
  53814. };
  53815. /** @hidden */
  53816. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  53817. var properties = propertyPath.split(".");
  53818. for (var index = 0; index < properties.length - 1; index++) {
  53819. target = target[properties[index]];
  53820. }
  53821. return target;
  53822. };
  53823. /** @hidden */
  53824. ActionManager.prototype._getProperty = function (propertyPath) {
  53825. var properties = propertyPath.split(".");
  53826. return properties[properties.length - 1];
  53827. };
  53828. /**
  53829. * Serialize this manager to a JSON object
  53830. * @param name defines the property name to store this manager
  53831. * @returns a JSON representation of this manager
  53832. */
  53833. ActionManager.prototype.serialize = function (name) {
  53834. var root = {
  53835. children: new Array(),
  53836. name: name,
  53837. type: 3,
  53838. properties: new Array() // Empty for root but required
  53839. };
  53840. for (var i = 0; i < this.actions.length; i++) {
  53841. var triggerObject = {
  53842. type: 0,
  53843. children: new Array(),
  53844. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  53845. properties: new Array()
  53846. };
  53847. var triggerOptions = this.actions[i].triggerOptions;
  53848. if (triggerOptions && typeof triggerOptions !== "number") {
  53849. if (triggerOptions.parameter instanceof BABYLON.Node) {
  53850. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  53851. }
  53852. else {
  53853. var parameter = {};
  53854. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  53855. if (triggerOptions.parameter.mesh) {
  53856. parameter._meshId = triggerOptions.parameter.mesh.id;
  53857. }
  53858. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  53859. }
  53860. }
  53861. // Serialize child action, recursively
  53862. this.actions[i].serialize(triggerObject);
  53863. // Add serialized trigger
  53864. root.children.push(triggerObject);
  53865. }
  53866. return root;
  53867. };
  53868. /**
  53869. * Creates a new ActionManager from a JSON data
  53870. * @param parsedActions defines the JSON data to read from
  53871. * @param object defines the hosting mesh
  53872. * @param scene defines the hosting scene
  53873. */
  53874. ActionManager.Parse = function (parsedActions, object, scene) {
  53875. var actionManager = new ActionManager(scene);
  53876. if (object === null)
  53877. scene.actionManager = actionManager;
  53878. else
  53879. object.actionManager = actionManager;
  53880. // instanciate a new object
  53881. var instanciate = function (name, params) {
  53882. // TODO: We will need to find a solution for the next line when using commonjs / es6 .
  53883. var newInstance = Object.create(BABYLON.Tools.Instantiate("BABYLON." + name).prototype);
  53884. newInstance.constructor.apply(newInstance, params);
  53885. return newInstance;
  53886. };
  53887. var parseParameter = function (name, value, target, propertyPath) {
  53888. if (propertyPath === null) {
  53889. // String, boolean or float
  53890. var floatValue = parseFloat(value);
  53891. if (value === "true" || value === "false")
  53892. return value === "true";
  53893. else
  53894. return isNaN(floatValue) ? value : floatValue;
  53895. }
  53896. var effectiveTarget = propertyPath.split(".");
  53897. var values = value.split(",");
  53898. // Get effective Target
  53899. for (var i = 0; i < effectiveTarget.length; i++) {
  53900. target = target[effectiveTarget[i]];
  53901. }
  53902. // Return appropriate value with its type
  53903. if (typeof (target) === "boolean")
  53904. return values[0] === "true";
  53905. if (typeof (target) === "string")
  53906. return values[0];
  53907. // Parameters with multiple values such as Vector3 etc.
  53908. var split = new Array();
  53909. for (var i = 0; i < values.length; i++)
  53910. split.push(parseFloat(values[i]));
  53911. if (target instanceof BABYLON.Vector3)
  53912. return BABYLON.Vector3.FromArray(split);
  53913. if (target instanceof BABYLON.Vector4)
  53914. return BABYLON.Vector4.FromArray(split);
  53915. if (target instanceof BABYLON.Color3)
  53916. return BABYLON.Color3.FromArray(split);
  53917. if (target instanceof BABYLON.Color4)
  53918. return BABYLON.Color4.FromArray(split);
  53919. return parseFloat(values[0]);
  53920. };
  53921. // traverse graph per trigger
  53922. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  53923. if (combineArray === void 0) { combineArray = null; }
  53924. if (parsedAction.detached)
  53925. return;
  53926. var parameters = new Array();
  53927. var target = null;
  53928. var propertyPath = null;
  53929. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  53930. // Parameters
  53931. if (parsedAction.type === 2)
  53932. parameters.push(actionManager);
  53933. else
  53934. parameters.push(trigger);
  53935. if (combine) {
  53936. var actions = new Array();
  53937. for (var j = 0; j < parsedAction.combine.length; j++) {
  53938. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  53939. }
  53940. parameters.push(actions);
  53941. }
  53942. else {
  53943. for (var i = 0; i < parsedAction.properties.length; i++) {
  53944. var value = parsedAction.properties[i].value;
  53945. var name = parsedAction.properties[i].name;
  53946. var targetType = parsedAction.properties[i].targetType;
  53947. if (name === "target")
  53948. if (targetType !== null && targetType === "SceneProperties")
  53949. value = target = scene;
  53950. else
  53951. value = target = scene.getNodeByName(value);
  53952. else if (name === "parent")
  53953. value = scene.getNodeByName(value);
  53954. else if (name === "sound") {
  53955. // Can not externalize to component, so only checks for the presence off the API.
  53956. if (scene.getSoundByName) {
  53957. value = scene.getSoundByName(value);
  53958. }
  53959. }
  53960. else if (name !== "propertyPath") {
  53961. if (parsedAction.type === 2 && name === "operator")
  53962. value = BABYLON.ValueCondition[value];
  53963. else
  53964. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  53965. }
  53966. else {
  53967. propertyPath = value;
  53968. }
  53969. parameters.push(value);
  53970. }
  53971. }
  53972. if (combineArray === null) {
  53973. parameters.push(condition);
  53974. }
  53975. else {
  53976. parameters.push(null);
  53977. }
  53978. // If interpolate value action
  53979. if (parsedAction.name === "InterpolateValueAction") {
  53980. var param = parameters[parameters.length - 2];
  53981. parameters[parameters.length - 1] = param;
  53982. parameters[parameters.length - 2] = condition;
  53983. }
  53984. // Action or condition(s) and not CombineAction
  53985. var newAction = instanciate(parsedAction.name, parameters);
  53986. if (newAction instanceof BABYLON.Condition && condition !== null) {
  53987. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  53988. if (action)
  53989. action.then(nothing);
  53990. else
  53991. actionManager.registerAction(nothing);
  53992. action = nothing;
  53993. }
  53994. if (combineArray === null) {
  53995. if (newAction instanceof BABYLON.Condition) {
  53996. condition = newAction;
  53997. newAction = action;
  53998. }
  53999. else {
  54000. condition = null;
  54001. if (action)
  54002. action.then(newAction);
  54003. else
  54004. actionManager.registerAction(newAction);
  54005. }
  54006. }
  54007. else {
  54008. combineArray.push(newAction);
  54009. }
  54010. for (var i = 0; i < parsedAction.children.length; i++)
  54011. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  54012. };
  54013. // triggers
  54014. for (var i = 0; i < parsedActions.children.length; i++) {
  54015. var triggerParams;
  54016. var trigger = parsedActions.children[i];
  54017. if (trigger.properties.length > 0) {
  54018. var param = trigger.properties[0].value;
  54019. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  54020. if (value._meshId) {
  54021. value.mesh = scene.getMeshByID(value._meshId);
  54022. }
  54023. triggerParams = { trigger: ActionManager[trigger.name], parameter: value };
  54024. }
  54025. else
  54026. triggerParams = ActionManager[trigger.name];
  54027. for (var j = 0; j < trigger.children.length; j++) {
  54028. if (!trigger.detached)
  54029. traverse(trigger.children[j], triggerParams, null, null);
  54030. }
  54031. }
  54032. };
  54033. /**
  54034. * Get a trigger name by index
  54035. * @param trigger defines the trigger index
  54036. * @returns a trigger name
  54037. */
  54038. ActionManager.GetTriggerName = function (trigger) {
  54039. switch (trigger) {
  54040. case 0: return "NothingTrigger";
  54041. case 1: return "OnPickTrigger";
  54042. case 2: return "OnLeftPickTrigger";
  54043. case 3: return "OnRightPickTrigger";
  54044. case 4: return "OnCenterPickTrigger";
  54045. case 5: return "OnPickDownTrigger";
  54046. case 6: return "OnPickUpTrigger";
  54047. case 7: return "OnLongPressTrigger";
  54048. case 8: return "OnPointerOverTrigger";
  54049. case 9: return "OnPointerOutTrigger";
  54050. case 10: return "OnEveryFrameTrigger";
  54051. case 11: return "OnIntersectionEnterTrigger";
  54052. case 12: return "OnIntersectionExitTrigger";
  54053. case 13: return "OnKeyDownTrigger";
  54054. case 14: return "OnKeyUpTrigger";
  54055. case 15: return "OnPickOutTrigger";
  54056. default: return "";
  54057. }
  54058. };
  54059. /**
  54060. * Nothing
  54061. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  54062. */
  54063. ActionManager.NothingTrigger = 0;
  54064. /**
  54065. * On pick
  54066. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  54067. */
  54068. ActionManager.OnPickTrigger = 1;
  54069. /**
  54070. * On left pick
  54071. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  54072. */
  54073. ActionManager.OnLeftPickTrigger = 2;
  54074. /**
  54075. * On right pick
  54076. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  54077. */
  54078. ActionManager.OnRightPickTrigger = 3;
  54079. /**
  54080. * On center pick
  54081. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  54082. */
  54083. ActionManager.OnCenterPickTrigger = 4;
  54084. /**
  54085. * On pick down
  54086. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  54087. */
  54088. ActionManager.OnPickDownTrigger = 5;
  54089. /**
  54090. * On double pick
  54091. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  54092. */
  54093. ActionManager.OnDoublePickTrigger = 6;
  54094. /**
  54095. * On pick up
  54096. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  54097. */
  54098. ActionManager.OnPickUpTrigger = 7;
  54099. /**
  54100. * On pick out.
  54101. * This trigger will only be raised if you also declared a OnPickDown
  54102. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  54103. */
  54104. ActionManager.OnPickOutTrigger = 16;
  54105. /**
  54106. * On long press
  54107. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  54108. */
  54109. ActionManager.OnLongPressTrigger = 8;
  54110. /**
  54111. * On pointer over
  54112. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  54113. */
  54114. ActionManager.OnPointerOverTrigger = 9;
  54115. /**
  54116. * On pointer out
  54117. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  54118. */
  54119. ActionManager.OnPointerOutTrigger = 10;
  54120. /**
  54121. * On every frame
  54122. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  54123. */
  54124. ActionManager.OnEveryFrameTrigger = 11;
  54125. /**
  54126. * On intersection enter
  54127. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  54128. */
  54129. ActionManager.OnIntersectionEnterTrigger = 12;
  54130. /**
  54131. * On intersection exit
  54132. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  54133. */
  54134. ActionManager.OnIntersectionExitTrigger = 13;
  54135. /**
  54136. * On key down
  54137. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  54138. */
  54139. ActionManager.OnKeyDownTrigger = 14;
  54140. /**
  54141. * On key up
  54142. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  54143. */
  54144. ActionManager.OnKeyUpTrigger = 15;
  54145. /** Gets the list of active triggers */
  54146. ActionManager.Triggers = {};
  54147. return ActionManager;
  54148. }());
  54149. BABYLON.ActionManager = ActionManager;
  54150. })(BABYLON || (BABYLON = {}));
  54151. //# sourceMappingURL=babylon.actionManager.js.map
  54152. var BABYLON;
  54153. (function (BABYLON) {
  54154. /**
  54155. * This defines an action responsible to change the value of a property
  54156. * by interpolating between its current value and the newly set one once triggered.
  54157. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  54158. */
  54159. var InterpolateValueAction = /** @class */ (function (_super) {
  54160. __extends(InterpolateValueAction, _super);
  54161. /**
  54162. * Instantiate the action
  54163. * @param triggerOptions defines the trigger options
  54164. * @param target defines the object containing the value to interpolate
  54165. * @param propertyPath defines the path to the property in the target object
  54166. * @param value defines the target value at the end of the interpolation
  54167. * @param duration deines the time it will take for the property to interpolate to the value.
  54168. * @param condition defines the trigger related conditions
  54169. * @param stopOtherAnimations defines if the other scene animations should be stopped when the action has been triggered
  54170. * @param onInterpolationDone defines a callback raised once the interpolation animation has been done
  54171. */
  54172. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  54173. if (duration === void 0) { duration = 1000; }
  54174. var _this = _super.call(this, triggerOptions, condition) || this;
  54175. /**
  54176. * Defines the time it will take for the property to interpolate to the value.
  54177. */
  54178. _this.duration = 1000;
  54179. /**
  54180. * Observable triggered once the interpolation animation has been done.
  54181. */
  54182. _this.onInterpolationDoneObservable = new BABYLON.Observable();
  54183. _this.propertyPath = propertyPath;
  54184. _this.value = value;
  54185. _this.duration = duration;
  54186. _this.stopOtherAnimations = stopOtherAnimations;
  54187. _this.onInterpolationDone = onInterpolationDone;
  54188. _this._target = _this._effectiveTarget = target;
  54189. return _this;
  54190. }
  54191. /** @hidden */
  54192. InterpolateValueAction.prototype._prepare = function () {
  54193. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  54194. this._property = this._getProperty(this.propertyPath);
  54195. };
  54196. /**
  54197. * Execute the action starts the value interpolation.
  54198. */
  54199. InterpolateValueAction.prototype.execute = function () {
  54200. var _this = this;
  54201. var scene = this._actionManager.getScene();
  54202. var keys = [
  54203. {
  54204. frame: 0,
  54205. value: this._effectiveTarget[this._property]
  54206. }, {
  54207. frame: 100,
  54208. value: this.value
  54209. }
  54210. ];
  54211. var dataType;
  54212. if (typeof this.value === "number") {
  54213. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  54214. }
  54215. else if (this.value instanceof BABYLON.Color3) {
  54216. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  54217. }
  54218. else if (this.value instanceof BABYLON.Vector3) {
  54219. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  54220. }
  54221. else if (this.value instanceof BABYLON.Matrix) {
  54222. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  54223. }
  54224. else if (this.value instanceof BABYLON.Quaternion) {
  54225. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  54226. }
  54227. else {
  54228. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  54229. return;
  54230. }
  54231. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  54232. animation.setKeys(keys);
  54233. if (this.stopOtherAnimations) {
  54234. scene.stopAnimation(this._effectiveTarget);
  54235. }
  54236. var wrapper = function () {
  54237. _this.onInterpolationDoneObservable.notifyObservers(_this);
  54238. if (_this.onInterpolationDone) {
  54239. _this.onInterpolationDone();
  54240. }
  54241. };
  54242. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);
  54243. };
  54244. /**
  54245. * Serializes the actions and its related information.
  54246. * @param parent defines the object to serialize in
  54247. * @returns the serialized object
  54248. */
  54249. InterpolateValueAction.prototype.serialize = function (parent) {
  54250. return _super.prototype._serialize.call(this, {
  54251. name: "InterpolateValueAction",
  54252. properties: [
  54253. BABYLON.Action._GetTargetProperty(this._target),
  54254. { name: "propertyPath", value: this.propertyPath },
  54255. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  54256. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  54257. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  54258. ]
  54259. }, parent);
  54260. };
  54261. return InterpolateValueAction;
  54262. }(BABYLON.Action));
  54263. BABYLON.InterpolateValueAction = InterpolateValueAction;
  54264. })(BABYLON || (BABYLON = {}));
  54265. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  54266. var BABYLON;
  54267. (function (BABYLON) {
  54268. /**
  54269. * This defines an action responsible to toggle a boolean once triggered.
  54270. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  54271. */
  54272. var SwitchBooleanAction = /** @class */ (function (_super) {
  54273. __extends(SwitchBooleanAction, _super);
  54274. /**
  54275. * Instantiate the action
  54276. * @param triggerOptions defines the trigger options
  54277. * @param target defines the object containing the boolean
  54278. * @param propertyPath defines the path to the boolean property in the target object
  54279. * @param condition defines the trigger related conditions
  54280. */
  54281. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  54282. var _this = _super.call(this, triggerOptions, condition) || this;
  54283. _this.propertyPath = propertyPath;
  54284. _this._target = _this._effectiveTarget = target;
  54285. return _this;
  54286. }
  54287. /** @hidden */
  54288. SwitchBooleanAction.prototype._prepare = function () {
  54289. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  54290. this._property = this._getProperty(this.propertyPath);
  54291. };
  54292. /**
  54293. * Execute the action toggle the boolean value.
  54294. */
  54295. SwitchBooleanAction.prototype.execute = function () {
  54296. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  54297. };
  54298. /**
  54299. * Serializes the actions and its related information.
  54300. * @param parent defines the object to serialize in
  54301. * @returns the serialized object
  54302. */
  54303. SwitchBooleanAction.prototype.serialize = function (parent) {
  54304. return _super.prototype._serialize.call(this, {
  54305. name: "SwitchBooleanAction",
  54306. properties: [
  54307. BABYLON.Action._GetTargetProperty(this._target),
  54308. { name: "propertyPath", value: this.propertyPath }
  54309. ]
  54310. }, parent);
  54311. };
  54312. return SwitchBooleanAction;
  54313. }(BABYLON.Action));
  54314. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  54315. /**
  54316. * This defines an action responsible to set a the state field of the target
  54317. * to a desired value once triggered.
  54318. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  54319. */
  54320. var SetStateAction = /** @class */ (function (_super) {
  54321. __extends(SetStateAction, _super);
  54322. /**
  54323. * Instantiate the action
  54324. * @param triggerOptions defines the trigger options
  54325. * @param target defines the object containing the state property
  54326. * @param value defines the value to store in the state field
  54327. * @param condition defines the trigger related conditions
  54328. */
  54329. function SetStateAction(triggerOptions, target, value, condition) {
  54330. var _this = _super.call(this, triggerOptions, condition) || this;
  54331. _this.value = value;
  54332. _this._target = target;
  54333. return _this;
  54334. }
  54335. /**
  54336. * Execute the action and store the value on the target state property.
  54337. */
  54338. SetStateAction.prototype.execute = function () {
  54339. this._target.state = this.value;
  54340. };
  54341. /**
  54342. * Serializes the actions and its related information.
  54343. * @param parent defines the object to serialize in
  54344. * @returns the serialized object
  54345. */
  54346. SetStateAction.prototype.serialize = function (parent) {
  54347. return _super.prototype._serialize.call(this, {
  54348. name: "SetStateAction",
  54349. properties: [
  54350. BABYLON.Action._GetTargetProperty(this._target),
  54351. { name: "value", value: this.value }
  54352. ]
  54353. }, parent);
  54354. };
  54355. return SetStateAction;
  54356. }(BABYLON.Action));
  54357. BABYLON.SetStateAction = SetStateAction;
  54358. /**
  54359. * This defines an action responsible to set a property of the target
  54360. * to a desired value once triggered.
  54361. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  54362. */
  54363. var SetValueAction = /** @class */ (function (_super) {
  54364. __extends(SetValueAction, _super);
  54365. /**
  54366. * Instantiate the action
  54367. * @param triggerOptions defines the trigger options
  54368. * @param target defines the object containing the property
  54369. * @param propertyPath defines the path of the property to set in the target
  54370. * @param value defines the value to set in the property
  54371. * @param condition defines the trigger related conditions
  54372. */
  54373. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  54374. var _this = _super.call(this, triggerOptions, condition) || this;
  54375. _this.propertyPath = propertyPath;
  54376. _this.value = value;
  54377. _this._target = _this._effectiveTarget = target;
  54378. return _this;
  54379. }
  54380. /** @hidden */
  54381. SetValueAction.prototype._prepare = function () {
  54382. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  54383. this._property = this._getProperty(this.propertyPath);
  54384. };
  54385. /**
  54386. * Execute the action and set the targetted property to the desired value.
  54387. */
  54388. SetValueAction.prototype.execute = function () {
  54389. this._effectiveTarget[this._property] = this.value;
  54390. if (this._target.markAsDirty) {
  54391. this._target.markAsDirty(this._property);
  54392. }
  54393. };
  54394. /**
  54395. * Serializes the actions and its related information.
  54396. * @param parent defines the object to serialize in
  54397. * @returns the serialized object
  54398. */
  54399. SetValueAction.prototype.serialize = function (parent) {
  54400. return _super.prototype._serialize.call(this, {
  54401. name: "SetValueAction",
  54402. properties: [
  54403. BABYLON.Action._GetTargetProperty(this._target),
  54404. { name: "propertyPath", value: this.propertyPath },
  54405. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  54406. ]
  54407. }, parent);
  54408. };
  54409. return SetValueAction;
  54410. }(BABYLON.Action));
  54411. BABYLON.SetValueAction = SetValueAction;
  54412. /**
  54413. * This defines an action responsible to increment the target value
  54414. * to a desired value once triggered.
  54415. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  54416. */
  54417. var IncrementValueAction = /** @class */ (function (_super) {
  54418. __extends(IncrementValueAction, _super);
  54419. /**
  54420. * Instantiate the action
  54421. * @param triggerOptions defines the trigger options
  54422. * @param target defines the object containing the property
  54423. * @param propertyPath defines the path of the property to increment in the target
  54424. * @param value defines the value value we should increment the property by
  54425. * @param condition defines the trigger related conditions
  54426. */
  54427. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  54428. var _this = _super.call(this, triggerOptions, condition) || this;
  54429. _this.propertyPath = propertyPath;
  54430. _this.value = value;
  54431. _this._target = _this._effectiveTarget = target;
  54432. return _this;
  54433. }
  54434. /** @hidden */
  54435. IncrementValueAction.prototype._prepare = function () {
  54436. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  54437. this._property = this._getProperty(this.propertyPath);
  54438. if (typeof this._effectiveTarget[this._property] !== "number") {
  54439. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  54440. }
  54441. };
  54442. /**
  54443. * Execute the action and increment the target of the value amount.
  54444. */
  54445. IncrementValueAction.prototype.execute = function () {
  54446. this._effectiveTarget[this._property] += this.value;
  54447. if (this._target.markAsDirty) {
  54448. this._target.markAsDirty(this._property);
  54449. }
  54450. };
  54451. /**
  54452. * Serializes the actions and its related information.
  54453. * @param parent defines the object to serialize in
  54454. * @returns the serialized object
  54455. */
  54456. IncrementValueAction.prototype.serialize = function (parent) {
  54457. return _super.prototype._serialize.call(this, {
  54458. name: "IncrementValueAction",
  54459. properties: [
  54460. BABYLON.Action._GetTargetProperty(this._target),
  54461. { name: "propertyPath", value: this.propertyPath },
  54462. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  54463. ]
  54464. }, parent);
  54465. };
  54466. return IncrementValueAction;
  54467. }(BABYLON.Action));
  54468. BABYLON.IncrementValueAction = IncrementValueAction;
  54469. /**
  54470. * This defines an action responsible to start an animation once triggered.
  54471. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  54472. */
  54473. var PlayAnimationAction = /** @class */ (function (_super) {
  54474. __extends(PlayAnimationAction, _super);
  54475. /**
  54476. * Instantiate the action
  54477. * @param triggerOptions defines the trigger options
  54478. * @param target defines the target animation or animation name
  54479. * @param from defines from where the animation should start (animation frame)
  54480. * @param end defines where the animation should stop (animation frame)
  54481. * @param loop defines if the animation should loop or stop after the first play
  54482. * @param condition defines the trigger related conditions
  54483. */
  54484. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  54485. var _this = _super.call(this, triggerOptions, condition) || this;
  54486. _this.from = from;
  54487. _this.to = to;
  54488. _this.loop = loop;
  54489. _this._target = target;
  54490. return _this;
  54491. }
  54492. /** @hidden */
  54493. PlayAnimationAction.prototype._prepare = function () {
  54494. };
  54495. /**
  54496. * Execute the action and play the animation.
  54497. */
  54498. PlayAnimationAction.prototype.execute = function () {
  54499. var scene = this._actionManager.getScene();
  54500. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  54501. };
  54502. /**
  54503. * Serializes the actions and its related information.
  54504. * @param parent defines the object to serialize in
  54505. * @returns the serialized object
  54506. */
  54507. PlayAnimationAction.prototype.serialize = function (parent) {
  54508. return _super.prototype._serialize.call(this, {
  54509. name: "PlayAnimationAction",
  54510. properties: [
  54511. BABYLON.Action._GetTargetProperty(this._target),
  54512. { name: "from", value: String(this.from) },
  54513. { name: "to", value: String(this.to) },
  54514. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  54515. ]
  54516. }, parent);
  54517. };
  54518. return PlayAnimationAction;
  54519. }(BABYLON.Action));
  54520. BABYLON.PlayAnimationAction = PlayAnimationAction;
  54521. /**
  54522. * This defines an action responsible to stop an animation once triggered.
  54523. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  54524. */
  54525. var StopAnimationAction = /** @class */ (function (_super) {
  54526. __extends(StopAnimationAction, _super);
  54527. /**
  54528. * Instantiate the action
  54529. * @param triggerOptions defines the trigger options
  54530. * @param target defines the target animation or animation name
  54531. * @param condition defines the trigger related conditions
  54532. */
  54533. function StopAnimationAction(triggerOptions, target, condition) {
  54534. var _this = _super.call(this, triggerOptions, condition) || this;
  54535. _this._target = target;
  54536. return _this;
  54537. }
  54538. /** @hidden */
  54539. StopAnimationAction.prototype._prepare = function () {
  54540. };
  54541. /**
  54542. * Execute the action and stop the animation.
  54543. */
  54544. StopAnimationAction.prototype.execute = function () {
  54545. var scene = this._actionManager.getScene();
  54546. scene.stopAnimation(this._target);
  54547. };
  54548. /**
  54549. * Serializes the actions and its related information.
  54550. * @param parent defines the object to serialize in
  54551. * @returns the serialized object
  54552. */
  54553. StopAnimationAction.prototype.serialize = function (parent) {
  54554. return _super.prototype._serialize.call(this, {
  54555. name: "StopAnimationAction",
  54556. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  54557. }, parent);
  54558. };
  54559. return StopAnimationAction;
  54560. }(BABYLON.Action));
  54561. BABYLON.StopAnimationAction = StopAnimationAction;
  54562. /**
  54563. * This defines an action responsible that does nothing once triggered.
  54564. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  54565. */
  54566. var DoNothingAction = /** @class */ (function (_super) {
  54567. __extends(DoNothingAction, _super);
  54568. /**
  54569. * Instantiate the action
  54570. * @param triggerOptions defines the trigger options
  54571. * @param condition defines the trigger related conditions
  54572. */
  54573. function DoNothingAction(triggerOptions, condition) {
  54574. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  54575. return _super.call(this, triggerOptions, condition) || this;
  54576. }
  54577. /**
  54578. * Execute the action and do nothing.
  54579. */
  54580. DoNothingAction.prototype.execute = function () {
  54581. };
  54582. /**
  54583. * Serializes the actions and its related information.
  54584. * @param parent defines the object to serialize in
  54585. * @returns the serialized object
  54586. */
  54587. DoNothingAction.prototype.serialize = function (parent) {
  54588. return _super.prototype._serialize.call(this, {
  54589. name: "DoNothingAction",
  54590. properties: []
  54591. }, parent);
  54592. };
  54593. return DoNothingAction;
  54594. }(BABYLON.Action));
  54595. BABYLON.DoNothingAction = DoNothingAction;
  54596. /**
  54597. * This defines an action responsible to trigger several actions once triggered.
  54598. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  54599. */
  54600. var CombineAction = /** @class */ (function (_super) {
  54601. __extends(CombineAction, _super);
  54602. /**
  54603. * Instantiate the action
  54604. * @param triggerOptions defines the trigger options
  54605. * @param children defines the list of aggregated animations to run
  54606. * @param condition defines the trigger related conditions
  54607. */
  54608. function CombineAction(triggerOptions, children, condition) {
  54609. var _this = _super.call(this, triggerOptions, condition) || this;
  54610. _this.children = children;
  54611. return _this;
  54612. }
  54613. /** @hidden */
  54614. CombineAction.prototype._prepare = function () {
  54615. for (var index = 0; index < this.children.length; index++) {
  54616. this.children[index]._actionManager = this._actionManager;
  54617. this.children[index]._prepare();
  54618. }
  54619. };
  54620. /**
  54621. * Execute the action and executes all the aggregated actions.
  54622. */
  54623. CombineAction.prototype.execute = function (evt) {
  54624. for (var index = 0; index < this.children.length; index++) {
  54625. this.children[index].execute(evt);
  54626. }
  54627. };
  54628. /**
  54629. * Serializes the actions and its related information.
  54630. * @param parent defines the object to serialize in
  54631. * @returns the serialized object
  54632. */
  54633. CombineAction.prototype.serialize = function (parent) {
  54634. var serializationObject = _super.prototype._serialize.call(this, {
  54635. name: "CombineAction",
  54636. properties: [],
  54637. combine: []
  54638. }, parent);
  54639. for (var i = 0; i < this.children.length; i++) {
  54640. serializationObject.combine.push(this.children[i].serialize(null));
  54641. }
  54642. return serializationObject;
  54643. };
  54644. return CombineAction;
  54645. }(BABYLON.Action));
  54646. BABYLON.CombineAction = CombineAction;
  54647. /**
  54648. * This defines an action responsible to run code (external event) once triggered.
  54649. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  54650. */
  54651. var ExecuteCodeAction = /** @class */ (function (_super) {
  54652. __extends(ExecuteCodeAction, _super);
  54653. /**
  54654. * Instantiate the action
  54655. * @param triggerOptions defines the trigger options
  54656. * @param func defines the callback function to run
  54657. * @param condition defines the trigger related conditions
  54658. */
  54659. function ExecuteCodeAction(triggerOptions, func, condition) {
  54660. var _this = _super.call(this, triggerOptions, condition) || this;
  54661. _this.func = func;
  54662. return _this;
  54663. }
  54664. /**
  54665. * Execute the action and run the attached code.
  54666. */
  54667. ExecuteCodeAction.prototype.execute = function (evt) {
  54668. this.func(evt);
  54669. };
  54670. return ExecuteCodeAction;
  54671. }(BABYLON.Action));
  54672. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  54673. /**
  54674. * This defines an action responsible to set the parent property of the target once triggered.
  54675. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  54676. */
  54677. var SetParentAction = /** @class */ (function (_super) {
  54678. __extends(SetParentAction, _super);
  54679. /**
  54680. * Instantiate the action
  54681. * @param triggerOptions defines the trigger options
  54682. * @param target defines the target containing the parent property
  54683. * @param parent defines from where the animation should start (animation frame)
  54684. * @param condition defines the trigger related conditions
  54685. */
  54686. function SetParentAction(triggerOptions, target, parent, condition) {
  54687. var _this = _super.call(this, triggerOptions, condition) || this;
  54688. _this._target = target;
  54689. _this._parent = parent;
  54690. return _this;
  54691. }
  54692. /** @hidden */
  54693. SetParentAction.prototype._prepare = function () {
  54694. };
  54695. /**
  54696. * Execute the action and set the parent property.
  54697. */
  54698. SetParentAction.prototype.execute = function () {
  54699. if (this._target.parent === this._parent) {
  54700. return;
  54701. }
  54702. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  54703. invertParentWorldMatrix.invert();
  54704. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  54705. this._target.parent = this._parent;
  54706. };
  54707. /**
  54708. * Serializes the actions and its related information.
  54709. * @param parent defines the object to serialize in
  54710. * @returns the serialized object
  54711. */
  54712. SetParentAction.prototype.serialize = function (parent) {
  54713. return _super.prototype._serialize.call(this, {
  54714. name: "SetParentAction",
  54715. properties: [
  54716. BABYLON.Action._GetTargetProperty(this._target),
  54717. BABYLON.Action._GetTargetProperty(this._parent),
  54718. ]
  54719. }, parent);
  54720. };
  54721. return SetParentAction;
  54722. }(BABYLON.Action));
  54723. BABYLON.SetParentAction = SetParentAction;
  54724. })(BABYLON || (BABYLON = {}));
  54725. //# sourceMappingURL=babylon.directActions.js.map
  54726. var BABYLON;
  54727. (function (BABYLON) {
  54728. var SpriteManager = /** @class */ (function () {
  54729. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  54730. if (epsilon === void 0) { epsilon = 0.01; }
  54731. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  54732. this.name = name;
  54733. this.sprites = new Array();
  54734. this.renderingGroupId = 0;
  54735. this.layerMask = 0x0FFFFFFF;
  54736. this.fogEnabled = true;
  54737. this.isPickable = false;
  54738. /**
  54739. * An event triggered when the manager is disposed.
  54740. */
  54741. this.onDisposeObservable = new BABYLON.Observable();
  54742. this._vertexBuffers = {};
  54743. if (!scene._getComponent(BABYLON.SceneComponentConstants.NAME_SPRITE)) {
  54744. scene._addComponent(new BABYLON.SpriteSceneComponent(scene));
  54745. }
  54746. this._capacity = capacity;
  54747. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  54748. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  54749. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  54750. if (cellSize.width && cellSize.height) {
  54751. this.cellWidth = cellSize.width;
  54752. this.cellHeight = cellSize.height;
  54753. }
  54754. else if (cellSize !== undefined) {
  54755. this.cellWidth = cellSize;
  54756. this.cellHeight = cellSize;
  54757. }
  54758. else {
  54759. return;
  54760. }
  54761. this._epsilon = epsilon;
  54762. this._scene = scene;
  54763. this._scene.spriteManagers.push(this);
  54764. var indices = [];
  54765. var index = 0;
  54766. for (var count = 0; count < capacity; count++) {
  54767. indices.push(index);
  54768. indices.push(index + 1);
  54769. indices.push(index + 2);
  54770. indices.push(index);
  54771. indices.push(index + 2);
  54772. indices.push(index + 3);
  54773. index += 4;
  54774. }
  54775. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  54776. // VBO
  54777. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  54778. this._vertexData = new Float32Array(capacity * 16 * 4);
  54779. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  54780. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  54781. var options = this._buffer.createVertexBuffer("options", 4, 4);
  54782. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  54783. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  54784. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  54785. this._vertexBuffers["options"] = options;
  54786. this._vertexBuffers["cellInfo"] = cellInfo;
  54787. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  54788. // Effects
  54789. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  54790. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  54791. }
  54792. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  54793. set: function (callback) {
  54794. if (this._onDisposeObserver) {
  54795. this.onDisposeObservable.remove(this._onDisposeObserver);
  54796. }
  54797. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  54798. },
  54799. enumerable: true,
  54800. configurable: true
  54801. });
  54802. Object.defineProperty(SpriteManager.prototype, "texture", {
  54803. get: function () {
  54804. return this._spriteTexture;
  54805. },
  54806. set: function (value) {
  54807. this._spriteTexture = value;
  54808. },
  54809. enumerable: true,
  54810. configurable: true
  54811. });
  54812. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  54813. var arrayOffset = index * 16;
  54814. if (offsetX === 0)
  54815. offsetX = this._epsilon;
  54816. else if (offsetX === 1)
  54817. offsetX = 1 - this._epsilon;
  54818. if (offsetY === 0)
  54819. offsetY = this._epsilon;
  54820. else if (offsetY === 1)
  54821. offsetY = 1 - this._epsilon;
  54822. this._vertexData[arrayOffset] = sprite.position.x;
  54823. this._vertexData[arrayOffset + 1] = sprite.position.y;
  54824. this._vertexData[arrayOffset + 2] = sprite.position.z;
  54825. this._vertexData[arrayOffset + 3] = sprite.angle;
  54826. this._vertexData[arrayOffset + 4] = sprite.width;
  54827. this._vertexData[arrayOffset + 5] = sprite.height;
  54828. this._vertexData[arrayOffset + 6] = offsetX;
  54829. this._vertexData[arrayOffset + 7] = offsetY;
  54830. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  54831. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  54832. var offset = (sprite.cellIndex / rowSize) >> 0;
  54833. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  54834. this._vertexData[arrayOffset + 11] = offset;
  54835. // Color
  54836. this._vertexData[arrayOffset + 12] = sprite.color.r;
  54837. this._vertexData[arrayOffset + 13] = sprite.color.g;
  54838. this._vertexData[arrayOffset + 14] = sprite.color.b;
  54839. this._vertexData[arrayOffset + 15] = sprite.color.a;
  54840. };
  54841. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  54842. var count = Math.min(this._capacity, this.sprites.length);
  54843. var min = BABYLON.Vector3.Zero();
  54844. var max = BABYLON.Vector3.Zero();
  54845. var distance = Number.MAX_VALUE;
  54846. var currentSprite = null;
  54847. var cameraSpacePosition = BABYLON.Vector3.Zero();
  54848. var cameraView = camera.getViewMatrix();
  54849. for (var index = 0; index < count; index++) {
  54850. var sprite = this.sprites[index];
  54851. if (!sprite) {
  54852. continue;
  54853. }
  54854. if (predicate) {
  54855. if (!predicate(sprite)) {
  54856. continue;
  54857. }
  54858. }
  54859. else if (!sprite.isPickable) {
  54860. continue;
  54861. }
  54862. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  54863. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  54864. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  54865. if (ray.intersectsBoxMinMax(min, max)) {
  54866. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  54867. if (distance > currentDistance) {
  54868. distance = currentDistance;
  54869. currentSprite = sprite;
  54870. if (fastCheck) {
  54871. break;
  54872. }
  54873. }
  54874. }
  54875. }
  54876. if (currentSprite) {
  54877. var result = new BABYLON.PickingInfo();
  54878. result.hit = true;
  54879. result.pickedSprite = currentSprite;
  54880. result.distance = distance;
  54881. return result;
  54882. }
  54883. return null;
  54884. };
  54885. SpriteManager.prototype.render = function () {
  54886. // Check
  54887. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  54888. return;
  54889. var engine = this._scene.getEngine();
  54890. var baseSize = this._spriteTexture.getBaseSize();
  54891. // Sprites
  54892. var deltaTime = engine.getDeltaTime();
  54893. var max = Math.min(this._capacity, this.sprites.length);
  54894. var rowSize = baseSize.width / this.cellWidth;
  54895. var offset = 0;
  54896. for (var index = 0; index < max; index++) {
  54897. var sprite = this.sprites[index];
  54898. if (!sprite || !sprite.isVisible) {
  54899. continue;
  54900. }
  54901. sprite._animate(deltaTime);
  54902. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  54903. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  54904. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  54905. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  54906. }
  54907. this._buffer.update(this._vertexData);
  54908. // Render
  54909. var effect = this._effectBase;
  54910. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  54911. effect = this._effectFog;
  54912. }
  54913. engine.enableEffect(effect);
  54914. var viewMatrix = this._scene.getViewMatrix();
  54915. effect.setTexture("diffuseSampler", this._spriteTexture);
  54916. effect.setMatrix("view", viewMatrix);
  54917. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  54918. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  54919. // Fog
  54920. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  54921. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  54922. effect.setColor3("vFogColor", this._scene.fogColor);
  54923. }
  54924. // VBOs
  54925. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  54926. // Draw order
  54927. engine.setDepthFunctionToLessOrEqual();
  54928. effect.setBool("alphaTest", true);
  54929. engine.setColorWrite(false);
  54930. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, (offset / 4) * 6);
  54931. engine.setColorWrite(true);
  54932. effect.setBool("alphaTest", false);
  54933. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  54934. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, (offset / 4) * 6);
  54935. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  54936. };
  54937. SpriteManager.prototype.dispose = function () {
  54938. if (this._buffer) {
  54939. this._buffer.dispose();
  54940. this._buffer = null;
  54941. }
  54942. if (this._indexBuffer) {
  54943. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  54944. this._indexBuffer = null;
  54945. }
  54946. if (this._spriteTexture) {
  54947. this._spriteTexture.dispose();
  54948. this._spriteTexture = null;
  54949. }
  54950. // Remove from scene
  54951. var index = this._scene.spriteManagers.indexOf(this);
  54952. this._scene.spriteManagers.splice(index, 1);
  54953. // Callback
  54954. this.onDisposeObservable.notifyObservers(this);
  54955. this.onDisposeObservable.clear();
  54956. };
  54957. return SpriteManager;
  54958. }());
  54959. BABYLON.SpriteManager = SpriteManager;
  54960. })(BABYLON || (BABYLON = {}));
  54961. //# sourceMappingURL=babylon.spriteManager.js.map
  54962. var BABYLON;
  54963. (function (BABYLON) {
  54964. var Sprite = /** @class */ (function () {
  54965. function Sprite(name, manager) {
  54966. this.name = name;
  54967. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  54968. this.width = 1.0;
  54969. this.height = 1.0;
  54970. this.angle = 0;
  54971. this.cellIndex = 0;
  54972. this.invertU = 0;
  54973. this.invertV = 0;
  54974. this.animations = new Array();
  54975. this.isPickable = false;
  54976. this._animationStarted = false;
  54977. this._loopAnimation = false;
  54978. this._fromIndex = 0;
  54979. this._toIndex = 0;
  54980. this._delay = 0;
  54981. this._direction = 1;
  54982. this._time = 0;
  54983. /**
  54984. * Gets or sets a boolean indicating if the sprite is visible (renderable). Default is true
  54985. */
  54986. this.isVisible = true;
  54987. this._manager = manager;
  54988. this._manager.sprites.push(this);
  54989. this.position = BABYLON.Vector3.Zero();
  54990. }
  54991. Object.defineProperty(Sprite.prototype, "size", {
  54992. get: function () {
  54993. return this.width;
  54994. },
  54995. set: function (value) {
  54996. this.width = value;
  54997. this.height = value;
  54998. },
  54999. enumerable: true,
  55000. configurable: true
  55001. });
  55002. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  55003. this._fromIndex = from;
  55004. this._toIndex = to;
  55005. this._loopAnimation = loop;
  55006. this._delay = delay;
  55007. this._animationStarted = true;
  55008. this._direction = from < to ? 1 : -1;
  55009. this.cellIndex = from;
  55010. this._time = 0;
  55011. this._onAnimationEnd = onAnimationEnd;
  55012. };
  55013. Sprite.prototype.stopAnimation = function () {
  55014. this._animationStarted = false;
  55015. };
  55016. /** @hidden */
  55017. Sprite.prototype._animate = function (deltaTime) {
  55018. if (!this._animationStarted)
  55019. return;
  55020. this._time += deltaTime;
  55021. if (this._time > this._delay) {
  55022. this._time = this._time % this._delay;
  55023. this.cellIndex += this._direction;
  55024. if (this.cellIndex > this._toIndex) {
  55025. if (this._loopAnimation) {
  55026. this.cellIndex = this._fromIndex;
  55027. }
  55028. else {
  55029. this.cellIndex = this._toIndex;
  55030. this._animationStarted = false;
  55031. if (this._onAnimationEnd) {
  55032. this._onAnimationEnd();
  55033. }
  55034. if (this.disposeWhenFinishedAnimating) {
  55035. this.dispose();
  55036. }
  55037. }
  55038. }
  55039. }
  55040. };
  55041. Sprite.prototype.dispose = function () {
  55042. for (var i = 0; i < this._manager.sprites.length; i++) {
  55043. if (this._manager.sprites[i] == this) {
  55044. this._manager.sprites.splice(i, 1);
  55045. }
  55046. }
  55047. };
  55048. return Sprite;
  55049. }());
  55050. BABYLON.Sprite = Sprite;
  55051. })(BABYLON || (BABYLON = {}));
  55052. //# sourceMappingURL=babylon.sprite.js.map
  55053. var BABYLON;
  55054. (function (BABYLON) {
  55055. BABYLON.Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  55056. if (!BABYLON.PickingInfo) {
  55057. return null;
  55058. }
  55059. var pickingInfo = null;
  55060. if (!camera) {
  55061. if (!this.activeCamera) {
  55062. return null;
  55063. }
  55064. camera = this.activeCamera;
  55065. }
  55066. if (this.spriteManagers.length > 0) {
  55067. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  55068. var spriteManager = this.spriteManagers[spriteIndex];
  55069. if (!spriteManager.isPickable) {
  55070. continue;
  55071. }
  55072. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  55073. if (!result || !result.hit)
  55074. continue;
  55075. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  55076. continue;
  55077. pickingInfo = result;
  55078. if (fastCheck) {
  55079. break;
  55080. }
  55081. }
  55082. }
  55083. return pickingInfo || new BABYLON.PickingInfo();
  55084. };
  55085. BABYLON.Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  55086. this.createPickingRayInCameraSpaceToRef(x, y, this._tempSpritePickingRay, camera);
  55087. return this._internalPickSprites(this._tempSpritePickingRay, predicate, fastCheck, camera);
  55088. };
  55089. BABYLON.Scene.prototype.pickSpriteWithRay = function (ray, predicate, fastCheck, camera) {
  55090. if (!this._tempSpritePickingRay) {
  55091. return null;
  55092. }
  55093. if (!camera) {
  55094. if (!this.activeCamera) {
  55095. return null;
  55096. }
  55097. camera = this.activeCamera;
  55098. }
  55099. BABYLON.Ray.TransformToRef(ray, camera.getViewMatrix(), this._tempSpritePickingRay);
  55100. return this._internalPickSprites(this._tempSpritePickingRay, predicate, fastCheck, camera);
  55101. };
  55102. BABYLON.Scene.prototype.setPointerOverSprite = function (sprite) {
  55103. if (this._pointerOverSprite === sprite) {
  55104. return;
  55105. }
  55106. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  55107. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  55108. }
  55109. this._pointerOverSprite = sprite;
  55110. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  55111. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  55112. }
  55113. };
  55114. BABYLON.Scene.prototype.getPointerOverSprite = function () {
  55115. return this._pointerOverSprite;
  55116. };
  55117. /**
  55118. * Defines the sprite scene component responsible to manage sprites
  55119. * in a given scene.
  55120. */
  55121. var SpriteSceneComponent = /** @class */ (function () {
  55122. /**
  55123. * Creates a new instance of the component for the given scene
  55124. * @param scene Defines the scene to register the component in
  55125. */
  55126. function SpriteSceneComponent(scene) {
  55127. /**
  55128. * The component name helpfull to identify the component in the list of scene components.
  55129. */
  55130. this.name = BABYLON.SceneComponentConstants.NAME_SPRITE;
  55131. this.scene = scene;
  55132. this.scene.spriteManagers = new Array();
  55133. this.scene._tempSpritePickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  55134. this.scene.onBeforeSpritesRenderingObservable = new BABYLON.Observable();
  55135. this.scene.onAfterSpritesRenderingObservable = new BABYLON.Observable();
  55136. this._spritePredicate = function (sprite) {
  55137. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  55138. };
  55139. }
  55140. /**
  55141. * Registers the component in a given scene
  55142. */
  55143. SpriteSceneComponent.prototype.register = function () {
  55144. this.scene._pointerMoveStage.registerStep(BABYLON.SceneComponentConstants.STEP_POINTERMOVE_SPRITE, this, this._pointerMove);
  55145. this.scene._pointerDownStage.registerStep(BABYLON.SceneComponentConstants.STEP_POINTERDOWN_SPRITE, this, this._pointerDown);
  55146. this.scene._pointerUpStage.registerStep(BABYLON.SceneComponentConstants.STEP_POINTERUP_SPRITE, this, this._pointerUp);
  55147. };
  55148. /**
  55149. * Rebuilds the elements related to this component in case of
  55150. * context lost for instance.
  55151. */
  55152. SpriteSceneComponent.prototype.rebuild = function () {
  55153. /** Nothing to do for sprites */
  55154. };
  55155. /**
  55156. * Disposes the component and the associated ressources.
  55157. */
  55158. SpriteSceneComponent.prototype.dispose = function () {
  55159. this.scene.onBeforeSpritesRenderingObservable.clear();
  55160. this.scene.onAfterSpritesRenderingObservable.clear();
  55161. var spriteManagers = this.scene.spriteManagers;
  55162. while (spriteManagers.length) {
  55163. spriteManagers[0].dispose();
  55164. }
  55165. };
  55166. SpriteSceneComponent.prototype._pickSpriteButKeepRay = function (originalPointerInfo, x, y, fastCheck, camera) {
  55167. var result = this.scene.pickSprite(x, y, this._spritePredicate, fastCheck, camera);
  55168. if (result) {
  55169. result.ray = originalPointerInfo ? originalPointerInfo.ray : null;
  55170. }
  55171. return result;
  55172. };
  55173. SpriteSceneComponent.prototype._pointerMove = function (unTranslatedPointerX, unTranslatedPointerY, pickResult, isMeshPicked, canvas) {
  55174. var scene = this.scene;
  55175. if (isMeshPicked) {
  55176. scene.setPointerOverSprite(null);
  55177. }
  55178. else {
  55179. pickResult = this._pickSpriteButKeepRay(pickResult, unTranslatedPointerX, unTranslatedPointerY, false, scene.cameraToUseForPointers || undefined);
  55180. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  55181. scene.setPointerOverSprite(pickResult.pickedSprite);
  55182. if (scene._pointerOverSprite && scene._pointerOverSprite.actionManager && scene._pointerOverSprite.actionManager.hoverCursor) {
  55183. canvas.style.cursor = scene._pointerOverSprite.actionManager.hoverCursor;
  55184. }
  55185. else {
  55186. canvas.style.cursor = scene.hoverCursor;
  55187. }
  55188. }
  55189. else {
  55190. scene.setPointerOverSprite(null);
  55191. }
  55192. }
  55193. return pickResult;
  55194. };
  55195. SpriteSceneComponent.prototype._pointerDown = function (unTranslatedPointerX, unTranslatedPointerY, pickResult, evt) {
  55196. var scene = this.scene;
  55197. scene._pickedDownSprite = null;
  55198. if (scene.spriteManagers.length > 0) {
  55199. pickResult = scene.pickSprite(unTranslatedPointerX, unTranslatedPointerY, this._spritePredicate, false, scene.cameraToUseForPointers || undefined);
  55200. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  55201. if (pickResult.pickedSprite.actionManager) {
  55202. scene._pickedDownSprite = pickResult.pickedSprite;
  55203. switch (evt.button) {
  55204. case 0:
  55205. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, scene, evt));
  55206. break;
  55207. case 1:
  55208. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, scene, evt));
  55209. break;
  55210. case 2:
  55211. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, scene, evt));
  55212. break;
  55213. }
  55214. if (pickResult.pickedSprite.actionManager) {
  55215. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, scene, evt));
  55216. }
  55217. }
  55218. }
  55219. }
  55220. return pickResult;
  55221. };
  55222. SpriteSceneComponent.prototype._pointerUp = function (unTranslatedPointerX, unTranslatedPointerY, pickResult, evt) {
  55223. var scene = this.scene;
  55224. if (scene.spriteManagers.length > 0) {
  55225. var spritePickResult = scene.pickSprite(unTranslatedPointerX, unTranslatedPointerY, this._spritePredicate, false, scene.cameraToUseForPointers || undefined);
  55226. if (spritePickResult) {
  55227. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  55228. if (spritePickResult.pickedSprite.actionManager) {
  55229. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, scene, evt));
  55230. if (spritePickResult.pickedSprite.actionManager) {
  55231. if (!this.scene._isPointerSwiping()) {
  55232. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, scene, evt));
  55233. }
  55234. }
  55235. }
  55236. }
  55237. if (scene._pickedDownSprite && scene._pickedDownSprite.actionManager && scene._pickedDownSprite !== spritePickResult.pickedSprite) {
  55238. scene._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(scene._pickedDownSprite, scene, evt));
  55239. }
  55240. }
  55241. }
  55242. return pickResult;
  55243. };
  55244. return SpriteSceneComponent;
  55245. }());
  55246. BABYLON.SpriteSceneComponent = SpriteSceneComponent;
  55247. })(BABYLON || (BABYLON = {}));
  55248. //# sourceMappingURL=babylon.spriteSceneComponent.js.map
  55249. var BABYLON;
  55250. (function (BABYLON) {
  55251. /**
  55252. * @hidden
  55253. */
  55254. var IntersectionInfo = /** @class */ (function () {
  55255. function IntersectionInfo(bu, bv, distance) {
  55256. this.bu = bu;
  55257. this.bv = bv;
  55258. this.distance = distance;
  55259. this.faceId = 0;
  55260. this.subMeshId = 0;
  55261. }
  55262. return IntersectionInfo;
  55263. }());
  55264. BABYLON.IntersectionInfo = IntersectionInfo;
  55265. /**
  55266. * Information about the result of picking within a scene
  55267. * @see https://doc.babylonjs.com/babylon101/picking_collisions
  55268. */
  55269. var PickingInfo = /** @class */ (function () {
  55270. function PickingInfo() {
  55271. /**
  55272. * If the pick collided with an object
  55273. */
  55274. this.hit = false;
  55275. /**
  55276. * Distance away where the pick collided
  55277. */
  55278. this.distance = 0;
  55279. /**
  55280. * The location of pick collision
  55281. */
  55282. this.pickedPoint = null;
  55283. /**
  55284. * The mesh corresponding the the pick collision
  55285. */
  55286. this.pickedMesh = null;
  55287. /** (See getTextureCoordinates) The barycentric U coordinate that is used when calulating the texture coordinates of the collision.*/
  55288. this.bu = 0;
  55289. /** (See getTextureCoordinates) The barycentric V coordinate that is used when calulating the texture coordinates of the collision.*/
  55290. this.bv = 0;
  55291. /** The id of the face on the mesh that was picked */
  55292. this.faceId = -1;
  55293. /** Id of the the submesh that was picked */
  55294. this.subMeshId = 0;
  55295. /** If a sprite was picked, this will be the sprite the pick collided with */
  55296. this.pickedSprite = null;
  55297. /**
  55298. * If a mesh was used to do the picking (eg. 6dof controller) this will be populated.
  55299. */
  55300. this.originMesh = null;
  55301. /**
  55302. * The ray that was used to perform the picking.
  55303. */
  55304. this.ray = null;
  55305. }
  55306. /**
  55307. * Gets the normal correspodning to the face the pick collided with
  55308. * @param useWorldCoordinates If the resulting normal should be relative to the world (default: false)
  55309. * @param useVerticesNormals If the vertices normals should be used to calculate the normal instead of the normal map
  55310. * @returns The normal correspodning to the face the pick collided with
  55311. */
  55312. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  55313. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  55314. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  55315. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  55316. return null;
  55317. }
  55318. var indices = this.pickedMesh.getIndices();
  55319. if (!indices) {
  55320. return null;
  55321. }
  55322. var result;
  55323. if (useVerticesNormals) {
  55324. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  55325. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  55326. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  55327. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  55328. normal0 = normal0.scale(this.bu);
  55329. normal1 = normal1.scale(this.bv);
  55330. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  55331. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  55332. }
  55333. else {
  55334. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  55335. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  55336. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  55337. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  55338. var p1p2 = vertex1.subtract(vertex2);
  55339. var p3p2 = vertex3.subtract(vertex2);
  55340. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  55341. }
  55342. if (useWorldCoordinates) {
  55343. var wm = this.pickedMesh.getWorldMatrix();
  55344. if (this.pickedMesh.nonUniformScaling) {
  55345. BABYLON.Tmp.Matrix[0].copyFrom(wm);
  55346. wm = BABYLON.Tmp.Matrix[0];
  55347. wm.setTranslationFromFloats(0, 0, 0);
  55348. wm.invert();
  55349. wm.transposeToRef(BABYLON.Tmp.Matrix[1]);
  55350. wm = BABYLON.Tmp.Matrix[1];
  55351. }
  55352. result = BABYLON.Vector3.TransformNormal(result, wm);
  55353. }
  55354. result.normalize();
  55355. return result;
  55356. };
  55357. /**
  55358. * Gets the texture coordinates of where the pick occured
  55359. * @returns the vector containing the coordnates of the texture
  55360. */
  55361. PickingInfo.prototype.getTextureCoordinates = function () {
  55362. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  55363. return null;
  55364. }
  55365. var indices = this.pickedMesh.getIndices();
  55366. if (!indices) {
  55367. return null;
  55368. }
  55369. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  55370. if (!uvs) {
  55371. return null;
  55372. }
  55373. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  55374. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  55375. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  55376. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  55377. uv1 = uv1.scale(this.bu);
  55378. uv2 = uv2.scale(this.bv);
  55379. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  55380. };
  55381. return PickingInfo;
  55382. }());
  55383. BABYLON.PickingInfo = PickingInfo;
  55384. })(BABYLON || (BABYLON = {}));
  55385. //# sourceMappingURL=babylon.pickingInfo.js.map
  55386. var BABYLON;
  55387. (function (BABYLON) {
  55388. var Ray = /** @class */ (function () {
  55389. function Ray(origin, direction, length) {
  55390. if (length === void 0) { length = Number.MAX_VALUE; }
  55391. this.origin = origin;
  55392. this.direction = direction;
  55393. this.length = length;
  55394. }
  55395. // Methods
  55396. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  55397. var d = 0.0;
  55398. var maxValue = Number.MAX_VALUE;
  55399. var inv;
  55400. var min;
  55401. var max;
  55402. var temp;
  55403. if (Math.abs(this.direction.x) < 0.0000001) {
  55404. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  55405. return false;
  55406. }
  55407. }
  55408. else {
  55409. inv = 1.0 / this.direction.x;
  55410. min = (minimum.x - this.origin.x) * inv;
  55411. max = (maximum.x - this.origin.x) * inv;
  55412. if (max === -Infinity) {
  55413. max = Infinity;
  55414. }
  55415. if (min > max) {
  55416. temp = min;
  55417. min = max;
  55418. max = temp;
  55419. }
  55420. d = Math.max(min, d);
  55421. maxValue = Math.min(max, maxValue);
  55422. if (d > maxValue) {
  55423. return false;
  55424. }
  55425. }
  55426. if (Math.abs(this.direction.y) < 0.0000001) {
  55427. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  55428. return false;
  55429. }
  55430. }
  55431. else {
  55432. inv = 1.0 / this.direction.y;
  55433. min = (minimum.y - this.origin.y) * inv;
  55434. max = (maximum.y - this.origin.y) * inv;
  55435. if (max === -Infinity) {
  55436. max = Infinity;
  55437. }
  55438. if (min > max) {
  55439. temp = min;
  55440. min = max;
  55441. max = temp;
  55442. }
  55443. d = Math.max(min, d);
  55444. maxValue = Math.min(max, maxValue);
  55445. if (d > maxValue) {
  55446. return false;
  55447. }
  55448. }
  55449. if (Math.abs(this.direction.z) < 0.0000001) {
  55450. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  55451. return false;
  55452. }
  55453. }
  55454. else {
  55455. inv = 1.0 / this.direction.z;
  55456. min = (minimum.z - this.origin.z) * inv;
  55457. max = (maximum.z - this.origin.z) * inv;
  55458. if (max === -Infinity) {
  55459. max = Infinity;
  55460. }
  55461. if (min > max) {
  55462. temp = min;
  55463. min = max;
  55464. max = temp;
  55465. }
  55466. d = Math.max(min, d);
  55467. maxValue = Math.min(max, maxValue);
  55468. if (d > maxValue) {
  55469. return false;
  55470. }
  55471. }
  55472. return true;
  55473. };
  55474. Ray.prototype.intersectsBox = function (box) {
  55475. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  55476. };
  55477. Ray.prototype.intersectsSphere = function (sphere) {
  55478. var x = sphere.center.x - this.origin.x;
  55479. var y = sphere.center.y - this.origin.y;
  55480. var z = sphere.center.z - this.origin.z;
  55481. var pyth = (x * x) + (y * y) + (z * z);
  55482. var rr = sphere.radius * sphere.radius;
  55483. if (pyth <= rr) {
  55484. return true;
  55485. }
  55486. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  55487. if (dot < 0.0) {
  55488. return false;
  55489. }
  55490. var temp = pyth - (dot * dot);
  55491. return temp <= rr;
  55492. };
  55493. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  55494. if (!this._edge1) {
  55495. this._edge1 = BABYLON.Vector3.Zero();
  55496. this._edge2 = BABYLON.Vector3.Zero();
  55497. this._pvec = BABYLON.Vector3.Zero();
  55498. this._tvec = BABYLON.Vector3.Zero();
  55499. this._qvec = BABYLON.Vector3.Zero();
  55500. }
  55501. vertex1.subtractToRef(vertex0, this._edge1);
  55502. vertex2.subtractToRef(vertex0, this._edge2);
  55503. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  55504. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  55505. if (det === 0) {
  55506. return null;
  55507. }
  55508. var invdet = 1 / det;
  55509. this.origin.subtractToRef(vertex0, this._tvec);
  55510. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  55511. if (bu < 0 || bu > 1.0) {
  55512. return null;
  55513. }
  55514. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  55515. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  55516. if (bv < 0 || bu + bv > 1.0) {
  55517. return null;
  55518. }
  55519. //check if the distance is longer than the predefined length.
  55520. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  55521. if (distance > this.length) {
  55522. return null;
  55523. }
  55524. return new BABYLON.IntersectionInfo(bu, bv, distance);
  55525. };
  55526. Ray.prototype.intersectsPlane = function (plane) {
  55527. var distance;
  55528. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  55529. if (Math.abs(result1) < 9.99999997475243E-07) {
  55530. return null;
  55531. }
  55532. else {
  55533. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  55534. distance = (-plane.d - result2) / result1;
  55535. if (distance < 0.0) {
  55536. if (distance < -9.99999997475243E-07) {
  55537. return null;
  55538. }
  55539. else {
  55540. return 0;
  55541. }
  55542. }
  55543. return distance;
  55544. }
  55545. };
  55546. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  55547. var tm = BABYLON.Tmp.Matrix[0];
  55548. mesh.getWorldMatrix().invertToRef(tm);
  55549. if (this._tmpRay) {
  55550. Ray.TransformToRef(this, tm, this._tmpRay);
  55551. }
  55552. else {
  55553. this._tmpRay = Ray.Transform(this, tm);
  55554. }
  55555. return mesh.intersects(this._tmpRay, fastCheck);
  55556. };
  55557. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  55558. if (results) {
  55559. results.length = 0;
  55560. }
  55561. else {
  55562. results = [];
  55563. }
  55564. for (var i = 0; i < meshes.length; i++) {
  55565. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  55566. if (pickInfo.hit) {
  55567. results.push(pickInfo);
  55568. }
  55569. }
  55570. results.sort(this._comparePickingInfo);
  55571. return results;
  55572. };
  55573. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  55574. if (pickingInfoA.distance < pickingInfoB.distance) {
  55575. return -1;
  55576. }
  55577. else if (pickingInfoA.distance > pickingInfoB.distance) {
  55578. return 1;
  55579. }
  55580. else {
  55581. return 0;
  55582. }
  55583. };
  55584. /**
  55585. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  55586. * @param sega the first point of the segment to test the intersection against
  55587. * @param segb the second point of the segment to test the intersection against
  55588. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  55589. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  55590. */
  55591. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  55592. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  55593. var u = segb.subtract(sega);
  55594. var v = rsegb.subtract(this.origin);
  55595. var w = sega.subtract(this.origin);
  55596. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  55597. var b = BABYLON.Vector3.Dot(u, v);
  55598. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  55599. var d = BABYLON.Vector3.Dot(u, w);
  55600. var e = BABYLON.Vector3.Dot(v, w);
  55601. var D = a * c - b * b; // always >= 0
  55602. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  55603. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  55604. // compute the line parameters of the two closest points
  55605. if (D < Ray.smallnum) { // the lines are almost parallel
  55606. sN = 0.0; // force using point P0 on segment S1
  55607. sD = 1.0; // to prevent possible division by 0.0 later
  55608. tN = e;
  55609. tD = c;
  55610. }
  55611. else { // get the closest points on the infinite lines
  55612. sN = (b * e - c * d);
  55613. tN = (a * e - b * d);
  55614. if (sN < 0.0) { // sc < 0 => the s=0 edge is visible
  55615. sN = 0.0;
  55616. tN = e;
  55617. tD = c;
  55618. }
  55619. else if (sN > sD) { // sc > 1 => the s=1 edge is visible
  55620. sN = sD;
  55621. tN = e + b;
  55622. tD = c;
  55623. }
  55624. }
  55625. if (tN < 0.0) { // tc < 0 => the t=0 edge is visible
  55626. tN = 0.0;
  55627. // recompute sc for this edge
  55628. if (-d < 0.0) {
  55629. sN = 0.0;
  55630. }
  55631. else if (-d > a)
  55632. sN = sD;
  55633. else {
  55634. sN = -d;
  55635. sD = a;
  55636. }
  55637. }
  55638. else if (tN > tD) { // tc > 1 => the t=1 edge is visible
  55639. tN = tD;
  55640. // recompute sc for this edge
  55641. if ((-d + b) < 0.0) {
  55642. sN = 0;
  55643. }
  55644. else if ((-d + b) > a) {
  55645. sN = sD;
  55646. }
  55647. else {
  55648. sN = (-d + b);
  55649. sD = a;
  55650. }
  55651. }
  55652. // finally do the division to get sc and tc
  55653. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  55654. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  55655. // get the difference of the two closest points
  55656. var qtc = v.multiplyByFloats(tc, tc, tc);
  55657. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  55658. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  55659. if (isIntersected) {
  55660. return qtc.length();
  55661. }
  55662. return -1;
  55663. };
  55664. Ray.prototype.update = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  55665. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 0, viewportWidth, viewportHeight, world, view, projection, this.origin);
  55666. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 1, viewportWidth, viewportHeight, world, view, projection, BABYLON.Tmp.Vector3[0]);
  55667. BABYLON.Tmp.Vector3[0].subtractToRef(this.origin, this.direction);
  55668. this.direction.normalize();
  55669. return this;
  55670. };
  55671. // Statics
  55672. Ray.Zero = function () {
  55673. return new Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero());
  55674. };
  55675. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  55676. var result = Ray.Zero();
  55677. return result.update(x, y, viewportWidth, viewportHeight, world, view, projection);
  55678. };
  55679. /**
  55680. * 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
  55681. * transformed to the given world matrix.
  55682. * @param origin The origin point
  55683. * @param end The end point
  55684. * @param world a matrix to transform the ray to. Default is the identity matrix.
  55685. */
  55686. Ray.CreateNewFromTo = function (origin, end, world) {
  55687. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  55688. var direction = end.subtract(origin);
  55689. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  55690. direction.normalize();
  55691. return Ray.Transform(new Ray(origin, direction, length), world);
  55692. };
  55693. Ray.Transform = function (ray, matrix) {
  55694. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  55695. Ray.TransformToRef(ray, matrix, result);
  55696. return result;
  55697. };
  55698. Ray.TransformToRef = function (ray, matrix, result) {
  55699. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  55700. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  55701. result.length = ray.length;
  55702. var dir = result.direction;
  55703. var len = dir.length();
  55704. if (!(len === 0 || len === 1)) {
  55705. var num = 1.0 / len;
  55706. dir.x *= num;
  55707. dir.y *= num;
  55708. dir.z *= num;
  55709. result.length *= len;
  55710. }
  55711. };
  55712. Ray.smallnum = 0.00000001;
  55713. Ray.rayl = 10e8;
  55714. return Ray;
  55715. }());
  55716. BABYLON.Ray = Ray;
  55717. })(BABYLON || (BABYLON = {}));
  55718. //# sourceMappingURL=babylon.ray.js.map
  55719. var BABYLON;
  55720. (function (BABYLON) {
  55721. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  55722. if (boxMin.x > sphereCenter.x + sphereRadius)
  55723. return false;
  55724. if (sphereCenter.x - sphereRadius > boxMax.x)
  55725. return false;
  55726. if (boxMin.y > sphereCenter.y + sphereRadius)
  55727. return false;
  55728. if (sphereCenter.y - sphereRadius > boxMax.y)
  55729. return false;
  55730. if (boxMin.z > sphereCenter.z + sphereRadius)
  55731. return false;
  55732. if (sphereCenter.z - sphereRadius > boxMax.z)
  55733. return false;
  55734. return true;
  55735. };
  55736. var getLowestRoot = (function () {
  55737. var result = { root: 0, found: false };
  55738. return function (a, b, c, maxR) {
  55739. result.root = 0;
  55740. result.found = false;
  55741. var determinant = b * b - 4.0 * a * c;
  55742. if (determinant < 0)
  55743. return result;
  55744. var sqrtD = Math.sqrt(determinant);
  55745. var r1 = (-b - sqrtD) / (2.0 * a);
  55746. var r2 = (-b + sqrtD) / (2.0 * a);
  55747. if (r1 > r2) {
  55748. var temp = r2;
  55749. r2 = r1;
  55750. r1 = temp;
  55751. }
  55752. if (r1 > 0 && r1 < maxR) {
  55753. result.root = r1;
  55754. result.found = true;
  55755. return result;
  55756. }
  55757. if (r2 > 0 && r2 < maxR) {
  55758. result.root = r2;
  55759. result.found = true;
  55760. return result;
  55761. }
  55762. return result;
  55763. };
  55764. })();
  55765. /** @hidden */
  55766. var Collider = /** @class */ (function () {
  55767. function Collider() {
  55768. this._collisionPoint = BABYLON.Vector3.Zero();
  55769. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  55770. this._tempVector = BABYLON.Vector3.Zero();
  55771. this._tempVector2 = BABYLON.Vector3.Zero();
  55772. this._tempVector3 = BABYLON.Vector3.Zero();
  55773. this._tempVector4 = BABYLON.Vector3.Zero();
  55774. this._edge = BABYLON.Vector3.Zero();
  55775. this._baseToVertex = BABYLON.Vector3.Zero();
  55776. this._destinationPoint = BABYLON.Vector3.Zero();
  55777. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  55778. this._displacementVector = BABYLON.Vector3.Zero();
  55779. /** @hidden */
  55780. this._radius = BABYLON.Vector3.One();
  55781. /** @hidden */
  55782. this._retry = 0;
  55783. /** @hidden */
  55784. this._basePointWorld = BABYLON.Vector3.Zero();
  55785. this._velocityWorld = BABYLON.Vector3.Zero();
  55786. this._normalizedVelocity = BABYLON.Vector3.Zero();
  55787. this._collisionMask = -1;
  55788. }
  55789. Object.defineProperty(Collider.prototype, "collisionMask", {
  55790. get: function () {
  55791. return this._collisionMask;
  55792. },
  55793. set: function (mask) {
  55794. this._collisionMask = !isNaN(mask) ? mask : -1;
  55795. },
  55796. enumerable: true,
  55797. configurable: true
  55798. });
  55799. Object.defineProperty(Collider.prototype, "slidePlaneNormal", {
  55800. /**
  55801. * Gets the plane normal used to compute the sliding response (in local space)
  55802. */
  55803. get: function () {
  55804. return this._slidePlaneNormal;
  55805. },
  55806. enumerable: true,
  55807. configurable: true
  55808. });
  55809. // Methods
  55810. /** @hidden */
  55811. Collider.prototype._initialize = function (source, dir, e) {
  55812. this._velocity = dir;
  55813. BABYLON.Vector3.NormalizeToRef(dir, this._normalizedVelocity);
  55814. this._basePoint = source;
  55815. source.multiplyToRef(this._radius, this._basePointWorld);
  55816. dir.multiplyToRef(this._radius, this._velocityWorld);
  55817. this._velocityWorldLength = this._velocityWorld.length();
  55818. this._epsilon = e;
  55819. this.collisionFound = false;
  55820. };
  55821. /** @hidden */
  55822. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  55823. pa.subtractToRef(point, this._tempVector);
  55824. pb.subtractToRef(point, this._tempVector2);
  55825. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  55826. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  55827. if (d < 0)
  55828. return false;
  55829. pc.subtractToRef(point, this._tempVector3);
  55830. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  55831. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  55832. if (d < 0)
  55833. return false;
  55834. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  55835. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  55836. return d >= 0;
  55837. };
  55838. /** @hidden */
  55839. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  55840. var distance = BABYLON.Vector3.Distance(this._basePointWorld, sphereCenter);
  55841. var max = Math.max(this._radius.x, this._radius.y, this._radius.z);
  55842. if (distance > this._velocityWorldLength + max + sphereRadius) {
  55843. return false;
  55844. }
  55845. if (!intersectBoxAASphere(vecMin, vecMax, this._basePointWorld, this._velocityWorldLength + max))
  55846. return false;
  55847. return true;
  55848. };
  55849. /** @hidden */
  55850. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  55851. var t0;
  55852. var embeddedInPlane = false;
  55853. //defensive programming, actually not needed.
  55854. if (!trianglePlaneArray) {
  55855. trianglePlaneArray = [];
  55856. }
  55857. if (!trianglePlaneArray[faceIndex]) {
  55858. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  55859. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  55860. }
  55861. var trianglePlane = trianglePlaneArray[faceIndex];
  55862. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this._normalizedVelocity, 0))
  55863. return;
  55864. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this._basePoint);
  55865. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this._velocity);
  55866. if (normalDotVelocity == 0) {
  55867. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  55868. return;
  55869. embeddedInPlane = true;
  55870. t0 = 0;
  55871. }
  55872. else {
  55873. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  55874. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  55875. if (t0 > t1) {
  55876. var temp = t1;
  55877. t1 = t0;
  55878. t0 = temp;
  55879. }
  55880. if (t0 > 1.0 || t1 < 0.0)
  55881. return;
  55882. if (t0 < 0)
  55883. t0 = 0;
  55884. if (t0 > 1.0)
  55885. t0 = 1.0;
  55886. }
  55887. this._collisionPoint.copyFromFloats(0, 0, 0);
  55888. var found = false;
  55889. var t = 1.0;
  55890. if (!embeddedInPlane) {
  55891. this._basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  55892. this._velocity.scaleToRef(t0, this._tempVector);
  55893. this._planeIntersectionPoint.addInPlace(this._tempVector);
  55894. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  55895. found = true;
  55896. t = t0;
  55897. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  55898. }
  55899. }
  55900. if (!found) {
  55901. var velocitySquaredLength = this._velocity.lengthSquared();
  55902. var a = velocitySquaredLength;
  55903. this._basePoint.subtractToRef(p1, this._tempVector);
  55904. var b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  55905. var c = this._tempVector.lengthSquared() - 1.0;
  55906. var lowestRoot = getLowestRoot(a, b, c, t);
  55907. if (lowestRoot.found) {
  55908. t = lowestRoot.root;
  55909. found = true;
  55910. this._collisionPoint.copyFrom(p1);
  55911. }
  55912. this._basePoint.subtractToRef(p2, this._tempVector);
  55913. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  55914. c = this._tempVector.lengthSquared() - 1.0;
  55915. lowestRoot = getLowestRoot(a, b, c, t);
  55916. if (lowestRoot.found) {
  55917. t = lowestRoot.root;
  55918. found = true;
  55919. this._collisionPoint.copyFrom(p2);
  55920. }
  55921. this._basePoint.subtractToRef(p3, this._tempVector);
  55922. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  55923. c = this._tempVector.lengthSquared() - 1.0;
  55924. lowestRoot = getLowestRoot(a, b, c, t);
  55925. if (lowestRoot.found) {
  55926. t = lowestRoot.root;
  55927. found = true;
  55928. this._collisionPoint.copyFrom(p3);
  55929. }
  55930. p2.subtractToRef(p1, this._edge);
  55931. p1.subtractToRef(this._basePoint, this._baseToVertex);
  55932. var edgeSquaredLength = this._edge.lengthSquared();
  55933. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  55934. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  55935. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  55936. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  55937. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  55938. lowestRoot = getLowestRoot(a, b, c, t);
  55939. if (lowestRoot.found) {
  55940. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  55941. if (f >= 0.0 && f <= 1.0) {
  55942. t = lowestRoot.root;
  55943. found = true;
  55944. this._edge.scaleInPlace(f);
  55945. p1.addToRef(this._edge, this._collisionPoint);
  55946. }
  55947. }
  55948. p3.subtractToRef(p2, this._edge);
  55949. p2.subtractToRef(this._basePoint, this._baseToVertex);
  55950. edgeSquaredLength = this._edge.lengthSquared();
  55951. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  55952. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  55953. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  55954. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  55955. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  55956. lowestRoot = getLowestRoot(a, b, c, t);
  55957. if (lowestRoot.found) {
  55958. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  55959. if (f >= 0.0 && f <= 1.0) {
  55960. t = lowestRoot.root;
  55961. found = true;
  55962. this._edge.scaleInPlace(f);
  55963. p2.addToRef(this._edge, this._collisionPoint);
  55964. }
  55965. }
  55966. p1.subtractToRef(p3, this._edge);
  55967. p3.subtractToRef(this._basePoint, this._baseToVertex);
  55968. edgeSquaredLength = this._edge.lengthSquared();
  55969. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  55970. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  55971. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  55972. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  55973. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  55974. lowestRoot = getLowestRoot(a, b, c, t);
  55975. if (lowestRoot.found) {
  55976. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  55977. if (f >= 0.0 && f <= 1.0) {
  55978. t = lowestRoot.root;
  55979. found = true;
  55980. this._edge.scaleInPlace(f);
  55981. p3.addToRef(this._edge, this._collisionPoint);
  55982. }
  55983. }
  55984. }
  55985. if (found) {
  55986. var distToCollision = t * this._velocity.length();
  55987. if (!this.collisionFound || distToCollision < this._nearestDistance) {
  55988. if (!this.intersectionPoint) {
  55989. this.intersectionPoint = this._collisionPoint.clone();
  55990. }
  55991. else {
  55992. this.intersectionPoint.copyFrom(this._collisionPoint);
  55993. }
  55994. this._nearestDistance = distToCollision;
  55995. this.collisionFound = true;
  55996. }
  55997. }
  55998. };
  55999. /** @hidden */
  56000. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  56001. for (var i = indexStart; i < indexEnd; i += 3) {
  56002. var p1 = pts[indices[i] - decal];
  56003. var p2 = pts[indices[i + 1] - decal];
  56004. var p3 = pts[indices[i + 2] - decal];
  56005. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  56006. }
  56007. };
  56008. /** @hidden */
  56009. Collider.prototype._getResponse = function (pos, vel) {
  56010. pos.addToRef(vel, this._destinationPoint);
  56011. vel.scaleInPlace((this._nearestDistance / vel.length()));
  56012. this._basePoint.addToRef(vel, pos);
  56013. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  56014. this._slidePlaneNormal.normalize();
  56015. this._slidePlaneNormal.scaleToRef(this._epsilon, this._displacementVector);
  56016. pos.addInPlace(this._displacementVector);
  56017. this.intersectionPoint.addInPlace(this._displacementVector);
  56018. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  56019. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  56020. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  56021. };
  56022. return Collider;
  56023. }());
  56024. BABYLON.Collider = Collider;
  56025. })(BABYLON || (BABYLON = {}));
  56026. //# sourceMappingURL=babylon.collider.js.map
  56027. var BABYLON;
  56028. (function (BABYLON) {
  56029. //WebWorker code will be inserted to this variable.
  56030. /** @hidden */
  56031. BABYLON.CollisionWorker = "";
  56032. /** Defines supported task for worker process */
  56033. var WorkerTaskType;
  56034. (function (WorkerTaskType) {
  56035. /** Initialization */
  56036. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  56037. /** Update of geometry */
  56038. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  56039. /** Evaluate collision */
  56040. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  56041. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  56042. /** Defines kind of replies returned by worker */
  56043. var WorkerReplyType;
  56044. (function (WorkerReplyType) {
  56045. /** Success */
  56046. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  56047. /** Unkown error */
  56048. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  56049. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  56050. /** @hidden */
  56051. var CollisionCoordinatorWorker = /** @class */ (function () {
  56052. function CollisionCoordinatorWorker() {
  56053. var _this = this;
  56054. this._scaledPosition = BABYLON.Vector3.Zero();
  56055. this._scaledVelocity = BABYLON.Vector3.Zero();
  56056. this.onMeshUpdated = function (transformNode) {
  56057. _this._addUpdateMeshesList[transformNode.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(transformNode);
  56058. };
  56059. this.onGeometryUpdated = function (geometry) {
  56060. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  56061. };
  56062. this._afterRender = function () {
  56063. if (!_this._init)
  56064. return;
  56065. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  56066. return;
  56067. }
  56068. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  56069. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  56070. if (_this._runningUpdated > 4) {
  56071. return;
  56072. }
  56073. ++_this._runningUpdated;
  56074. var payload = {
  56075. updatedMeshes: _this._addUpdateMeshesList,
  56076. updatedGeometries: _this._addUpdateGeometriesList,
  56077. removedGeometries: _this._toRemoveGeometryArray,
  56078. removedMeshes: _this._toRemoveMeshesArray
  56079. };
  56080. var message = {
  56081. payload: payload,
  56082. taskType: WorkerTaskType.UPDATE
  56083. };
  56084. var serializable = [];
  56085. for (var id in payload.updatedGeometries) {
  56086. if (payload.updatedGeometries.hasOwnProperty(id)) {
  56087. //prepare transferables
  56088. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  56089. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  56090. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  56091. }
  56092. }
  56093. _this._worker.postMessage(message, serializable);
  56094. _this._addUpdateMeshesList = {};
  56095. _this._addUpdateGeometriesList = {};
  56096. _this._toRemoveGeometryArray = [];
  56097. _this._toRemoveMeshesArray = [];
  56098. };
  56099. this._onMessageFromWorker = function (e) {
  56100. var returnData = e.data;
  56101. if (returnData.error != WorkerReplyType.SUCCESS) {
  56102. //TODO what errors can be returned from the worker?
  56103. BABYLON.Tools.Warn("error returned from worker!");
  56104. return;
  56105. }
  56106. switch (returnData.taskType) {
  56107. case WorkerTaskType.INIT:
  56108. _this._init = true;
  56109. //Update the worked with ALL of the scene's current state
  56110. _this._scene.meshes.forEach(function (mesh) {
  56111. _this.onMeshAdded(mesh);
  56112. });
  56113. _this._scene.getGeometries().forEach(function (geometry) {
  56114. _this.onGeometryAdded(geometry);
  56115. });
  56116. break;
  56117. case WorkerTaskType.UPDATE:
  56118. _this._runningUpdated--;
  56119. break;
  56120. case WorkerTaskType.COLLIDE:
  56121. var returnPayload = returnData.payload;
  56122. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  56123. return;
  56124. var callback = _this._collisionsCallbackArray[returnPayload.collisionId];
  56125. if (callback) {
  56126. var mesh = _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId);
  56127. if (mesh) {
  56128. callback(returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), mesh);
  56129. }
  56130. }
  56131. //cleanup
  56132. _this._collisionsCallbackArray[returnPayload.collisionId] = null;
  56133. break;
  56134. }
  56135. };
  56136. this._collisionsCallbackArray = [];
  56137. this._init = false;
  56138. this._runningUpdated = 0;
  56139. this._addUpdateMeshesList = {};
  56140. this._addUpdateGeometriesList = {};
  56141. this._toRemoveGeometryArray = [];
  56142. this._toRemoveMeshesArray = [];
  56143. }
  56144. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  56145. if (!this._init)
  56146. return;
  56147. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  56148. return;
  56149. position.divideToRef(collider._radius, this._scaledPosition);
  56150. displacement.divideToRef(collider._radius, this._scaledVelocity);
  56151. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  56152. var payload = {
  56153. collider: {
  56154. position: this._scaledPosition.asArray(),
  56155. velocity: this._scaledVelocity.asArray(),
  56156. radius: collider._radius.asArray()
  56157. },
  56158. collisionId: collisionIndex,
  56159. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  56160. maximumRetry: maximumRetry
  56161. };
  56162. var message = {
  56163. payload: payload,
  56164. taskType: WorkerTaskType.COLLIDE
  56165. };
  56166. this._worker.postMessage(message);
  56167. };
  56168. CollisionCoordinatorWorker.prototype.init = function (scene) {
  56169. this._scene = scene;
  56170. this._scene.registerAfterRender(this._afterRender);
  56171. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  56172. this._worker = new Worker(workerUrl);
  56173. this._worker.onmessage = this._onMessageFromWorker;
  56174. var message = {
  56175. payload: {},
  56176. taskType: WorkerTaskType.INIT
  56177. };
  56178. this._worker.postMessage(message);
  56179. };
  56180. CollisionCoordinatorWorker.prototype.destroy = function () {
  56181. this._scene.unregisterAfterRender(this._afterRender);
  56182. this._worker.terminate();
  56183. };
  56184. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  56185. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  56186. this.onMeshUpdated(mesh);
  56187. };
  56188. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  56189. this._toRemoveMeshesArray.push(mesh.uniqueId);
  56190. };
  56191. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  56192. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  56193. geometry.onGeometryUpdated = this.onGeometryUpdated;
  56194. this.onGeometryUpdated(geometry);
  56195. };
  56196. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  56197. this._toRemoveGeometryArray.push(geometry.id);
  56198. };
  56199. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  56200. var submeshes = [];
  56201. if (mesh.subMeshes) {
  56202. submeshes = mesh.subMeshes.map(function (sm, idx) {
  56203. var boundingInfo = sm.getBoundingInfo();
  56204. return {
  56205. position: idx,
  56206. verticesStart: sm.verticesStart,
  56207. verticesCount: sm.verticesCount,
  56208. indexStart: sm.indexStart,
  56209. indexCount: sm.indexCount,
  56210. hasMaterial: !!sm.getMaterial(),
  56211. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  56212. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  56213. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  56214. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray()
  56215. };
  56216. });
  56217. }
  56218. var geometryId = null;
  56219. if (mesh instanceof BABYLON.Mesh) {
  56220. var geometry = mesh.geometry;
  56221. geometryId = geometry ? geometry.id : null;
  56222. }
  56223. else if (mesh instanceof BABYLON.InstancedMesh) {
  56224. var geometry = mesh.sourceMesh && mesh.sourceMesh.geometry;
  56225. geometryId = geometry ? geometry.id : null;
  56226. }
  56227. var boundingInfo = mesh.getBoundingInfo();
  56228. return {
  56229. uniqueId: mesh.uniqueId,
  56230. id: mesh.id,
  56231. name: mesh.name,
  56232. geometryId: geometryId,
  56233. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  56234. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  56235. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  56236. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray(),
  56237. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  56238. subMeshes: submeshes,
  56239. checkCollisions: mesh.checkCollisions
  56240. };
  56241. };
  56242. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  56243. return {
  56244. id: geometry.id,
  56245. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  56246. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  56247. indices: new Uint32Array(geometry.getIndices() || []),
  56248. };
  56249. };
  56250. return CollisionCoordinatorWorker;
  56251. }());
  56252. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  56253. /** @hidden */
  56254. var CollisionCoordinatorLegacy = /** @class */ (function () {
  56255. function CollisionCoordinatorLegacy() {
  56256. this._scaledPosition = BABYLON.Vector3.Zero();
  56257. this._scaledVelocity = BABYLON.Vector3.Zero();
  56258. this._finalPosition = BABYLON.Vector3.Zero();
  56259. }
  56260. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  56261. position.divideToRef(collider._radius, this._scaledPosition);
  56262. displacement.divideToRef(collider._radius, this._scaledVelocity);
  56263. collider.collidedMesh = null;
  56264. collider._retry = 0;
  56265. collider._initialVelocity = this._scaledVelocity;
  56266. collider._initialPosition = this._scaledPosition;
  56267. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  56268. this._finalPosition.multiplyInPlace(collider._radius);
  56269. //run the callback
  56270. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  56271. };
  56272. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  56273. this._scene = scene;
  56274. };
  56275. CollisionCoordinatorLegacy.prototype.destroy = function () {
  56276. //Legacy need no destruction method.
  56277. };
  56278. //No update in legacy mode
  56279. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  56280. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  56281. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  56282. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  56283. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  56284. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  56285. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  56286. if (excludedMesh === void 0) { excludedMesh = null; }
  56287. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  56288. if (collider._retry >= maximumRetry) {
  56289. finalPosition.copyFrom(position);
  56290. return;
  56291. }
  56292. // Check if this is a mesh else camera or -1
  56293. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  56294. collider._initialize(position, velocity, closeDistance);
  56295. // Check all meshes
  56296. for (var index = 0; index < this._scene.meshes.length; index++) {
  56297. var mesh = this._scene.meshes[index];
  56298. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  56299. mesh._checkCollision(collider);
  56300. }
  56301. }
  56302. if (!collider.collisionFound) {
  56303. position.addToRef(velocity, finalPosition);
  56304. return;
  56305. }
  56306. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  56307. collider._getResponse(position, velocity);
  56308. }
  56309. if (velocity.length() <= closeDistance) {
  56310. finalPosition.copyFrom(position);
  56311. return;
  56312. }
  56313. collider._retry++;
  56314. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  56315. };
  56316. return CollisionCoordinatorLegacy;
  56317. }());
  56318. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  56319. })(BABYLON || (BABYLON = {}));
  56320. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  56321. var BABYLON;
  56322. (function (BABYLON) {
  56323. /**
  56324. * A particle represents one of the element emitted by a particle system.
  56325. * This is mainly define by its coordinates, direction, velocity and age.
  56326. */
  56327. var Particle = /** @class */ (function () {
  56328. /**
  56329. * Creates a new instance Particle
  56330. * @param particleSystem the particle system the particle belongs to
  56331. */
  56332. function Particle(
  56333. /**
  56334. * The particle system the particle belongs to.
  56335. */
  56336. particleSystem) {
  56337. this.particleSystem = particleSystem;
  56338. /**
  56339. * The world position of the particle in the scene.
  56340. */
  56341. this.position = BABYLON.Vector3.Zero();
  56342. /**
  56343. * The world direction of the particle in the scene.
  56344. */
  56345. this.direction = BABYLON.Vector3.Zero();
  56346. /**
  56347. * The color of the particle.
  56348. */
  56349. this.color = new BABYLON.Color4(0, 0, 0, 0);
  56350. /**
  56351. * The color change of the particle per step.
  56352. */
  56353. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  56354. /**
  56355. * Defines how long will the life of the particle be.
  56356. */
  56357. this.lifeTime = 1.0;
  56358. /**
  56359. * The current age of the particle.
  56360. */
  56361. this.age = 0;
  56362. /**
  56363. * The current size of the particle.
  56364. */
  56365. this.size = 0;
  56366. /**
  56367. * The current scale of the particle.
  56368. */
  56369. this.scale = new BABYLON.Vector2(1, 1);
  56370. /**
  56371. * The current angle of the particle.
  56372. */
  56373. this.angle = 0;
  56374. /**
  56375. * Defines how fast is the angle changing.
  56376. */
  56377. this.angularSpeed = 0;
  56378. /**
  56379. * Defines the cell index used by the particle to be rendered from a sprite.
  56380. */
  56381. this.cellIndex = 0;
  56382. /** @hidden */
  56383. this._attachedSubEmitters = null;
  56384. /** @hidden */
  56385. this._currentColor1 = new BABYLON.Color4(0, 0, 0, 0);
  56386. /** @hidden */
  56387. this._currentColor2 = new BABYLON.Color4(0, 0, 0, 0);
  56388. /** @hidden */
  56389. this._currentSize1 = 0;
  56390. /** @hidden */
  56391. this._currentSize2 = 0;
  56392. /** @hidden */
  56393. this._currentAngularSpeed1 = 0;
  56394. /** @hidden */
  56395. this._currentAngularSpeed2 = 0;
  56396. /** @hidden */
  56397. this._currentVelocity1 = 0;
  56398. /** @hidden */
  56399. this._currentVelocity2 = 0;
  56400. /** @hidden */
  56401. this._currentLimitVelocity1 = 0;
  56402. /** @hidden */
  56403. this._currentLimitVelocity2 = 0;
  56404. /** @hidden */
  56405. this._currentDrag1 = 0;
  56406. /** @hidden */
  56407. this._currentDrag2 = 0;
  56408. this.id = Particle._Count++;
  56409. if (!this.particleSystem.isAnimationSheetEnabled) {
  56410. return;
  56411. }
  56412. this.updateCellInfoFromSystem();
  56413. }
  56414. Particle.prototype.updateCellInfoFromSystem = function () {
  56415. this.cellIndex = this.particleSystem.startSpriteCellID;
  56416. };
  56417. /**
  56418. * Defines how the sprite cell index is updated for the particle
  56419. */
  56420. Particle.prototype.updateCellIndex = function () {
  56421. var offsetAge = this.age;
  56422. var changeSpeed = this.particleSystem.spriteCellChangeSpeed;
  56423. if (this.particleSystem.spriteRandomStartCell) {
  56424. if (this._randomCellOffset === undefined) {
  56425. this._randomCellOffset = Math.random() * this.lifeTime;
  56426. }
  56427. if (changeSpeed === 0) { // Special case when speed = 0 meaning we want to stay on initial cell
  56428. changeSpeed = 1;
  56429. offsetAge = this._randomCellOffset;
  56430. }
  56431. else {
  56432. offsetAge += this._randomCellOffset;
  56433. }
  56434. }
  56435. var dist = (this._initialEndSpriteCellID - this._initialStartSpriteCellID);
  56436. var ratio = BABYLON.Scalar.Clamp(((offsetAge * changeSpeed) % this.lifeTime) / this.lifeTime);
  56437. this.cellIndex = this._initialStartSpriteCellID + (ratio * dist) | 0;
  56438. };
  56439. /** @hidden */
  56440. Particle.prototype._inheritParticleInfoToSubEmitter = function (subEmitter) {
  56441. if (subEmitter.particleSystem.emitter.position) {
  56442. var emitterMesh = subEmitter.particleSystem.emitter;
  56443. emitterMesh.position.copyFrom(this.position);
  56444. if (subEmitter.inheritDirection) {
  56445. emitterMesh.position.subtractToRef(this.direction, BABYLON.Tmp.Vector3[0]);
  56446. // Look at using Y as forward
  56447. emitterMesh.lookAt(BABYLON.Tmp.Vector3[0], 0, Math.PI / 2);
  56448. }
  56449. }
  56450. else {
  56451. var emitterPosition = subEmitter.particleSystem.emitter;
  56452. emitterPosition.copyFrom(this.position);
  56453. }
  56454. // Set inheritedVelocityOffset to be used when new particles are created
  56455. this.direction.scaleToRef(subEmitter.inheritedVelocityAmount / 2, BABYLON.Tmp.Vector3[0]);
  56456. subEmitter.particleSystem._inheritedVelocityOffset.copyFrom(BABYLON.Tmp.Vector3[0]);
  56457. };
  56458. /** @hidden */
  56459. Particle.prototype._inheritParticleInfoToSubEmitters = function () {
  56460. var _this = this;
  56461. if (this._attachedSubEmitters && this._attachedSubEmitters.length > 0) {
  56462. this._attachedSubEmitters.forEach(function (subEmitter) {
  56463. _this._inheritParticleInfoToSubEmitter(subEmitter);
  56464. });
  56465. }
  56466. };
  56467. /** @hidden */
  56468. Particle.prototype._reset = function () {
  56469. this.age = 0;
  56470. this._currentColorGradient = null;
  56471. this._currentSizeGradient = null;
  56472. this._currentAngularSpeedGradient = null;
  56473. this._currentVelocityGradient = null;
  56474. this._currentLimitVelocityGradient = null;
  56475. this._currentDragGradient = null;
  56476. this.cellIndex = this.particleSystem.startSpriteCellID;
  56477. this._randomCellOffset = undefined;
  56478. };
  56479. /**
  56480. * Copy the properties of particle to another one.
  56481. * @param other the particle to copy the information to.
  56482. */
  56483. Particle.prototype.copyTo = function (other) {
  56484. other.position.copyFrom(this.position);
  56485. if (this._initialDirection) {
  56486. if (other._initialDirection) {
  56487. other._initialDirection.copyFrom(this._initialDirection);
  56488. }
  56489. else {
  56490. other._initialDirection = this._initialDirection.clone();
  56491. }
  56492. }
  56493. else {
  56494. other._initialDirection = null;
  56495. }
  56496. other.direction.copyFrom(this.direction);
  56497. other.color.copyFrom(this.color);
  56498. other.colorStep.copyFrom(this.colorStep);
  56499. other.lifeTime = this.lifeTime;
  56500. other.age = this.age;
  56501. other._randomCellOffset = this._randomCellOffset;
  56502. other.size = this.size;
  56503. other.scale.copyFrom(this.scale);
  56504. other.angle = this.angle;
  56505. other.angularSpeed = this.angularSpeed;
  56506. other.particleSystem = this.particleSystem;
  56507. other.cellIndex = this.cellIndex;
  56508. other.id = this.id;
  56509. other._attachedSubEmitters = this._attachedSubEmitters;
  56510. if (this._currentColorGradient) {
  56511. other._currentColorGradient = this._currentColorGradient;
  56512. other._currentColor1.copyFrom(this._currentColor1);
  56513. other._currentColor2.copyFrom(this._currentColor2);
  56514. }
  56515. if (this._currentSizeGradient) {
  56516. other._currentSizeGradient = this._currentSizeGradient;
  56517. other._currentSize1 = this._currentSize1;
  56518. other._currentSize2 = this._currentSize2;
  56519. }
  56520. if (this._currentAngularSpeedGradient) {
  56521. other._currentAngularSpeedGradient = this._currentAngularSpeedGradient;
  56522. other._currentAngularSpeed1 = this._currentAngularSpeed1;
  56523. other._currentAngularSpeed2 = this._currentAngularSpeed2;
  56524. }
  56525. if (this._currentVelocityGradient) {
  56526. other._currentVelocityGradient = this._currentVelocityGradient;
  56527. other._currentVelocity1 = this._currentVelocity1;
  56528. other._currentVelocity2 = this._currentVelocity2;
  56529. }
  56530. if (this._currentLimitVelocityGradient) {
  56531. other._currentLimitVelocityGradient = this._currentLimitVelocityGradient;
  56532. other._currentLimitVelocity1 = this._currentLimitVelocity1;
  56533. other._currentLimitVelocity2 = this._currentLimitVelocity2;
  56534. }
  56535. if (this._currentDragGradient) {
  56536. other._currentDragGradient = this._currentDragGradient;
  56537. other._currentDrag1 = this._currentDrag1;
  56538. other._currentDrag2 = this._currentDrag2;
  56539. }
  56540. if (this.particleSystem.isAnimationSheetEnabled) {
  56541. other._initialStartSpriteCellID = this._initialStartSpriteCellID;
  56542. other._initialEndSpriteCellID = this._initialEndSpriteCellID;
  56543. }
  56544. if (this.particleSystem.useRampGradients) {
  56545. other.remapData.copyFrom(this.remapData);
  56546. }
  56547. if (this._randomNoiseCoordinates1) {
  56548. if (other._randomNoiseCoordinates1) {
  56549. other._randomNoiseCoordinates1.copyFrom(this._randomNoiseCoordinates1);
  56550. other._randomNoiseCoordinates2.copyFrom(this._randomNoiseCoordinates2);
  56551. }
  56552. else {
  56553. other._randomNoiseCoordinates1 = this._randomNoiseCoordinates1.clone();
  56554. other._randomNoiseCoordinates2 = this._randomNoiseCoordinates2.clone();
  56555. }
  56556. }
  56557. };
  56558. Particle._Count = 0;
  56559. return Particle;
  56560. }());
  56561. BABYLON.Particle = Particle;
  56562. })(BABYLON || (BABYLON = {}));
  56563. //# sourceMappingURL=babylon.particle.js.map
  56564. var BABYLON;
  56565. (function (BABYLON) {
  56566. /**
  56567. * This represents the base class for particle system in Babylon.
  56568. * 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.
  56569. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  56570. * @example https://doc.babylonjs.com/babylon101/particles
  56571. */
  56572. var BaseParticleSystem = /** @class */ (function () {
  56573. /**
  56574. * Instantiates a particle system.
  56575. * 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.
  56576. * @param name The name of the particle system
  56577. */
  56578. function BaseParticleSystem(name) {
  56579. /**
  56580. * List of animations used by the particle system.
  56581. */
  56582. this.animations = [];
  56583. /**
  56584. * The rendering group used by the Particle system to chose when to render.
  56585. */
  56586. this.renderingGroupId = 0;
  56587. /**
  56588. * The emitter represents the Mesh or position we are attaching the particle system to.
  56589. */
  56590. this.emitter = null;
  56591. /**
  56592. * The maximum number of particles to emit per frame
  56593. */
  56594. this.emitRate = 10;
  56595. /**
  56596. * If you want to launch only a few particles at once, that can be done, as well.
  56597. */
  56598. this.manualEmitCount = -1;
  56599. /**
  56600. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  56601. */
  56602. this.updateSpeed = 0.01;
  56603. /**
  56604. * The amount of time the particle system is running (depends of the overall update speed).
  56605. */
  56606. this.targetStopDuration = 0;
  56607. /**
  56608. * Specifies whether the particle system will be disposed once it reaches the end of the animation.
  56609. */
  56610. this.disposeOnStop = false;
  56611. /**
  56612. * Minimum power of emitting particles.
  56613. */
  56614. this.minEmitPower = 1;
  56615. /**
  56616. * Maximum power of emitting particles.
  56617. */
  56618. this.maxEmitPower = 1;
  56619. /**
  56620. * Minimum life time of emitting particles.
  56621. */
  56622. this.minLifeTime = 1;
  56623. /**
  56624. * Maximum life time of emitting particles.
  56625. */
  56626. this.maxLifeTime = 1;
  56627. /**
  56628. * Minimum Size of emitting particles.
  56629. */
  56630. this.minSize = 1;
  56631. /**
  56632. * Maximum Size of emitting particles.
  56633. */
  56634. this.maxSize = 1;
  56635. /**
  56636. * Minimum scale of emitting particles on X axis.
  56637. */
  56638. this.minScaleX = 1;
  56639. /**
  56640. * Maximum scale of emitting particles on X axis.
  56641. */
  56642. this.maxScaleX = 1;
  56643. /**
  56644. * Minimum scale of emitting particles on Y axis.
  56645. */
  56646. this.minScaleY = 1;
  56647. /**
  56648. * Maximum scale of emitting particles on Y axis.
  56649. */
  56650. this.maxScaleY = 1;
  56651. /**
  56652. * Gets or sets the minimal initial rotation in radians.
  56653. */
  56654. this.minInitialRotation = 0;
  56655. /**
  56656. * Gets or sets the maximal initial rotation in radians.
  56657. */
  56658. this.maxInitialRotation = 0;
  56659. /**
  56660. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  56661. */
  56662. this.minAngularSpeed = 0;
  56663. /**
  56664. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  56665. */
  56666. this.maxAngularSpeed = 0;
  56667. /**
  56668. * The layer mask we are rendering the particles through.
  56669. */
  56670. this.layerMask = 0x0FFFFFFF;
  56671. /**
  56672. * This can help using your own shader to render the particle system.
  56673. * The according effect will be created
  56674. */
  56675. this.customShader = null;
  56676. /**
  56677. * By default particle system starts as soon as they are created. This prevents the
  56678. * automatic start to happen and let you decide when to start emitting particles.
  56679. */
  56680. this.preventAutoStart = false;
  56681. /** Gets or sets the strength to apply to the noise value (default is (10, 10, 10)) */
  56682. this.noiseStrength = new BABYLON.Vector3(10, 10, 10);
  56683. /**
  56684. * Callback triggered when the particle animation is ending.
  56685. */
  56686. this.onAnimationEnd = null;
  56687. /**
  56688. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  56689. */
  56690. this.blendMode = BABYLON.ParticleSystem.BLENDMODE_ONEONE;
  56691. /**
  56692. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  56693. * to override the particles.
  56694. */
  56695. this.forceDepthWrite = false;
  56696. /** 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 */
  56697. this.preWarmCycles = 0;
  56698. /** Gets or sets a value indicating the time step multiplier to use in pre-warm mode (default is 1) */
  56699. this.preWarmStepOffset = 1;
  56700. /**
  56701. * If using a spritesheet (isAnimationSheetEnabled) defines the speed of the sprite loop (default is 1 meaning the animation will play once during the entire particle lifetime)
  56702. */
  56703. this.spriteCellChangeSpeed = 1;
  56704. /**
  56705. * If using a spritesheet (isAnimationSheetEnabled) defines the first sprite cell to display
  56706. */
  56707. this.startSpriteCellID = 0;
  56708. /**
  56709. * If using a spritesheet (isAnimationSheetEnabled) defines the last sprite cell to display
  56710. */
  56711. this.endSpriteCellID = 0;
  56712. /**
  56713. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use
  56714. */
  56715. this.spriteCellWidth = 0;
  56716. /**
  56717. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use
  56718. */
  56719. this.spriteCellHeight = 0;
  56720. /**
  56721. * This allows the system to random pick the start cell ID between startSpriteCellID and endSpriteCellID
  56722. */
  56723. this.spriteRandomStartCell = false;
  56724. /** Gets or sets a Vector2 used to move the pivot (by default (0,0)) */
  56725. this.translationPivot = new BABYLON.Vector2(0, 0);
  56726. /**
  56727. * You can use gravity if you want to give an orientation to your particles.
  56728. */
  56729. this.gravity = BABYLON.Vector3.Zero();
  56730. this._colorGradients = null;
  56731. this._sizeGradients = null;
  56732. this._lifeTimeGradients = null;
  56733. this._angularSpeedGradients = null;
  56734. this._velocityGradients = null;
  56735. this._limitVelocityGradients = null;
  56736. this._dragGradients = null;
  56737. this._emitRateGradients = null;
  56738. this._startSizeGradients = null;
  56739. this._rampGradients = null;
  56740. this._colorRemapGradients = null;
  56741. this._alphaRemapGradients = null;
  56742. /**
  56743. * Defines the delay in milliseconds before starting the system (0 by default)
  56744. */
  56745. this.startDelay = 0;
  56746. /** Gets or sets a value indicating the damping to apply if the limit velocity factor is reached */
  56747. this.limitVelocityDamping = 0.4;
  56748. /**
  56749. * Random color of each particle after it has been emitted, between color1 and color2 vectors
  56750. */
  56751. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  56752. /**
  56753. * Random color of each particle after it has been emitted, between color1 and color2 vectors
  56754. */
  56755. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  56756. /**
  56757. * Color the particle will have at the end of its lifetime
  56758. */
  56759. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  56760. /**
  56761. * An optional mask to filter some colors out of the texture, or filter a part of the alpha channel
  56762. */
  56763. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  56764. /**
  56765. * Gets or sets the billboard mode to use when isBillboardBased = true.
  56766. * Value can be: ParticleSystem.BILLBOARDMODE_ALL, ParticleSystem.BILLBOARDMODE_Y, ParticleSystem.BILLBOARDMODE_STRETCHED
  56767. */
  56768. this.billboardMode = BABYLON.ParticleSystem.BILLBOARDMODE_ALL;
  56769. this._isBillboardBased = true;
  56770. /**
  56771. * Local cache of defines for image processing.
  56772. */
  56773. this._imageProcessingConfigurationDefines = new BABYLON.ImageProcessingConfigurationDefines();
  56774. this.id = name;
  56775. this.name = name;
  56776. }
  56777. Object.defineProperty(BaseParticleSystem.prototype, "isAnimationSheetEnabled", {
  56778. /**
  56779. * Gets or sets whether an animation sprite sheet is enabled or not on the particle system
  56780. */
  56781. get: function () {
  56782. return this._isAnimationSheetEnabled;
  56783. },
  56784. set: function (value) {
  56785. if (this._isAnimationSheetEnabled == value) {
  56786. return;
  56787. }
  56788. this._isAnimationSheetEnabled = value;
  56789. this._reset();
  56790. },
  56791. enumerable: true,
  56792. configurable: true
  56793. });
  56794. /**
  56795. * Get hosting scene
  56796. * @returns the scene
  56797. */
  56798. BaseParticleSystem.prototype.getScene = function () {
  56799. return this._scene;
  56800. };
  56801. BaseParticleSystem.prototype._hasTargetStopDurationDependantGradient = function () {
  56802. return (this._startSizeGradients && this._startSizeGradients.length > 0)
  56803. || (this._emitRateGradients && this._emitRateGradients.length > 0)
  56804. || (this._lifeTimeGradients && this._lifeTimeGradients.length > 0);
  56805. };
  56806. /**
  56807. * Gets the current list of drag gradients.
  56808. * You must use addDragGradient and removeDragGradient to udpate this list
  56809. * @returns the list of drag gradients
  56810. */
  56811. BaseParticleSystem.prototype.getDragGradients = function () {
  56812. return this._dragGradients;
  56813. };
  56814. /**
  56815. * Gets the current list of limit velocity gradients.
  56816. * You must use addLimitVelocityGradient and removeLimitVelocityGradient to udpate this list
  56817. * @returns the list of limit velocity gradients
  56818. */
  56819. BaseParticleSystem.prototype.getLimitVelocityGradients = function () {
  56820. return this._limitVelocityGradients;
  56821. };
  56822. /**
  56823. * Gets the current list of color gradients.
  56824. * You must use addColorGradient and removeColorGradient to udpate this list
  56825. * @returns the list of color gradients
  56826. */
  56827. BaseParticleSystem.prototype.getColorGradients = function () {
  56828. return this._colorGradients;
  56829. };
  56830. /**
  56831. * Gets the current list of size gradients.
  56832. * You must use addSizeGradient and removeSizeGradient to udpate this list
  56833. * @returns the list of size gradients
  56834. */
  56835. BaseParticleSystem.prototype.getSizeGradients = function () {
  56836. return this._sizeGradients;
  56837. };
  56838. /**
  56839. * Gets the current list of color remap gradients.
  56840. * You must use addColorRemapGradient and removeColorRemapGradient to udpate this list
  56841. * @returns the list of color remap gradients
  56842. */
  56843. BaseParticleSystem.prototype.getColorRemapGradients = function () {
  56844. return this._colorRemapGradients;
  56845. };
  56846. /**
  56847. * Gets the current list of alpha remap gradients.
  56848. * You must use addAlphaRemapGradient and removeAlphaRemapGradient to udpate this list
  56849. * @returns the list of alpha remap gradients
  56850. */
  56851. BaseParticleSystem.prototype.getAlphaRemapGradients = function () {
  56852. return this._alphaRemapGradients;
  56853. };
  56854. /**
  56855. * Gets the current list of life time gradients.
  56856. * You must use addLifeTimeGradient and removeLifeTimeGradient to udpate this list
  56857. * @returns the list of life time gradients
  56858. */
  56859. BaseParticleSystem.prototype.getLifeTimeGradients = function () {
  56860. return this._lifeTimeGradients;
  56861. };
  56862. /**
  56863. * Gets the current list of angular speed gradients.
  56864. * You must use addAngularSpeedGradient and removeAngularSpeedGradient to udpate this list
  56865. * @returns the list of angular speed gradients
  56866. */
  56867. BaseParticleSystem.prototype.getAngularSpeedGradients = function () {
  56868. return this._angularSpeedGradients;
  56869. };
  56870. /**
  56871. * Gets the current list of velocity gradients.
  56872. * You must use addVelocityGradient and removeVelocityGradient to udpate this list
  56873. * @returns the list of velocity gradients
  56874. */
  56875. BaseParticleSystem.prototype.getVelocityGradients = function () {
  56876. return this._velocityGradients;
  56877. };
  56878. /**
  56879. * Gets the current list of start size gradients.
  56880. * You must use addStartSizeGradient and removeStartSizeGradient to udpate this list
  56881. * @returns the list of start size gradients
  56882. */
  56883. BaseParticleSystem.prototype.getStartSizeGradients = function () {
  56884. return this._startSizeGradients;
  56885. };
  56886. /**
  56887. * Gets the current list of emit rate gradients.
  56888. * You must use addEmitRateGradient and removeEmitRateGradient to udpate this list
  56889. * @returns the list of emit rate gradients
  56890. */
  56891. BaseParticleSystem.prototype.getEmitRateGradients = function () {
  56892. return this._emitRateGradients;
  56893. };
  56894. Object.defineProperty(BaseParticleSystem.prototype, "direction1", {
  56895. /**
  56896. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  56897. * This only works when particleEmitterTyps is a BoxParticleEmitter
  56898. */
  56899. get: function () {
  56900. if (this.particleEmitterType.direction1) {
  56901. return this.particleEmitterType.direction1;
  56902. }
  56903. return BABYLON.Vector3.Zero();
  56904. },
  56905. set: function (value) {
  56906. if (this.particleEmitterType.direction1) {
  56907. this.particleEmitterType.direction1 = value;
  56908. }
  56909. },
  56910. enumerable: true,
  56911. configurable: true
  56912. });
  56913. Object.defineProperty(BaseParticleSystem.prototype, "direction2", {
  56914. /**
  56915. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  56916. * This only works when particleEmitterTyps is a BoxParticleEmitter
  56917. */
  56918. get: function () {
  56919. if (this.particleEmitterType.direction2) {
  56920. return this.particleEmitterType.direction2;
  56921. }
  56922. return BABYLON.Vector3.Zero();
  56923. },
  56924. set: function (value) {
  56925. if (this.particleEmitterType.direction2) {
  56926. this.particleEmitterType.direction2 = value;
  56927. }
  56928. },
  56929. enumerable: true,
  56930. configurable: true
  56931. });
  56932. Object.defineProperty(BaseParticleSystem.prototype, "minEmitBox", {
  56933. /**
  56934. * 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.
  56935. * This only works when particleEmitterTyps is a BoxParticleEmitter
  56936. */
  56937. get: function () {
  56938. if (this.particleEmitterType.minEmitBox) {
  56939. return this.particleEmitterType.minEmitBox;
  56940. }
  56941. return BABYLON.Vector3.Zero();
  56942. },
  56943. set: function (value) {
  56944. if (this.particleEmitterType.minEmitBox) {
  56945. this.particleEmitterType.minEmitBox = value;
  56946. }
  56947. },
  56948. enumerable: true,
  56949. configurable: true
  56950. });
  56951. Object.defineProperty(BaseParticleSystem.prototype, "maxEmitBox", {
  56952. /**
  56953. * 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.
  56954. * This only works when particleEmitterTyps is a BoxParticleEmitter
  56955. */
  56956. get: function () {
  56957. if (this.particleEmitterType.maxEmitBox) {
  56958. return this.particleEmitterType.maxEmitBox;
  56959. }
  56960. return BABYLON.Vector3.Zero();
  56961. },
  56962. set: function (value) {
  56963. if (this.particleEmitterType.maxEmitBox) {
  56964. this.particleEmitterType.maxEmitBox = value;
  56965. }
  56966. },
  56967. enumerable: true,
  56968. configurable: true
  56969. });
  56970. Object.defineProperty(BaseParticleSystem.prototype, "isBillboardBased", {
  56971. /**
  56972. * Gets or sets a boolean indicating if the particles must be rendered as billboard or aligned with the direction
  56973. */
  56974. get: function () {
  56975. return this._isBillboardBased;
  56976. },
  56977. set: function (value) {
  56978. if (this._isBillboardBased === value) {
  56979. return;
  56980. }
  56981. this._isBillboardBased = value;
  56982. this._reset();
  56983. },
  56984. enumerable: true,
  56985. configurable: true
  56986. });
  56987. Object.defineProperty(BaseParticleSystem.prototype, "imageProcessingConfiguration", {
  56988. /**
  56989. * Gets the image processing configuration used either in this material.
  56990. */
  56991. get: function () {
  56992. return this._imageProcessingConfiguration;
  56993. },
  56994. /**
  56995. * Sets the Default image processing configuration used either in the this material.
  56996. *
  56997. * If sets to null, the scene one is in use.
  56998. */
  56999. set: function (value) {
  57000. this._attachImageProcessingConfiguration(value);
  57001. },
  57002. enumerable: true,
  57003. configurable: true
  57004. });
  57005. /**
  57006. * Attaches a new image processing configuration to the Standard Material.
  57007. * @param configuration
  57008. */
  57009. BaseParticleSystem.prototype._attachImageProcessingConfiguration = function (configuration) {
  57010. if (configuration === this._imageProcessingConfiguration) {
  57011. return;
  57012. }
  57013. // Pick the scene configuration if needed.
  57014. if (!configuration) {
  57015. this._imageProcessingConfiguration = this._scene.imageProcessingConfiguration;
  57016. }
  57017. else {
  57018. this._imageProcessingConfiguration = configuration;
  57019. }
  57020. };
  57021. /** @hidden */
  57022. BaseParticleSystem.prototype._reset = function () {
  57023. };
  57024. /** @hidden */
  57025. BaseParticleSystem.prototype._removeGradientAndTexture = function (gradient, gradients, texture) {
  57026. if (!gradients) {
  57027. return this;
  57028. }
  57029. var index = 0;
  57030. for (var _i = 0, gradients_1 = gradients; _i < gradients_1.length; _i++) {
  57031. var valueGradient = gradients_1[_i];
  57032. if (valueGradient.gradient === gradient) {
  57033. gradients.splice(index, 1);
  57034. break;
  57035. }
  57036. index++;
  57037. }
  57038. if (texture) {
  57039. texture.dispose();
  57040. }
  57041. return this;
  57042. };
  57043. /**
  57044. * Creates a Point Emitter for the particle system (emits directly from the emitter position)
  57045. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  57046. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  57047. * @returns the emitter
  57048. */
  57049. BaseParticleSystem.prototype.createPointEmitter = function (direction1, direction2) {
  57050. var particleEmitter = new BABYLON.PointParticleEmitter();
  57051. particleEmitter.direction1 = direction1;
  57052. particleEmitter.direction2 = direction2;
  57053. this.particleEmitterType = particleEmitter;
  57054. return particleEmitter;
  57055. };
  57056. /**
  57057. * Creates a Hemisphere Emitter for the particle system (emits along the hemisphere radius)
  57058. * @param radius The radius of the hemisphere to emit from
  57059. * @param radiusRange The range of the hemisphere to emit from [0-1] 0 Surface Only, 1 Entire Radius
  57060. * @returns the emitter
  57061. */
  57062. BaseParticleSystem.prototype.createHemisphericEmitter = function (radius, radiusRange) {
  57063. if (radius === void 0) { radius = 1; }
  57064. if (radiusRange === void 0) { radiusRange = 1; }
  57065. var particleEmitter = new BABYLON.HemisphericParticleEmitter(radius, radiusRange);
  57066. this.particleEmitterType = particleEmitter;
  57067. return particleEmitter;
  57068. };
  57069. /**
  57070. * Creates a Sphere Emitter for the particle system (emits along the sphere radius)
  57071. * @param radius The radius of the sphere to emit from
  57072. * @param radiusRange The range of the sphere to emit from [0-1] 0 Surface Only, 1 Entire Radius
  57073. * @returns the emitter
  57074. */
  57075. BaseParticleSystem.prototype.createSphereEmitter = function (radius, radiusRange) {
  57076. if (radius === void 0) { radius = 1; }
  57077. if (radiusRange === void 0) { radiusRange = 1; }
  57078. var particleEmitter = new BABYLON.SphereParticleEmitter(radius, radiusRange);
  57079. this.particleEmitterType = particleEmitter;
  57080. return particleEmitter;
  57081. };
  57082. /**
  57083. * Creates a Directed Sphere Emitter for the particle system (emits between direction1 and direction2)
  57084. * @param radius The radius of the sphere to emit from
  57085. * @param direction1 Particles are emitted between the direction1 and direction2 from within the sphere
  57086. * @param direction2 Particles are emitted between the direction1 and direction2 from within the sphere
  57087. * @returns the emitter
  57088. */
  57089. BaseParticleSystem.prototype.createDirectedSphereEmitter = function (radius, direction1, direction2) {
  57090. if (radius === void 0) { radius = 1; }
  57091. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  57092. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  57093. var particleEmitter = new BABYLON.SphereDirectedParticleEmitter(radius, direction1, direction2);
  57094. this.particleEmitterType = particleEmitter;
  57095. return particleEmitter;
  57096. };
  57097. /**
  57098. * Creates a Cylinder Emitter for the particle system (emits from the cylinder to the particle position)
  57099. * @param radius The radius of the emission cylinder
  57100. * @param height The height of the emission cylinder
  57101. * @param radiusRange The range of emission [0-1] 0 Surface only, 1 Entire Radius
  57102. * @param directionRandomizer How much to randomize the particle direction [0-1]
  57103. * @returns the emitter
  57104. */
  57105. BaseParticleSystem.prototype.createCylinderEmitter = function (radius, height, radiusRange, directionRandomizer) {
  57106. if (radius === void 0) { radius = 1; }
  57107. if (height === void 0) { height = 1; }
  57108. if (radiusRange === void 0) { radiusRange = 1; }
  57109. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  57110. var particleEmitter = new BABYLON.CylinderParticleEmitter(radius, height, radiusRange, directionRandomizer);
  57111. this.particleEmitterType = particleEmitter;
  57112. return particleEmitter;
  57113. };
  57114. /**
  57115. * Creates a Directed Cylinder Emitter for the particle system (emits between direction1 and direction2)
  57116. * @param radius The radius of the cylinder to emit from
  57117. * @param height The height of the emission cylinder
  57118. * @param radiusRange the range of the emission cylinder [0-1] 0 Surface only, 1 Entire Radius (1 by default)
  57119. * @param direction1 Particles are emitted between the direction1 and direction2 from within the cylinder
  57120. * @param direction2 Particles are emitted between the direction1 and direction2 from within the cylinder
  57121. * @returns the emitter
  57122. */
  57123. BaseParticleSystem.prototype.createDirectedCylinderEmitter = function (radius, height, radiusRange, direction1, direction2) {
  57124. if (radius === void 0) { radius = 1; }
  57125. if (height === void 0) { height = 1; }
  57126. if (radiusRange === void 0) { radiusRange = 1; }
  57127. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  57128. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  57129. var particleEmitter = new BABYLON.CylinderDirectedParticleEmitter(radius, height, radiusRange, direction1, direction2);
  57130. this.particleEmitterType = particleEmitter;
  57131. return particleEmitter;
  57132. };
  57133. /**
  57134. * Creates a Cone Emitter for the particle system (emits from the cone to the particle position)
  57135. * @param radius The radius of the cone to emit from
  57136. * @param angle The base angle of the cone
  57137. * @returns the emitter
  57138. */
  57139. BaseParticleSystem.prototype.createConeEmitter = function (radius, angle) {
  57140. if (radius === void 0) { radius = 1; }
  57141. if (angle === void 0) { angle = Math.PI / 4; }
  57142. var particleEmitter = new BABYLON.ConeParticleEmitter(radius, angle);
  57143. this.particleEmitterType = particleEmitter;
  57144. return particleEmitter;
  57145. };
  57146. /**
  57147. * Creates a Box Emitter for the particle system. (emits between direction1 and direction2 from withing the box defined by minEmitBox and maxEmitBox)
  57148. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  57149. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  57150. * @param minEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  57151. * @param maxEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  57152. * @returns the emitter
  57153. */
  57154. BaseParticleSystem.prototype.createBoxEmitter = function (direction1, direction2, minEmitBox, maxEmitBox) {
  57155. var particleEmitter = new BABYLON.BoxParticleEmitter();
  57156. this.particleEmitterType = particleEmitter;
  57157. this.direction1 = direction1;
  57158. this.direction2 = direction2;
  57159. this.minEmitBox = minEmitBox;
  57160. this.maxEmitBox = maxEmitBox;
  57161. return particleEmitter;
  57162. };
  57163. /**
  57164. * Source color is added to the destination color without alpha affecting the result
  57165. */
  57166. BaseParticleSystem.BLENDMODE_ONEONE = 0;
  57167. /**
  57168. * Blend current color and particle color using particle’s alpha
  57169. */
  57170. BaseParticleSystem.BLENDMODE_STANDARD = 1;
  57171. /**
  57172. * Add current color and particle color multiplied by particle’s alpha
  57173. */
  57174. BaseParticleSystem.BLENDMODE_ADD = 2;
  57175. /**
  57176. * Multiply current color with particle color
  57177. */
  57178. BaseParticleSystem.BLENDMODE_MULTIPLY = 3;
  57179. /**
  57180. * Multiply current color with particle color then add current color and particle color multiplied by particle’s alpha
  57181. */
  57182. BaseParticleSystem.BLENDMODE_MULTIPLYADD = 4;
  57183. return BaseParticleSystem;
  57184. }());
  57185. BABYLON.BaseParticleSystem = BaseParticleSystem;
  57186. })(BABYLON || (BABYLON = {}));
  57187. //# sourceMappingURL=babylon.baseParticleSystem.js.map
  57188. var BABYLON;
  57189. (function (BABYLON) {
  57190. /**
  57191. * This represents a particle system in Babylon.
  57192. * 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.
  57193. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  57194. * @example https://doc.babylonjs.com/babylon101/particles
  57195. */
  57196. var ParticleSystem = /** @class */ (function (_super) {
  57197. __extends(ParticleSystem, _super);
  57198. /**
  57199. * Instantiates a particle system.
  57200. * 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.
  57201. * @param name The name of the particle system
  57202. * @param capacity The max number of particles alive at the same time
  57203. * @param scene The scene the particle system belongs to
  57204. * @param customEffect a custom effect used to change the way particles are rendered by default
  57205. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  57206. * @param epsilon Offset used to render the particles
  57207. */
  57208. function ParticleSystem(name, capacity, scene, customEffect, isAnimationSheetEnabled, epsilon) {
  57209. if (customEffect === void 0) { customEffect = null; }
  57210. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  57211. if (epsilon === void 0) { epsilon = 0.01; }
  57212. var _this = _super.call(this, name) || this;
  57213. /**
  57214. * @hidden
  57215. */
  57216. _this._inheritedVelocityOffset = new BABYLON.Vector3();
  57217. /**
  57218. * An event triggered when the system is disposed
  57219. */
  57220. _this.onDisposeObservable = new BABYLON.Observable();
  57221. _this._particles = new Array();
  57222. _this._stockParticles = new Array();
  57223. _this._newPartsExcess = 0;
  57224. _this._vertexBuffers = {};
  57225. _this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  57226. _this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  57227. _this._scaledDirection = BABYLON.Vector3.Zero();
  57228. _this._scaledGravity = BABYLON.Vector3.Zero();
  57229. _this._currentRenderId = -1;
  57230. _this._useInstancing = false;
  57231. _this._started = false;
  57232. _this._stopped = false;
  57233. _this._actualFrame = 0;
  57234. /** @hidden */
  57235. _this._currentEmitRate1 = 0;
  57236. /** @hidden */
  57237. _this._currentEmitRate2 = 0;
  57238. /** @hidden */
  57239. _this._currentStartSize1 = 0;
  57240. /** @hidden */
  57241. _this._currentStartSize2 = 0;
  57242. _this._rawTextureWidth = 256;
  57243. _this._useRampGradients = false;
  57244. /**
  57245. * @hidden
  57246. * If the particle systems emitter should be disposed when the particle system is disposed
  57247. */
  57248. _this._disposeEmitterOnDispose = false;
  57249. // start of sub system methods
  57250. /**
  57251. * "Recycles" one of the particle by copying it back to the "stock" of particles and removing it from the active list.
  57252. * Its lifetime will start back at 0.
  57253. */
  57254. _this.recycleParticle = function (particle) {
  57255. // move particle from activeParticle list to stock particles
  57256. var lastParticle = _this._particles.pop();
  57257. if (lastParticle !== particle) {
  57258. lastParticle.copyTo(particle);
  57259. }
  57260. _this._stockParticles.push(lastParticle);
  57261. };
  57262. _this._createParticle = function () {
  57263. var particle;
  57264. if (_this._stockParticles.length !== 0) {
  57265. particle = _this._stockParticles.pop();
  57266. particle._reset();
  57267. }
  57268. else {
  57269. particle = new BABYLON.Particle(_this);
  57270. }
  57271. // Attach emitters
  57272. if (_this._subEmitters && _this._subEmitters.length > 0) {
  57273. var subEmitters = _this._subEmitters[Math.floor(Math.random() * _this._subEmitters.length)];
  57274. particle._attachedSubEmitters = [];
  57275. subEmitters.forEach(function (subEmitter) {
  57276. if (subEmitter.type === BABYLON.SubEmitterType.ATTACHED) {
  57277. var newEmitter = subEmitter.clone();
  57278. particle._attachedSubEmitters.push(newEmitter);
  57279. newEmitter.particleSystem.start();
  57280. }
  57281. });
  57282. }
  57283. return particle;
  57284. };
  57285. _this._emitFromParticle = function (particle) {
  57286. if (!_this._subEmitters || _this._subEmitters.length === 0) {
  57287. return;
  57288. }
  57289. var templateIndex = Math.floor(Math.random() * _this._subEmitters.length);
  57290. _this._subEmitters[templateIndex].forEach(function (subEmitter) {
  57291. if (subEmitter.type === BABYLON.SubEmitterType.END) {
  57292. var subSystem = subEmitter.clone();
  57293. particle._inheritParticleInfoToSubEmitter(subSystem);
  57294. subSystem.particleSystem._rootParticleSystem = _this;
  57295. _this.activeSubSystems.push(subSystem.particleSystem);
  57296. subSystem.particleSystem.start();
  57297. }
  57298. });
  57299. };
  57300. _this._capacity = capacity;
  57301. _this._epsilon = epsilon;
  57302. _this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  57303. _this._scene = scene || BABYLON.Engine.LastCreatedScene;
  57304. // Setup the default processing configuration to the scene.
  57305. _this._attachImageProcessingConfiguration(null);
  57306. _this._customEffect = customEffect;
  57307. _this._scene.particleSystems.push(_this);
  57308. _this._useInstancing = _this._scene.getEngine().getCaps().instancedArrays;
  57309. _this._createIndexBuffer();
  57310. _this._createVertexBuffers();
  57311. // Default emitter type
  57312. _this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  57313. // Update
  57314. _this.updateFunction = function (particles) {
  57315. var noiseTextureSize = null;
  57316. var noiseTextureData = null;
  57317. if (_this.noiseTexture) { // We need to get texture data back to CPU
  57318. noiseTextureSize = _this.noiseTexture.getSize();
  57319. noiseTextureData = (_this.noiseTexture.getContent());
  57320. }
  57321. var _loop_1 = function () {
  57322. particle = particles[index];
  57323. var scaledUpdateSpeed = _this._scaledUpdateSpeed;
  57324. var previousAge = particle.age;
  57325. particle.age += scaledUpdateSpeed;
  57326. // Evaluate step to death
  57327. if (particle.age > particle.lifeTime) {
  57328. var diff = particle.age - previousAge;
  57329. var oldDiff = particle.lifeTime - previousAge;
  57330. scaledUpdateSpeed = (oldDiff * scaledUpdateSpeed) / diff;
  57331. particle.age = particle.lifeTime;
  57332. }
  57333. var ratio = particle.age / particle.lifeTime;
  57334. // Color
  57335. if (_this._colorGradients && _this._colorGradients.length > 0) {
  57336. BABYLON.Tools.GetCurrentGradient(ratio, _this._colorGradients, function (currentGradient, nextGradient, scale) {
  57337. if (currentGradient !== particle._currentColorGradient) {
  57338. particle._currentColor1.copyFrom(particle._currentColor2);
  57339. nextGradient.getColorToRef(particle._currentColor2);
  57340. particle._currentColorGradient = currentGradient;
  57341. }
  57342. BABYLON.Color4.LerpToRef(particle._currentColor1, particle._currentColor2, scale, particle.color);
  57343. });
  57344. }
  57345. else {
  57346. particle.colorStep.scaleToRef(scaledUpdateSpeed, _this._scaledColorStep);
  57347. particle.color.addInPlace(_this._scaledColorStep);
  57348. if (particle.color.a < 0) {
  57349. particle.color.a = 0;
  57350. }
  57351. }
  57352. // Angular speed
  57353. if (_this._angularSpeedGradients && _this._angularSpeedGradients.length > 0) {
  57354. BABYLON.Tools.GetCurrentGradient(ratio, _this._angularSpeedGradients, function (currentGradient, nextGradient, scale) {
  57355. if (currentGradient !== particle._currentAngularSpeedGradient) {
  57356. particle._currentAngularSpeed1 = particle._currentAngularSpeed2;
  57357. particle._currentAngularSpeed2 = nextGradient.getFactor();
  57358. particle._currentAngularSpeedGradient = currentGradient;
  57359. }
  57360. particle.angularSpeed = BABYLON.Scalar.Lerp(particle._currentAngularSpeed1, particle._currentAngularSpeed2, scale);
  57361. });
  57362. }
  57363. particle.angle += particle.angularSpeed * scaledUpdateSpeed;
  57364. // Direction
  57365. var directionScale = scaledUpdateSpeed;
  57366. /// Velocity
  57367. if (_this._velocityGradients && _this._velocityGradients.length > 0) {
  57368. BABYLON.Tools.GetCurrentGradient(ratio, _this._velocityGradients, function (currentGradient, nextGradient, scale) {
  57369. if (currentGradient !== particle._currentVelocityGradient) {
  57370. particle._currentVelocity1 = particle._currentVelocity2;
  57371. particle._currentVelocity2 = nextGradient.getFactor();
  57372. particle._currentVelocityGradient = currentGradient;
  57373. }
  57374. directionScale *= BABYLON.Scalar.Lerp(particle._currentVelocity1, particle._currentVelocity2, scale);
  57375. });
  57376. }
  57377. particle.direction.scaleToRef(directionScale, _this._scaledDirection);
  57378. /// Limit velocity
  57379. if (_this._limitVelocityGradients && _this._limitVelocityGradients.length > 0) {
  57380. BABYLON.Tools.GetCurrentGradient(ratio, _this._limitVelocityGradients, function (currentGradient, nextGradient, scale) {
  57381. if (currentGradient !== particle._currentLimitVelocityGradient) {
  57382. particle._currentLimitVelocity1 = particle._currentLimitVelocity2;
  57383. particle._currentLimitVelocity2 = nextGradient.getFactor();
  57384. particle._currentLimitVelocityGradient = currentGradient;
  57385. }
  57386. var limitVelocity = BABYLON.Scalar.Lerp(particle._currentLimitVelocity1, particle._currentLimitVelocity2, scale);
  57387. var currentVelocity = particle.direction.length();
  57388. if (currentVelocity > limitVelocity) {
  57389. particle.direction.scaleInPlace(_this.limitVelocityDamping);
  57390. }
  57391. });
  57392. }
  57393. /// Drag
  57394. if (_this._dragGradients && _this._dragGradients.length > 0) {
  57395. BABYLON.Tools.GetCurrentGradient(ratio, _this._dragGradients, function (currentGradient, nextGradient, scale) {
  57396. if (currentGradient !== particle._currentDragGradient) {
  57397. particle._currentDrag1 = particle._currentDrag2;
  57398. particle._currentDrag2 = nextGradient.getFactor();
  57399. particle._currentDragGradient = currentGradient;
  57400. }
  57401. var drag = BABYLON.Scalar.Lerp(particle._currentDrag1, particle._currentDrag2, scale);
  57402. _this._scaledDirection.scaleInPlace(1.0 - drag);
  57403. });
  57404. }
  57405. particle.position.addInPlace(_this._scaledDirection);
  57406. // Noise
  57407. if (noiseTextureData && noiseTextureSize) {
  57408. var fetchedColorR = _this._fetchR(particle._randomNoiseCoordinates1.x, particle._randomNoiseCoordinates1.y, noiseTextureSize.width, noiseTextureSize.height, noiseTextureData);
  57409. var fetchedColorG = _this._fetchR(particle._randomNoiseCoordinates1.z, particle._randomNoiseCoordinates2.x, noiseTextureSize.width, noiseTextureSize.height, noiseTextureData);
  57410. var fetchedColorB = _this._fetchR(particle._randomNoiseCoordinates2.y, particle._randomNoiseCoordinates2.z, noiseTextureSize.width, noiseTextureSize.height, noiseTextureData);
  57411. var force = BABYLON.Tmp.Vector3[0];
  57412. var scaledForce = BABYLON.Tmp.Vector3[1];
  57413. force.copyFromFloats((2 * fetchedColorR - 1) * _this.noiseStrength.x, (2 * fetchedColorG - 1) * _this.noiseStrength.y, (2 * fetchedColorB - 1) * _this.noiseStrength.z);
  57414. force.scaleToRef(scaledUpdateSpeed, scaledForce);
  57415. particle.direction.addInPlace(scaledForce);
  57416. }
  57417. // Gravity
  57418. _this.gravity.scaleToRef(scaledUpdateSpeed, _this._scaledGravity);
  57419. particle.direction.addInPlace(_this._scaledGravity);
  57420. // Size
  57421. if (_this._sizeGradients && _this._sizeGradients.length > 0) {
  57422. BABYLON.Tools.GetCurrentGradient(ratio, _this._sizeGradients, function (currentGradient, nextGradient, scale) {
  57423. if (currentGradient !== particle._currentSizeGradient) {
  57424. particle._currentSize1 = particle._currentSize2;
  57425. particle._currentSize2 = nextGradient.getFactor();
  57426. particle._currentSizeGradient = currentGradient;
  57427. }
  57428. particle.size = BABYLON.Scalar.Lerp(particle._currentSize1, particle._currentSize2, scale);
  57429. });
  57430. }
  57431. // Remap data
  57432. if (_this._useRampGradients) {
  57433. if (_this._colorRemapGradients && _this._colorRemapGradients.length > 0) {
  57434. BABYLON.Tools.GetCurrentGradient(ratio, _this._colorRemapGradients, function (currentGradient, nextGradient, scale) {
  57435. var min = BABYLON.Scalar.Lerp(currentGradient.factor1, nextGradient.factor1, scale);
  57436. var max = BABYLON.Scalar.Lerp(currentGradient.factor2, nextGradient.factor2, scale);
  57437. particle.remapData.x = min;
  57438. particle.remapData.y = max - min;
  57439. });
  57440. }
  57441. if (_this._alphaRemapGradients && _this._alphaRemapGradients.length > 0) {
  57442. BABYLON.Tools.GetCurrentGradient(ratio, _this._alphaRemapGradients, function (currentGradient, nextGradient, scale) {
  57443. var min = BABYLON.Scalar.Lerp(currentGradient.factor1, nextGradient.factor1, scale);
  57444. var max = BABYLON.Scalar.Lerp(currentGradient.factor2, nextGradient.factor2, scale);
  57445. particle.remapData.z = min;
  57446. particle.remapData.w = max - min;
  57447. });
  57448. }
  57449. }
  57450. if (_this._isAnimationSheetEnabled) {
  57451. particle.updateCellIndex();
  57452. }
  57453. // Update the position of the attached sub-emitters to match their attached particle
  57454. particle._inheritParticleInfoToSubEmitters();
  57455. if (particle.age >= particle.lifeTime) { // Recycle by swapping with last particle
  57456. _this._emitFromParticle(particle);
  57457. if (particle._attachedSubEmitters) {
  57458. particle._attachedSubEmitters.forEach(function (subEmitter) {
  57459. subEmitter.particleSystem.disposeOnStop = true;
  57460. subEmitter.particleSystem.stop();
  57461. });
  57462. particle._attachedSubEmitters = null;
  57463. }
  57464. _this.recycleParticle(particle);
  57465. index--;
  57466. return "continue";
  57467. }
  57468. };
  57469. var particle;
  57470. for (var index = 0; index < particles.length; index++) {
  57471. _loop_1();
  57472. }
  57473. };
  57474. return _this;
  57475. }
  57476. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  57477. /**
  57478. * Sets a callback that will be triggered when the system is disposed
  57479. */
  57480. set: function (callback) {
  57481. if (this._onDisposeObserver) {
  57482. this.onDisposeObservable.remove(this._onDisposeObserver);
  57483. }
  57484. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  57485. },
  57486. enumerable: true,
  57487. configurable: true
  57488. });
  57489. Object.defineProperty(ParticleSystem.prototype, "useRampGradients", {
  57490. /** Gets or sets a boolean indicating that ramp gradients must be used
  57491. * @see http://doc.babylonjs.com/babylon101/particles#ramp-gradients
  57492. */
  57493. get: function () {
  57494. return this._useRampGradients;
  57495. },
  57496. set: function (value) {
  57497. if (this._useRampGradients === value) {
  57498. return;
  57499. }
  57500. this._useRampGradients = value;
  57501. this._resetEffect();
  57502. },
  57503. enumerable: true,
  57504. configurable: true
  57505. });
  57506. Object.defineProperty(ParticleSystem.prototype, "particles", {
  57507. //end of Sub-emitter
  57508. /**
  57509. * Gets the current list of active particles
  57510. */
  57511. get: function () {
  57512. return this._particles;
  57513. },
  57514. enumerable: true,
  57515. configurable: true
  57516. });
  57517. /**
  57518. * Returns the string "ParticleSystem"
  57519. * @returns a string containing the class name
  57520. */
  57521. ParticleSystem.prototype.getClassName = function () {
  57522. return "ParticleSystem";
  57523. };
  57524. ParticleSystem.prototype._addFactorGradient = function (factorGradients, gradient, factor, factor2) {
  57525. var newGradient = new BABYLON.FactorGradient();
  57526. newGradient.gradient = gradient;
  57527. newGradient.factor1 = factor;
  57528. newGradient.factor2 = factor2;
  57529. factorGradients.push(newGradient);
  57530. factorGradients.sort(function (a, b) {
  57531. if (a.gradient < b.gradient) {
  57532. return -1;
  57533. }
  57534. else if (a.gradient > b.gradient) {
  57535. return 1;
  57536. }
  57537. return 0;
  57538. });
  57539. };
  57540. ParticleSystem.prototype._removeFactorGradient = function (factorGradients, gradient) {
  57541. if (!factorGradients) {
  57542. return;
  57543. }
  57544. var index = 0;
  57545. for (var _i = 0, factorGradients_1 = factorGradients; _i < factorGradients_1.length; _i++) {
  57546. var factorGradient = factorGradients_1[_i];
  57547. if (factorGradient.gradient === gradient) {
  57548. factorGradients.splice(index, 1);
  57549. break;
  57550. }
  57551. index++;
  57552. }
  57553. };
  57554. /**
  57555. * Adds a new life time gradient
  57556. * @param gradient defines the gradient to use (between 0 and 1)
  57557. * @param factor defines the life time factor to affect to the specified gradient
  57558. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  57559. * @returns the current particle system
  57560. */
  57561. ParticleSystem.prototype.addLifeTimeGradient = function (gradient, factor, factor2) {
  57562. if (!this._lifeTimeGradients) {
  57563. this._lifeTimeGradients = [];
  57564. }
  57565. this._addFactorGradient(this._lifeTimeGradients, gradient, factor, factor2);
  57566. return this;
  57567. };
  57568. /**
  57569. * Remove a specific life time gradient
  57570. * @param gradient defines the gradient to remove
  57571. * @returns the current particle system
  57572. */
  57573. ParticleSystem.prototype.removeLifeTimeGradient = function (gradient) {
  57574. this._removeFactorGradient(this._lifeTimeGradients, gradient);
  57575. return this;
  57576. };
  57577. /**
  57578. * Adds a new size gradient
  57579. * @param gradient defines the gradient to use (between 0 and 1)
  57580. * @param factor defines the size factor to affect to the specified gradient
  57581. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  57582. * @returns the current particle system
  57583. */
  57584. ParticleSystem.prototype.addSizeGradient = function (gradient, factor, factor2) {
  57585. if (!this._sizeGradients) {
  57586. this._sizeGradients = [];
  57587. }
  57588. this._addFactorGradient(this._sizeGradients, gradient, factor, factor2);
  57589. return this;
  57590. };
  57591. /**
  57592. * Remove a specific size gradient
  57593. * @param gradient defines the gradient to remove
  57594. * @returns the current particle system
  57595. */
  57596. ParticleSystem.prototype.removeSizeGradient = function (gradient) {
  57597. this._removeFactorGradient(this._sizeGradients, gradient);
  57598. return this;
  57599. };
  57600. /**
  57601. * Adds a new color remap gradient
  57602. * @param gradient defines the gradient to use (between 0 and 1)
  57603. * @param min defines the color remap minimal range
  57604. * @param max defines the color remap maximal range
  57605. * @returns the current particle system
  57606. */
  57607. ParticleSystem.prototype.addColorRemapGradient = function (gradient, min, max) {
  57608. if (!this._colorRemapGradients) {
  57609. this._colorRemapGradients = [];
  57610. }
  57611. this._addFactorGradient(this._colorRemapGradients, gradient, min, max);
  57612. return this;
  57613. };
  57614. /**
  57615. * Remove a specific color remap gradient
  57616. * @param gradient defines the gradient to remove
  57617. * @returns the current particle system
  57618. */
  57619. ParticleSystem.prototype.removeColorRemapGradient = function (gradient) {
  57620. this._removeFactorGradient(this._colorRemapGradients, gradient);
  57621. return this;
  57622. };
  57623. /**
  57624. * Adds a new alpha remap gradient
  57625. * @param gradient defines the gradient to use (between 0 and 1)
  57626. * @param min defines the alpha remap minimal range
  57627. * @param max defines the alpha remap maximal range
  57628. * @returns the current particle system
  57629. */
  57630. ParticleSystem.prototype.addAlphaRemapGradient = function (gradient, min, max) {
  57631. if (!this._alphaRemapGradients) {
  57632. this._alphaRemapGradients = [];
  57633. }
  57634. this._addFactorGradient(this._alphaRemapGradients, gradient, min, max);
  57635. return this;
  57636. };
  57637. /**
  57638. * Remove a specific alpha remap gradient
  57639. * @param gradient defines the gradient to remove
  57640. * @returns the current particle system
  57641. */
  57642. ParticleSystem.prototype.removeAlphaRemapGradient = function (gradient) {
  57643. this._removeFactorGradient(this._alphaRemapGradients, gradient);
  57644. return this;
  57645. };
  57646. /**
  57647. * Adds a new angular speed gradient
  57648. * @param gradient defines the gradient to use (between 0 and 1)
  57649. * @param factor defines the angular speed to affect to the specified gradient
  57650. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  57651. * @returns the current particle system
  57652. */
  57653. ParticleSystem.prototype.addAngularSpeedGradient = function (gradient, factor, factor2) {
  57654. if (!this._angularSpeedGradients) {
  57655. this._angularSpeedGradients = [];
  57656. }
  57657. this._addFactorGradient(this._angularSpeedGradients, gradient, factor, factor2);
  57658. return this;
  57659. };
  57660. /**
  57661. * Remove a specific angular speed gradient
  57662. * @param gradient defines the gradient to remove
  57663. * @returns the current particle system
  57664. */
  57665. ParticleSystem.prototype.removeAngularSpeedGradient = function (gradient) {
  57666. this._removeFactorGradient(this._angularSpeedGradients, gradient);
  57667. return this;
  57668. };
  57669. /**
  57670. * Adds a new velocity gradient
  57671. * @param gradient defines the gradient to use (between 0 and 1)
  57672. * @param factor defines the velocity to affect to the specified gradient
  57673. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  57674. * @returns the current particle system
  57675. */
  57676. ParticleSystem.prototype.addVelocityGradient = function (gradient, factor, factor2) {
  57677. if (!this._velocityGradients) {
  57678. this._velocityGradients = [];
  57679. }
  57680. this._addFactorGradient(this._velocityGradients, gradient, factor, factor2);
  57681. return this;
  57682. };
  57683. /**
  57684. * Remove a specific velocity gradient
  57685. * @param gradient defines the gradient to remove
  57686. * @returns the current particle system
  57687. */
  57688. ParticleSystem.prototype.removeVelocityGradient = function (gradient) {
  57689. this._removeFactorGradient(this._velocityGradients, gradient);
  57690. return this;
  57691. };
  57692. /**
  57693. * Adds a new limit velocity gradient
  57694. * @param gradient defines the gradient to use (between 0 and 1)
  57695. * @param factor defines the limit velocity value to affect to the specified gradient
  57696. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  57697. * @returns the current particle system
  57698. */
  57699. ParticleSystem.prototype.addLimitVelocityGradient = function (gradient, factor, factor2) {
  57700. if (!this._limitVelocityGradients) {
  57701. this._limitVelocityGradients = [];
  57702. }
  57703. this._addFactorGradient(this._limitVelocityGradients, gradient, factor, factor2);
  57704. return this;
  57705. };
  57706. /**
  57707. * Remove a specific limit velocity gradient
  57708. * @param gradient defines the gradient to remove
  57709. * @returns the current particle system
  57710. */
  57711. ParticleSystem.prototype.removeLimitVelocityGradient = function (gradient) {
  57712. this._removeFactorGradient(this._limitVelocityGradients, gradient);
  57713. return this;
  57714. };
  57715. /**
  57716. * Adds a new drag gradient
  57717. * @param gradient defines the gradient to use (between 0 and 1)
  57718. * @param factor defines the drag value to affect to the specified gradient
  57719. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  57720. * @returns the current particle system
  57721. */
  57722. ParticleSystem.prototype.addDragGradient = function (gradient, factor, factor2) {
  57723. if (!this._dragGradients) {
  57724. this._dragGradients = [];
  57725. }
  57726. this._addFactorGradient(this._dragGradients, gradient, factor, factor2);
  57727. return this;
  57728. };
  57729. /**
  57730. * Remove a specific drag gradient
  57731. * @param gradient defines the gradient to remove
  57732. * @returns the current particle system
  57733. */
  57734. ParticleSystem.prototype.removeDragGradient = function (gradient) {
  57735. this._removeFactorGradient(this._dragGradients, gradient);
  57736. return this;
  57737. };
  57738. /**
  57739. * Adds a new emit rate gradient (please note that this will only work if you set the targetStopDuration property)
  57740. * @param gradient defines the gradient to use (between 0 and 1)
  57741. * @param factor defines the emit rate value to affect to the specified gradient
  57742. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  57743. * @returns the current particle system
  57744. */
  57745. ParticleSystem.prototype.addEmitRateGradient = function (gradient, factor, factor2) {
  57746. if (!this._emitRateGradients) {
  57747. this._emitRateGradients = [];
  57748. }
  57749. this._addFactorGradient(this._emitRateGradients, gradient, factor, factor2);
  57750. if (!this._currentEmitRateGradient) {
  57751. this._currentEmitRateGradient = this._emitRateGradients[0];
  57752. this._currentEmitRate1 = this._currentEmitRateGradient.getFactor();
  57753. this._currentEmitRate2 = this._currentEmitRate1;
  57754. }
  57755. if (this._emitRateGradients.length === 2) {
  57756. this._currentEmitRate2 = this._emitRateGradients[1].getFactor();
  57757. }
  57758. return this;
  57759. };
  57760. /**
  57761. * Remove a specific emit rate gradient
  57762. * @param gradient defines the gradient to remove
  57763. * @returns the current particle system
  57764. */
  57765. ParticleSystem.prototype.removeEmitRateGradient = function (gradient) {
  57766. this._removeFactorGradient(this._emitRateGradients, gradient);
  57767. return this;
  57768. };
  57769. /**
  57770. * Adds a new start size gradient (please note that this will only work if you set the targetStopDuration property)
  57771. * @param gradient defines the gradient to use (between 0 and 1)
  57772. * @param factor defines the start size value to affect to the specified gradient
  57773. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  57774. * @returns the current particle system
  57775. */
  57776. ParticleSystem.prototype.addStartSizeGradient = function (gradient, factor, factor2) {
  57777. if (!this._startSizeGradients) {
  57778. this._startSizeGradients = [];
  57779. }
  57780. this._addFactorGradient(this._startSizeGradients, gradient, factor, factor2);
  57781. if (!this._currentStartSizeGradient) {
  57782. this._currentStartSizeGradient = this._startSizeGradients[0];
  57783. this._currentStartSize1 = this._currentStartSizeGradient.getFactor();
  57784. this._currentStartSize2 = this._currentStartSize1;
  57785. }
  57786. if (this._startSizeGradients.length === 2) {
  57787. this._currentStartSize2 = this._startSizeGradients[1].getFactor();
  57788. }
  57789. return this;
  57790. };
  57791. /**
  57792. * Remove a specific start size gradient
  57793. * @param gradient defines the gradient to remove
  57794. * @returns the current particle system
  57795. */
  57796. ParticleSystem.prototype.removeStartSizeGradient = function (gradient) {
  57797. this._removeFactorGradient(this._emitRateGradients, gradient);
  57798. return this;
  57799. };
  57800. ParticleSystem.prototype._createRampGradientTexture = function () {
  57801. if (!this._rampGradients || !this._rampGradients.length || this._rampGradientsTexture) {
  57802. return;
  57803. }
  57804. var data = new Uint8Array(this._rawTextureWidth * 4);
  57805. var tmpColor = BABYLON.Tmp.Color3[0];
  57806. for (var x = 0; x < this._rawTextureWidth; x++) {
  57807. var ratio = x / this._rawTextureWidth;
  57808. BABYLON.Tools.GetCurrentGradient(ratio, this._rampGradients, function (currentGradient, nextGradient, scale) {
  57809. BABYLON.Color3.LerpToRef(currentGradient.color, nextGradient.color, scale, tmpColor);
  57810. data[x * 4] = tmpColor.r * 255;
  57811. data[x * 4 + 1] = tmpColor.g * 255;
  57812. data[x * 4 + 2] = tmpColor.b * 255;
  57813. data[x * 4 + 3] = 255;
  57814. });
  57815. }
  57816. this._rampGradientsTexture = BABYLON.RawTexture.CreateRGBATexture(data, this._rawTextureWidth, 1, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  57817. };
  57818. /**
  57819. * Gets the current list of ramp gradients.
  57820. * You must use addRampGradient and removeRampGradient to udpate this list
  57821. * @returns the list of ramp gradients
  57822. */
  57823. ParticleSystem.prototype.getRampGradients = function () {
  57824. return this._rampGradients;
  57825. };
  57826. /**
  57827. * Adds a new ramp gradient used to remap particle colors
  57828. * @param gradient defines the gradient to use (between 0 and 1)
  57829. * @param color defines the color to affect to the specified gradient
  57830. * @returns the current particle system
  57831. */
  57832. ParticleSystem.prototype.addRampGradient = function (gradient, color) {
  57833. if (!this._rampGradients) {
  57834. this._rampGradients = [];
  57835. }
  57836. var rampGradient = new BABYLON.Color3Gradient();
  57837. rampGradient.gradient = gradient;
  57838. rampGradient.color = color;
  57839. this._rampGradients.push(rampGradient);
  57840. this._rampGradients.sort(function (a, b) {
  57841. if (a.gradient < b.gradient) {
  57842. return -1;
  57843. }
  57844. else if (a.gradient > b.gradient) {
  57845. return 1;
  57846. }
  57847. return 0;
  57848. });
  57849. if (this._rampGradientsTexture) {
  57850. this._rampGradientsTexture.dispose();
  57851. this._rampGradientsTexture = null;
  57852. }
  57853. this._createRampGradientTexture();
  57854. return this;
  57855. };
  57856. /**
  57857. * Remove a specific ramp gradient
  57858. * @param gradient defines the gradient to remove
  57859. * @returns the current particle system
  57860. */
  57861. ParticleSystem.prototype.removeRampGradient = function (gradient) {
  57862. this._removeGradientAndTexture(gradient, this._rampGradients, this._rampGradientsTexture);
  57863. this._rampGradientsTexture = null;
  57864. if (this._rampGradients && this._rampGradients.length > 0) {
  57865. this._createRampGradientTexture();
  57866. }
  57867. return this;
  57868. };
  57869. /**
  57870. * Adds a new color gradient
  57871. * @param gradient defines the gradient to use (between 0 and 1)
  57872. * @param color1 defines the color to affect to the specified gradient
  57873. * @param color2 defines an additional color used to define a range ([color, color2]) with main color to pick the final color from
  57874. */
  57875. ParticleSystem.prototype.addColorGradient = function (gradient, color1, color2) {
  57876. if (!this._colorGradients) {
  57877. this._colorGradients = [];
  57878. }
  57879. var colorGradient = new BABYLON.ColorGradient();
  57880. colorGradient.gradient = gradient;
  57881. colorGradient.color1 = color1;
  57882. colorGradient.color2 = color2;
  57883. this._colorGradients.push(colorGradient);
  57884. this._colorGradients.sort(function (a, b) {
  57885. if (a.gradient < b.gradient) {
  57886. return -1;
  57887. }
  57888. else if (a.gradient > b.gradient) {
  57889. return 1;
  57890. }
  57891. return 0;
  57892. });
  57893. return this;
  57894. };
  57895. /**
  57896. * Remove a specific color gradient
  57897. * @param gradient defines the gradient to remove
  57898. */
  57899. ParticleSystem.prototype.removeColorGradient = function (gradient) {
  57900. if (!this._colorGradients) {
  57901. return this;
  57902. }
  57903. var index = 0;
  57904. for (var _i = 0, _a = this._colorGradients; _i < _a.length; _i++) {
  57905. var colorGradient = _a[_i];
  57906. if (colorGradient.gradient === gradient) {
  57907. this._colorGradients.splice(index, 1);
  57908. break;
  57909. }
  57910. index++;
  57911. }
  57912. return this;
  57913. };
  57914. ParticleSystem.prototype._fetchR = function (u, v, width, height, pixels) {
  57915. u = Math.abs(u) * 0.5 + 0.5;
  57916. v = Math.abs(v) * 0.5 + 0.5;
  57917. var wrappedU = ((u * width) % width) | 0;
  57918. var wrappedV = ((v * height) % height) | 0;
  57919. var position = (wrappedU + wrappedV * width) * 4;
  57920. return pixels[position] / 255;
  57921. };
  57922. ParticleSystem.prototype._reset = function () {
  57923. this._resetEffect();
  57924. };
  57925. ParticleSystem.prototype._resetEffect = function () {
  57926. if (this._vertexBuffer) {
  57927. this._vertexBuffer.dispose();
  57928. this._vertexBuffer = null;
  57929. }
  57930. if (this._spriteBuffer) {
  57931. this._spriteBuffer.dispose();
  57932. this._spriteBuffer = null;
  57933. }
  57934. this._createVertexBuffers();
  57935. };
  57936. ParticleSystem.prototype._createVertexBuffers = function () {
  57937. this._vertexBufferSize = this._useInstancing ? 10 : 12;
  57938. if (this._isAnimationSheetEnabled) {
  57939. this._vertexBufferSize += 1;
  57940. }
  57941. if (!this._isBillboardBased || this.billboardMode === ParticleSystem.BILLBOARDMODE_STRETCHED) {
  57942. this._vertexBufferSize += 3;
  57943. }
  57944. if (this._useRampGradients) {
  57945. this._vertexBufferSize += 4;
  57946. }
  57947. var engine = this._scene.getEngine();
  57948. this._vertexData = new Float32Array(this._capacity * this._vertexBufferSize * (this._useInstancing ? 1 : 4));
  57949. this._vertexBuffer = new BABYLON.Buffer(engine, this._vertexData, true, this._vertexBufferSize);
  57950. var dataOffset = 0;
  57951. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, dataOffset, 3, this._vertexBufferSize, this._useInstancing);
  57952. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  57953. dataOffset += 3;
  57954. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, dataOffset, 4, this._vertexBufferSize, this._useInstancing);
  57955. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  57956. dataOffset += 4;
  57957. var options = this._vertexBuffer.createVertexBuffer("angle", dataOffset, 1, this._vertexBufferSize, this._useInstancing);
  57958. this._vertexBuffers["angle"] = options;
  57959. dataOffset += 1;
  57960. var size = this._vertexBuffer.createVertexBuffer("size", dataOffset, 2, this._vertexBufferSize, this._useInstancing);
  57961. this._vertexBuffers["size"] = size;
  57962. dataOffset += 2;
  57963. if (this._isAnimationSheetEnabled) {
  57964. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", dataOffset, 1, this._vertexBufferSize, this._useInstancing);
  57965. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  57966. dataOffset += 1;
  57967. }
  57968. if (!this._isBillboardBased || this.billboardMode === ParticleSystem.BILLBOARDMODE_STRETCHED) {
  57969. var directionBuffer = this._vertexBuffer.createVertexBuffer("direction", dataOffset, 3, this._vertexBufferSize, this._useInstancing);
  57970. this._vertexBuffers["direction"] = directionBuffer;
  57971. dataOffset += 3;
  57972. }
  57973. if (this._useRampGradients) {
  57974. var rampDataBuffer = this._vertexBuffer.createVertexBuffer("remapData", dataOffset, 4, this._vertexBufferSize, this._useInstancing);
  57975. this._vertexBuffers["remapData"] = rampDataBuffer;
  57976. dataOffset += 4;
  57977. }
  57978. var offsets;
  57979. if (this._useInstancing) {
  57980. var spriteData = new Float32Array([0, 0, 1, 0, 1, 1, 0, 1]);
  57981. this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 2);
  57982. offsets = this._spriteBuffer.createVertexBuffer("offset", 0, 2);
  57983. }
  57984. else {
  57985. offsets = this._vertexBuffer.createVertexBuffer("offset", dataOffset, 2, this._vertexBufferSize, this._useInstancing);
  57986. dataOffset += 2;
  57987. }
  57988. this._vertexBuffers["offset"] = offsets;
  57989. };
  57990. ParticleSystem.prototype._createIndexBuffer = function () {
  57991. if (this._useInstancing) {
  57992. return;
  57993. }
  57994. var indices = [];
  57995. var index = 0;
  57996. for (var count = 0; count < this._capacity; count++) {
  57997. indices.push(index);
  57998. indices.push(index + 1);
  57999. indices.push(index + 2);
  58000. indices.push(index);
  58001. indices.push(index + 2);
  58002. indices.push(index + 3);
  58003. index += 4;
  58004. }
  58005. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  58006. };
  58007. /**
  58008. * Gets the maximum number of particles active at the same time.
  58009. * @returns The max number of active particles.
  58010. */
  58011. ParticleSystem.prototype.getCapacity = function () {
  58012. return this._capacity;
  58013. };
  58014. /**
  58015. * Gets whether there are still active particles in the system.
  58016. * @returns True if it is alive, otherwise false.
  58017. */
  58018. ParticleSystem.prototype.isAlive = function () {
  58019. return this._alive;
  58020. };
  58021. /**
  58022. * Gets if the system has been started. (Note: this will still be true after stop is called)
  58023. * @returns True if it has been started, otherwise false.
  58024. */
  58025. ParticleSystem.prototype.isStarted = function () {
  58026. return this._started;
  58027. };
  58028. ParticleSystem.prototype._prepareSubEmitterInternalArray = function () {
  58029. var _this = this;
  58030. this._subEmitters = new Array();
  58031. if (this.subEmitters) {
  58032. this.subEmitters.forEach(function (subEmitter) {
  58033. if (subEmitter instanceof ParticleSystem) {
  58034. _this._subEmitters.push([new BABYLON.SubEmitter(subEmitter)]);
  58035. }
  58036. else if (subEmitter instanceof BABYLON.SubEmitter) {
  58037. _this._subEmitters.push([subEmitter]);
  58038. }
  58039. else if (subEmitter instanceof Array) {
  58040. _this._subEmitters.push(subEmitter);
  58041. }
  58042. _this._subEmitters[_this._subEmitters.length - 1].forEach(function (se) {
  58043. if (!(se.particleSystem.emitter instanceof BABYLON.AbstractMesh) && se.inheritDirection) {
  58044. BABYLON.Tools.Warn("subEmitter.inheritDirection is not supported with non-mesh emitter type");
  58045. }
  58046. });
  58047. });
  58048. }
  58049. };
  58050. /**
  58051. * Starts the particle system and begins to emit
  58052. * @param delay defines the delay in milliseconds before starting the system (this.startDelay by default)
  58053. */
  58054. ParticleSystem.prototype.start = function (delay) {
  58055. var _this = this;
  58056. if (delay === void 0) { delay = this.startDelay; }
  58057. if (!this.targetStopDuration && this._hasTargetStopDurationDependantGradient()) {
  58058. throw "Particle system started with a targetStopDuration dependant gradient (eg. startSizeGradients) but no targetStopDuration set";
  58059. }
  58060. if (delay) {
  58061. setTimeout(function () {
  58062. _this.start(0);
  58063. }, delay);
  58064. return;
  58065. }
  58066. // Convert the subEmitters field to the constant type field _subEmitters
  58067. this._prepareSubEmitterInternalArray();
  58068. this._started = true;
  58069. this._stopped = false;
  58070. this._actualFrame = 0;
  58071. if (this._subEmitters && this._subEmitters.length != 0) {
  58072. this.activeSubSystems = new Array();
  58073. }
  58074. if (this.preWarmCycles) {
  58075. if (this.emitter instanceof BABYLON.AbstractMesh) {
  58076. this.emitter.computeWorldMatrix(true);
  58077. }
  58078. var noiseTextureAsProcedural_1 = this.noiseTexture;
  58079. if (noiseTextureAsProcedural_1 && noiseTextureAsProcedural_1.onGeneratedObservable) {
  58080. noiseTextureAsProcedural_1.onGeneratedObservable.addOnce(function () {
  58081. setTimeout(function () {
  58082. for (var index = 0; index < _this.preWarmCycles; index++) {
  58083. _this.animate(true);
  58084. noiseTextureAsProcedural_1.render();
  58085. }
  58086. });
  58087. });
  58088. }
  58089. else {
  58090. for (var index = 0; index < this.preWarmCycles; index++) {
  58091. this.animate(true);
  58092. }
  58093. }
  58094. }
  58095. };
  58096. /**
  58097. * Stops the particle system.
  58098. * @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.
  58099. */
  58100. ParticleSystem.prototype.stop = function (stopSubEmitters) {
  58101. if (stopSubEmitters === void 0) { stopSubEmitters = true; }
  58102. this._stopped = true;
  58103. if (stopSubEmitters) {
  58104. this._stopSubEmitters();
  58105. }
  58106. };
  58107. // animation sheet
  58108. /**
  58109. * Remove all active particles
  58110. */
  58111. ParticleSystem.prototype.reset = function () {
  58112. this._stockParticles = [];
  58113. this._particles = [];
  58114. };
  58115. /**
  58116. * @hidden (for internal use only)
  58117. */
  58118. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  58119. var offset = index * this._vertexBufferSize;
  58120. this._vertexData[offset++] = particle.position.x;
  58121. this._vertexData[offset++] = particle.position.y;
  58122. this._vertexData[offset++] = particle.position.z;
  58123. this._vertexData[offset++] = particle.color.r;
  58124. this._vertexData[offset++] = particle.color.g;
  58125. this._vertexData[offset++] = particle.color.b;
  58126. this._vertexData[offset++] = particle.color.a;
  58127. this._vertexData[offset++] = particle.angle;
  58128. this._vertexData[offset++] = particle.scale.x * particle.size;
  58129. this._vertexData[offset++] = particle.scale.y * particle.size;
  58130. if (this._isAnimationSheetEnabled) {
  58131. this._vertexData[offset++] = particle.cellIndex;
  58132. }
  58133. if (!this._isBillboardBased) {
  58134. if (particle._initialDirection) {
  58135. this._vertexData[offset++] = particle._initialDirection.x;
  58136. this._vertexData[offset++] = particle._initialDirection.y;
  58137. this._vertexData[offset++] = particle._initialDirection.z;
  58138. }
  58139. else {
  58140. this._vertexData[offset++] = particle.direction.x;
  58141. this._vertexData[offset++] = particle.direction.y;
  58142. this._vertexData[offset++] = particle.direction.z;
  58143. }
  58144. }
  58145. else if (this.billboardMode === ParticleSystem.BILLBOARDMODE_STRETCHED) {
  58146. this._vertexData[offset++] = particle.direction.x;
  58147. this._vertexData[offset++] = particle.direction.y;
  58148. this._vertexData[offset++] = particle.direction.z;
  58149. }
  58150. if (this._useRampGradients) {
  58151. this._vertexData[offset++] = particle.remapData.x;
  58152. this._vertexData[offset++] = particle.remapData.y;
  58153. this._vertexData[offset++] = particle.remapData.z;
  58154. this._vertexData[offset++] = particle.remapData.w;
  58155. }
  58156. if (!this._useInstancing) {
  58157. if (this._isAnimationSheetEnabled) {
  58158. if (offsetX === 0)
  58159. offsetX = this._epsilon;
  58160. else if (offsetX === 1)
  58161. offsetX = 1 - this._epsilon;
  58162. if (offsetY === 0)
  58163. offsetY = this._epsilon;
  58164. else if (offsetY === 1)
  58165. offsetY = 1 - this._epsilon;
  58166. }
  58167. this._vertexData[offset++] = offsetX;
  58168. this._vertexData[offset++] = offsetY;
  58169. }
  58170. };
  58171. ParticleSystem.prototype._stopSubEmitters = function () {
  58172. if (!this.activeSubSystems) {
  58173. return;
  58174. }
  58175. this.activeSubSystems.forEach(function (subSystem) {
  58176. subSystem.stop(true);
  58177. });
  58178. this.activeSubSystems = new Array();
  58179. };
  58180. ParticleSystem.prototype._removeFromRoot = function () {
  58181. if (!this._rootParticleSystem) {
  58182. return;
  58183. }
  58184. var index = this._rootParticleSystem.activeSubSystems.indexOf(this);
  58185. if (index !== -1) {
  58186. this._rootParticleSystem.activeSubSystems.splice(index, 1);
  58187. }
  58188. this._rootParticleSystem = null;
  58189. };
  58190. // End of sub system methods
  58191. ParticleSystem.prototype._update = function (newParticles) {
  58192. var _this = this;
  58193. // Update current
  58194. this._alive = this._particles.length > 0;
  58195. if (this.emitter.position) {
  58196. var emitterMesh = this.emitter;
  58197. this._emitterWorldMatrix = emitterMesh.getWorldMatrix();
  58198. }
  58199. else {
  58200. var emitterPosition = this.emitter;
  58201. this._emitterWorldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  58202. }
  58203. this.updateFunction(this._particles);
  58204. // Add new ones
  58205. var particle;
  58206. var _loop_2 = function () {
  58207. if (this_1._particles.length === this_1._capacity) {
  58208. return "break";
  58209. }
  58210. particle = this_1._createParticle();
  58211. this_1._particles.push(particle);
  58212. // Emitter
  58213. var emitPower = BABYLON.Scalar.RandomRange(this_1.minEmitPower, this_1.maxEmitPower);
  58214. if (this_1.startPositionFunction) {
  58215. this_1.startPositionFunction(this_1._emitterWorldMatrix, particle.position, particle);
  58216. }
  58217. else {
  58218. this_1.particleEmitterType.startPositionFunction(this_1._emitterWorldMatrix, particle.position, particle);
  58219. }
  58220. if (this_1.startDirectionFunction) {
  58221. this_1.startDirectionFunction(this_1._emitterWorldMatrix, particle.direction, particle);
  58222. }
  58223. else {
  58224. this_1.particleEmitterType.startDirectionFunction(this_1._emitterWorldMatrix, particle.direction, particle);
  58225. }
  58226. if (emitPower === 0) {
  58227. if (!particle._initialDirection) {
  58228. particle._initialDirection = particle.direction.clone();
  58229. }
  58230. else {
  58231. particle._initialDirection.copyFrom(particle.direction);
  58232. }
  58233. }
  58234. else {
  58235. particle._initialDirection = null;
  58236. }
  58237. particle.direction.scaleInPlace(emitPower);
  58238. // Life time
  58239. if (this_1.targetStopDuration && this_1._lifeTimeGradients && this_1._lifeTimeGradients.length > 0) {
  58240. var ratio_1 = BABYLON.Scalar.Clamp(this_1._actualFrame / this_1.targetStopDuration);
  58241. BABYLON.Tools.GetCurrentGradient(ratio_1, this_1._lifeTimeGradients, function (currentGradient, nextGradient, scale) {
  58242. var factorGradient1 = currentGradient;
  58243. var factorGradient2 = nextGradient;
  58244. var lifeTime1 = factorGradient1.getFactor();
  58245. var lifeTime2 = factorGradient2.getFactor();
  58246. var gradient = (ratio_1 - factorGradient1.gradient) / (factorGradient2.gradient - factorGradient1.gradient);
  58247. particle.lifeTime = BABYLON.Scalar.Lerp(lifeTime1, lifeTime2, gradient);
  58248. });
  58249. }
  58250. else {
  58251. particle.lifeTime = BABYLON.Scalar.RandomRange(this_1.minLifeTime, this_1.maxLifeTime);
  58252. }
  58253. // Size
  58254. if (!this_1._sizeGradients || this_1._sizeGradients.length === 0) {
  58255. particle.size = BABYLON.Scalar.RandomRange(this_1.minSize, this_1.maxSize);
  58256. }
  58257. else {
  58258. particle._currentSizeGradient = this_1._sizeGradients[0];
  58259. particle._currentSize1 = particle._currentSizeGradient.getFactor();
  58260. particle.size = particle._currentSize1;
  58261. if (this_1._sizeGradients.length > 1) {
  58262. particle._currentSize2 = this_1._sizeGradients[1].getFactor();
  58263. }
  58264. else {
  58265. particle._currentSize2 = particle._currentSize1;
  58266. }
  58267. }
  58268. // Size and scale
  58269. particle.scale.copyFromFloats(BABYLON.Scalar.RandomRange(this_1.minScaleX, this_1.maxScaleX), BABYLON.Scalar.RandomRange(this_1.minScaleY, this_1.maxScaleY));
  58270. // Adjust scale by start size
  58271. if (this_1._startSizeGradients && this_1._startSizeGradients[0] && this_1.targetStopDuration) {
  58272. var ratio = this_1._actualFrame / this_1.targetStopDuration;
  58273. BABYLON.Tools.GetCurrentGradient(ratio, this_1._startSizeGradients, function (currentGradient, nextGradient, scale) {
  58274. if (currentGradient !== _this._currentStartSizeGradient) {
  58275. _this._currentStartSize1 = _this._currentStartSize2;
  58276. _this._currentStartSize2 = nextGradient.getFactor();
  58277. _this._currentStartSizeGradient = currentGradient;
  58278. }
  58279. var value = BABYLON.Scalar.Lerp(_this._currentStartSize1, _this._currentStartSize2, scale);
  58280. particle.scale.scaleInPlace(value);
  58281. });
  58282. }
  58283. // Angle
  58284. if (!this_1._angularSpeedGradients || this_1._angularSpeedGradients.length === 0) {
  58285. particle.angularSpeed = BABYLON.Scalar.RandomRange(this_1.minAngularSpeed, this_1.maxAngularSpeed);
  58286. }
  58287. else {
  58288. particle._currentAngularSpeedGradient = this_1._angularSpeedGradients[0];
  58289. particle.angularSpeed = particle._currentAngularSpeedGradient.getFactor();
  58290. particle._currentAngularSpeed1 = particle.angularSpeed;
  58291. if (this_1._angularSpeedGradients.length > 1) {
  58292. particle._currentAngularSpeed2 = this_1._angularSpeedGradients[1].getFactor();
  58293. }
  58294. else {
  58295. particle._currentAngularSpeed2 = particle._currentAngularSpeed1;
  58296. }
  58297. }
  58298. particle.angle = BABYLON.Scalar.RandomRange(this_1.minInitialRotation, this_1.maxInitialRotation);
  58299. // Velocity
  58300. if (this_1._velocityGradients && this_1._velocityGradients.length > 0) {
  58301. particle._currentVelocityGradient = this_1._velocityGradients[0];
  58302. particle._currentVelocity1 = particle._currentVelocityGradient.getFactor();
  58303. if (this_1._velocityGradients.length > 1) {
  58304. particle._currentVelocity2 = this_1._velocityGradients[1].getFactor();
  58305. }
  58306. else {
  58307. particle._currentVelocity2 = particle._currentVelocity1;
  58308. }
  58309. }
  58310. // Limit velocity
  58311. if (this_1._limitVelocityGradients && this_1._limitVelocityGradients.length > 0) {
  58312. particle._currentLimitVelocityGradient = this_1._limitVelocityGradients[0];
  58313. particle._currentLimitVelocity1 = particle._currentLimitVelocityGradient.getFactor();
  58314. if (this_1._limitVelocityGradients.length > 1) {
  58315. particle._currentLimitVelocity2 = this_1._limitVelocityGradients[1].getFactor();
  58316. }
  58317. else {
  58318. particle._currentLimitVelocity2 = particle._currentLimitVelocity1;
  58319. }
  58320. }
  58321. // Drag
  58322. if (this_1._dragGradients && this_1._dragGradients.length > 0) {
  58323. particle._currentDragGradient = this_1._dragGradients[0];
  58324. particle._currentDrag1 = particle._currentDragGradient.getFactor();
  58325. if (this_1._dragGradients.length > 1) {
  58326. particle._currentDrag2 = this_1._dragGradients[1].getFactor();
  58327. }
  58328. else {
  58329. particle._currentDrag2 = particle._currentDrag1;
  58330. }
  58331. }
  58332. // Color
  58333. if (!this_1._colorGradients || this_1._colorGradients.length === 0) {
  58334. step = BABYLON.Scalar.RandomRange(0, 1.0);
  58335. BABYLON.Color4.LerpToRef(this_1.color1, this_1.color2, step, particle.color);
  58336. this_1.colorDead.subtractToRef(particle.color, this_1._colorDiff);
  58337. this_1._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  58338. }
  58339. else {
  58340. particle._currentColorGradient = this_1._colorGradients[0];
  58341. particle._currentColorGradient.getColorToRef(particle.color);
  58342. particle._currentColor1.copyFrom(particle.color);
  58343. if (this_1._colorGradients.length > 1) {
  58344. this_1._colorGradients[1].getColorToRef(particle._currentColor2);
  58345. }
  58346. else {
  58347. particle._currentColor2.copyFrom(particle.color);
  58348. }
  58349. }
  58350. // Sheet
  58351. if (this_1._isAnimationSheetEnabled) {
  58352. particle._initialStartSpriteCellID = this_1.startSpriteCellID;
  58353. particle._initialEndSpriteCellID = this_1.endSpriteCellID;
  58354. }
  58355. // Inherited Velocity
  58356. particle.direction.addInPlace(this_1._inheritedVelocityOffset);
  58357. // Ramp
  58358. if (this_1._useRampGradients) {
  58359. particle.remapData = new BABYLON.Vector4(0, 1, 0, 1);
  58360. }
  58361. // Noise texture coordinates
  58362. if (this_1.noiseTexture) {
  58363. if (particle._randomNoiseCoordinates1) {
  58364. particle._randomNoiseCoordinates1.copyFromFloats(Math.random(), Math.random(), Math.random());
  58365. particle._randomNoiseCoordinates2.copyFromFloats(Math.random(), Math.random(), Math.random());
  58366. }
  58367. else {
  58368. particle._randomNoiseCoordinates1 = new BABYLON.Vector3(Math.random(), Math.random(), Math.random());
  58369. particle._randomNoiseCoordinates2 = new BABYLON.Vector3(Math.random(), Math.random(), Math.random());
  58370. }
  58371. }
  58372. // Update the position of the attached sub-emitters to match their attached particle
  58373. particle._inheritParticleInfoToSubEmitters();
  58374. };
  58375. var this_1 = this, step;
  58376. for (var index = 0; index < newParticles; index++) {
  58377. var state_1 = _loop_2();
  58378. if (state_1 === "break")
  58379. break;
  58380. }
  58381. };
  58382. /** @hidden */
  58383. ParticleSystem._GetAttributeNamesOrOptions = function (isAnimationSheetEnabled, isBillboardBased, useRampGradients) {
  58384. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  58385. if (isBillboardBased === void 0) { isBillboardBased = false; }
  58386. if (useRampGradients === void 0) { useRampGradients = false; }
  58387. var attributeNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "angle", "offset", "size"];
  58388. if (isAnimationSheetEnabled) {
  58389. attributeNamesOrOptions.push("cellIndex");
  58390. }
  58391. if (!isBillboardBased) {
  58392. attributeNamesOrOptions.push("direction");
  58393. }
  58394. if (useRampGradients) {
  58395. attributeNamesOrOptions.push("remapData");
  58396. }
  58397. return attributeNamesOrOptions;
  58398. };
  58399. ParticleSystem._GetEffectCreationOptions = function (isAnimationSheetEnabled) {
  58400. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  58401. var effectCreationOption = ["invView", "view", "projection", "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "textureMask", "translationPivot", "eyePosition"];
  58402. if (isAnimationSheetEnabled) {
  58403. effectCreationOption.push("particlesInfos");
  58404. }
  58405. return effectCreationOption;
  58406. };
  58407. ParticleSystem.prototype._getEffect = function (blendMode) {
  58408. if (this._customEffect) {
  58409. return this._customEffect;
  58410. }
  58411. ;
  58412. var defines = [];
  58413. if (this._scene.clipPlane) {
  58414. defines.push("#define CLIPPLANE");
  58415. }
  58416. if (this._scene.clipPlane2) {
  58417. defines.push("#define CLIPPLANE2");
  58418. }
  58419. if (this._scene.clipPlane3) {
  58420. defines.push("#define CLIPPLANE3");
  58421. }
  58422. if (this._scene.clipPlane4) {
  58423. defines.push("#define CLIPPLANE4");
  58424. }
  58425. if (this._isAnimationSheetEnabled) {
  58426. defines.push("#define ANIMATESHEET");
  58427. }
  58428. if (blendMode === ParticleSystem.BLENDMODE_MULTIPLY) {
  58429. defines.push("#define BLENDMULTIPLYMODE");
  58430. }
  58431. if (this._useRampGradients) {
  58432. defines.push("#define RAMPGRADIENT");
  58433. }
  58434. if (this._isBillboardBased) {
  58435. defines.push("#define BILLBOARD");
  58436. switch (this.billboardMode) {
  58437. case ParticleSystem.BILLBOARDMODE_Y:
  58438. defines.push("#define BILLBOARDY");
  58439. break;
  58440. case ParticleSystem.BILLBOARDMODE_STRETCHED:
  58441. defines.push("#define BILLBOARDSTRETCHED");
  58442. break;
  58443. case ParticleSystem.BILLBOARDMODE_ALL:
  58444. default:
  58445. break;
  58446. }
  58447. }
  58448. if (this._imageProcessingConfiguration) {
  58449. this._imageProcessingConfiguration.prepareDefines(this._imageProcessingConfigurationDefines);
  58450. defines.push(this._imageProcessingConfigurationDefines.toString());
  58451. }
  58452. // Effect
  58453. var join = defines.join("\n");
  58454. if (this._cachedDefines !== join) {
  58455. this._cachedDefines = join;
  58456. var attributesNamesOrOptions = ParticleSystem._GetAttributeNamesOrOptions(this._isAnimationSheetEnabled, this._isBillboardBased && this.billboardMode !== ParticleSystem.BILLBOARDMODE_STRETCHED, this._useRampGradients);
  58457. var effectCreationOption = ParticleSystem._GetEffectCreationOptions(this._isAnimationSheetEnabled);
  58458. var samplers = ["diffuseSampler", "rampSampler"];
  58459. if (BABYLON.ImageProcessingConfiguration) {
  58460. BABYLON.ImageProcessingConfiguration.PrepareUniforms(effectCreationOption, this._imageProcessingConfigurationDefines);
  58461. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._imageProcessingConfigurationDefines);
  58462. }
  58463. this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, samplers, join);
  58464. }
  58465. return this._effect;
  58466. };
  58467. /**
  58468. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  58469. * @param preWarmOnly will prevent the system from updating the vertex buffer (default is false)
  58470. */
  58471. ParticleSystem.prototype.animate = function (preWarmOnly) {
  58472. var _this = this;
  58473. if (preWarmOnly === void 0) { preWarmOnly = false; }
  58474. if (!this._started)
  58475. return;
  58476. if (!preWarmOnly) {
  58477. // Check
  58478. if (!this.isReady())
  58479. return;
  58480. if (this._currentRenderId === this._scene.getRenderId()) {
  58481. return;
  58482. }
  58483. this._currentRenderId = this._scene.getRenderId();
  58484. }
  58485. this._scaledUpdateSpeed = this.updateSpeed * (preWarmOnly ? this.preWarmStepOffset : this._scene.getAnimationRatio());
  58486. // Determine the number of particles we need to create
  58487. var newParticles;
  58488. if (this.manualEmitCount > -1) {
  58489. newParticles = this.manualEmitCount;
  58490. this._newPartsExcess = 0;
  58491. this.manualEmitCount = 0;
  58492. }
  58493. else {
  58494. var rate_1 = this.emitRate;
  58495. if (this._emitRateGradients && this._emitRateGradients.length > 0 && this.targetStopDuration) {
  58496. var ratio = this._actualFrame / this.targetStopDuration;
  58497. BABYLON.Tools.GetCurrentGradient(ratio, this._emitRateGradients, function (currentGradient, nextGradient, scale) {
  58498. if (currentGradient !== _this._currentEmitRateGradient) {
  58499. _this._currentEmitRate1 = _this._currentEmitRate2;
  58500. _this._currentEmitRate2 = nextGradient.getFactor();
  58501. _this._currentEmitRateGradient = currentGradient;
  58502. }
  58503. rate_1 = BABYLON.Scalar.Lerp(_this._currentEmitRate1, _this._currentEmitRate2, scale);
  58504. });
  58505. }
  58506. newParticles = ((rate_1 * this._scaledUpdateSpeed) >> 0);
  58507. this._newPartsExcess += rate_1 * this._scaledUpdateSpeed - newParticles;
  58508. }
  58509. if (this._newPartsExcess > 1.0) {
  58510. newParticles += this._newPartsExcess >> 0;
  58511. this._newPartsExcess -= this._newPartsExcess >> 0;
  58512. }
  58513. this._alive = false;
  58514. if (!this._stopped) {
  58515. this._actualFrame += this._scaledUpdateSpeed;
  58516. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  58517. this.stop();
  58518. }
  58519. else {
  58520. newParticles = 0;
  58521. }
  58522. this._update(newParticles);
  58523. // Stopped?
  58524. if (this._stopped) {
  58525. if (!this._alive) {
  58526. this._started = false;
  58527. if (this.onAnimationEnd) {
  58528. this.onAnimationEnd();
  58529. }
  58530. if (this.disposeOnStop) {
  58531. this._scene._toBeDisposed.push(this);
  58532. }
  58533. }
  58534. }
  58535. if (!preWarmOnly) {
  58536. // Update VBO
  58537. var offset = 0;
  58538. for (var index = 0; index < this._particles.length; index++) {
  58539. var particle = this._particles[index];
  58540. this._appendParticleVertices(offset, particle);
  58541. offset += this._useInstancing ? 1 : 4;
  58542. }
  58543. if (this._vertexBuffer) {
  58544. this._vertexBuffer.update(this._vertexData);
  58545. }
  58546. }
  58547. if (this.manualEmitCount === 0 && this.disposeOnStop) {
  58548. this.stop();
  58549. }
  58550. };
  58551. ParticleSystem.prototype._appendParticleVertices = function (offset, particle) {
  58552. this._appendParticleVertex(offset++, particle, 0, 0);
  58553. if (!this._useInstancing) {
  58554. this._appendParticleVertex(offset++, particle, 1, 0);
  58555. this._appendParticleVertex(offset++, particle, 1, 1);
  58556. this._appendParticleVertex(offset++, particle, 0, 1);
  58557. }
  58558. };
  58559. /**
  58560. * Rebuilds the particle system.
  58561. */
  58562. ParticleSystem.prototype.rebuild = function () {
  58563. this._createIndexBuffer();
  58564. if (this._vertexBuffer) {
  58565. this._vertexBuffer._rebuild();
  58566. }
  58567. };
  58568. /**
  58569. * Is this system ready to be used/rendered
  58570. * @return true if the system is ready
  58571. */
  58572. ParticleSystem.prototype.isReady = function () {
  58573. if (!this.emitter || !this._imageProcessingConfiguration.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  58574. return false;
  58575. }
  58576. if (this.blendMode !== ParticleSystem.BLENDMODE_MULTIPLYADD) {
  58577. if (!this._getEffect(this.blendMode).isReady()) {
  58578. return false;
  58579. }
  58580. }
  58581. else {
  58582. if (!this._getEffect(ParticleSystem.BLENDMODE_MULTIPLY).isReady()) {
  58583. return false;
  58584. }
  58585. if (!this._getEffect(ParticleSystem.BLENDMODE_ADD).isReady()) {
  58586. return false;
  58587. }
  58588. }
  58589. return true;
  58590. };
  58591. ParticleSystem.prototype._render = function (blendMode) {
  58592. var effect = this._getEffect(blendMode);
  58593. var engine = this._scene.getEngine();
  58594. // Render
  58595. engine.enableEffect(effect);
  58596. var viewMatrix = this._scene.getViewMatrix();
  58597. effect.setTexture("diffuseSampler", this.particleTexture);
  58598. effect.setMatrix("view", viewMatrix);
  58599. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  58600. if (this._isAnimationSheetEnabled && this.particleTexture) {
  58601. var baseSize = this.particleTexture.getBaseSize();
  58602. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  58603. }
  58604. effect.setVector2("translationPivot", this.translationPivot);
  58605. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  58606. if (this._isBillboardBased) {
  58607. var camera = this._scene.activeCamera;
  58608. effect.setVector3("eyePosition", camera.globalPosition);
  58609. }
  58610. if (this._rampGradientsTexture) {
  58611. effect.setTexture("rampSampler", this._rampGradientsTexture);
  58612. }
  58613. if (this._scene.clipPlane || this._scene.clipPlane2 || this._scene.clipPlane3 || this._scene.clipPlane4) {
  58614. var invView = viewMatrix.clone();
  58615. invView.invert();
  58616. effect.setMatrix("invView", invView);
  58617. BABYLON.MaterialHelper.BindClipPlane(effect, this._scene);
  58618. }
  58619. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  58620. // image processing
  58621. if (this._imageProcessingConfiguration && !this._imageProcessingConfiguration.applyByPostProcess) {
  58622. this._imageProcessingConfiguration.bind(effect);
  58623. }
  58624. // Draw order
  58625. switch (blendMode) {
  58626. case ParticleSystem.BLENDMODE_ADD:
  58627. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  58628. break;
  58629. case ParticleSystem.BLENDMODE_ONEONE:
  58630. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  58631. break;
  58632. case ParticleSystem.BLENDMODE_STANDARD:
  58633. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  58634. break;
  58635. case ParticleSystem.BLENDMODE_MULTIPLY:
  58636. engine.setAlphaMode(BABYLON.Engine.ALPHA_MULTIPLY);
  58637. break;
  58638. }
  58639. if (this._useInstancing) {
  58640. engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._particles.length);
  58641. }
  58642. else {
  58643. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._particles.length * 6);
  58644. }
  58645. return this._particles.length;
  58646. };
  58647. /**
  58648. * Renders the particle system in its current state.
  58649. * @returns the current number of particles
  58650. */
  58651. ParticleSystem.prototype.render = function () {
  58652. // Check
  58653. if (!this.isReady() || !this._particles.length) {
  58654. return 0;
  58655. }
  58656. var engine = this._scene.getEngine();
  58657. engine.setState(false);
  58658. if (this.forceDepthWrite) {
  58659. engine.setDepthWrite(true);
  58660. }
  58661. var outparticles = 0;
  58662. if (this.blendMode === ParticleSystem.BLENDMODE_MULTIPLYADD) {
  58663. outparticles = this._render(ParticleSystem.BLENDMODE_MULTIPLY) + this._render(ParticleSystem.BLENDMODE_ADD);
  58664. }
  58665. outparticles = this._render(this.blendMode);
  58666. engine.unbindInstanceAttributes();
  58667. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  58668. return outparticles;
  58669. };
  58670. /**
  58671. * Disposes the particle system and free the associated resources
  58672. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  58673. */
  58674. ParticleSystem.prototype.dispose = function (disposeTexture) {
  58675. if (disposeTexture === void 0) { disposeTexture = true; }
  58676. if (this._vertexBuffer) {
  58677. this._vertexBuffer.dispose();
  58678. this._vertexBuffer = null;
  58679. }
  58680. if (this._spriteBuffer) {
  58681. this._spriteBuffer.dispose();
  58682. this._spriteBuffer = null;
  58683. }
  58684. if (this._indexBuffer) {
  58685. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  58686. this._indexBuffer = null;
  58687. }
  58688. if (disposeTexture && this.particleTexture) {
  58689. this.particleTexture.dispose();
  58690. this.particleTexture = null;
  58691. }
  58692. if (disposeTexture && this.noiseTexture) {
  58693. this.noiseTexture.dispose();
  58694. this.noiseTexture = null;
  58695. }
  58696. if (this._rampGradientsTexture) {
  58697. this._rampGradientsTexture.dispose();
  58698. this._rampGradientsTexture = null;
  58699. }
  58700. this._removeFromRoot();
  58701. if (this._subEmitters && this._subEmitters.length) {
  58702. for (var index = 0; index < this._subEmitters.length; index++) {
  58703. for (var _i = 0, _a = this._subEmitters[index]; _i < _a.length; _i++) {
  58704. var subEmitter = _a[_i];
  58705. subEmitter.dispose();
  58706. }
  58707. }
  58708. this._subEmitters = [];
  58709. this.subEmitters = [];
  58710. }
  58711. if (this._disposeEmitterOnDispose && this.emitter && this.emitter.dispose) {
  58712. this.emitter.dispose(true);
  58713. }
  58714. // Remove from scene
  58715. var index = this._scene.particleSystems.indexOf(this);
  58716. if (index > -1) {
  58717. this._scene.particleSystems.splice(index, 1);
  58718. }
  58719. this._scene._activeParticleSystems.dispose();
  58720. // Callback
  58721. this.onDisposeObservable.notifyObservers(this);
  58722. this.onDisposeObservable.clear();
  58723. this.reset();
  58724. };
  58725. // Clone
  58726. /**
  58727. * Clones the particle system.
  58728. * @param name The name of the cloned object
  58729. * @param newEmitter The new emitter to use
  58730. * @returns the cloned particle system
  58731. */
  58732. ParticleSystem.prototype.clone = function (name, newEmitter) {
  58733. var custom = null;
  58734. var program = null;
  58735. if (this.customShader != null) {
  58736. program = this.customShader;
  58737. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  58738. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  58739. }
  58740. else if (this._customEffect) {
  58741. custom = this._customEffect;
  58742. }
  58743. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  58744. result.customShader = program;
  58745. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader", "noiseTexture"]);
  58746. if (newEmitter === undefined) {
  58747. newEmitter = this.emitter;
  58748. }
  58749. result.noiseTexture = this.noiseTexture;
  58750. result.emitter = newEmitter;
  58751. if (this.particleTexture) {
  58752. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  58753. }
  58754. // Clone gradients
  58755. if (this._colorGradients) {
  58756. this._colorGradients.forEach(function (v) {
  58757. result.addColorGradient(v.gradient, v.color1, v.color2);
  58758. });
  58759. }
  58760. if (this._dragGradients) {
  58761. this._dragGradients.forEach(function (v) {
  58762. result.addDragGradient(v.gradient, v.factor1, v.factor2);
  58763. });
  58764. }
  58765. if (this._angularSpeedGradients) {
  58766. this._angularSpeedGradients.forEach(function (v) {
  58767. result.addAngularSpeedGradient(v.gradient, v.factor1, v.factor2);
  58768. });
  58769. }
  58770. if (this._emitRateGradients) {
  58771. this._emitRateGradients.forEach(function (v) {
  58772. result.addEmitRateGradient(v.gradient, v.factor1, v.factor2);
  58773. });
  58774. }
  58775. if (this._lifeTimeGradients) {
  58776. this._lifeTimeGradients.forEach(function (v) {
  58777. result.addLifeTimeGradient(v.gradient, v.factor1, v.factor2);
  58778. });
  58779. }
  58780. if (this._limitVelocityGradients) {
  58781. this._limitVelocityGradients.forEach(function (v) {
  58782. result.addLimitVelocityGradient(v.gradient, v.factor1, v.factor2);
  58783. });
  58784. }
  58785. if (this._sizeGradients) {
  58786. this._sizeGradients.forEach(function (v) {
  58787. result.addSizeGradient(v.gradient, v.factor1, v.factor2);
  58788. });
  58789. }
  58790. if (this._startSizeGradients) {
  58791. this._startSizeGradients.forEach(function (v) {
  58792. result.addStartSizeGradient(v.gradient, v.factor1, v.factor2);
  58793. });
  58794. }
  58795. if (this._velocityGradients) {
  58796. this._velocityGradients.forEach(function (v) {
  58797. result.addVelocityGradient(v.gradient, v.factor1, v.factor2);
  58798. });
  58799. }
  58800. if (this._rampGradients) {
  58801. this._rampGradients.forEach(function (v) {
  58802. result.addRampGradient(v.gradient, v.color);
  58803. });
  58804. }
  58805. if (this._colorRemapGradients) {
  58806. this._colorRemapGradients.forEach(function (v) {
  58807. result.addColorRemapGradient(v.gradient, v.factor1, v.factor2);
  58808. });
  58809. }
  58810. if (this._alphaRemapGradients) {
  58811. this._alphaRemapGradients.forEach(function (v) {
  58812. result.addAlphaRemapGradient(v.gradient, v.factor1, v.factor2);
  58813. });
  58814. }
  58815. if (!this.preventAutoStart) {
  58816. result.start();
  58817. }
  58818. return result;
  58819. };
  58820. /**
  58821. * Serializes the particle system to a JSON object.
  58822. * @returns the JSON object
  58823. */
  58824. ParticleSystem.prototype.serialize = function () {
  58825. var serializationObject = {};
  58826. ParticleSystem._Serialize(serializationObject, this);
  58827. serializationObject.textureMask = this.textureMask.asArray();
  58828. serializationObject.customShader = this.customShader;
  58829. serializationObject.preventAutoStart = this.preventAutoStart;
  58830. // SubEmitters
  58831. if (this.subEmitters) {
  58832. serializationObject.subEmitters = [];
  58833. if (!this._subEmitters) {
  58834. this._prepareSubEmitterInternalArray();
  58835. }
  58836. for (var _i = 0, _a = this._subEmitters; _i < _a.length; _i++) {
  58837. var subs = _a[_i];
  58838. var cell = [];
  58839. for (var _b = 0, subs_1 = subs; _b < subs_1.length; _b++) {
  58840. var sub = subs_1[_b];
  58841. cell.push(sub.serialize());
  58842. }
  58843. serializationObject.subEmitters.push(cell);
  58844. }
  58845. }
  58846. return serializationObject;
  58847. };
  58848. /** @hidden */
  58849. ParticleSystem._Serialize = function (serializationObject, particleSystem) {
  58850. serializationObject.name = particleSystem.name;
  58851. serializationObject.id = particleSystem.id;
  58852. serializationObject.capacity = particleSystem.getCapacity();
  58853. // Emitter
  58854. if (particleSystem.emitter.position) {
  58855. var emitterMesh = particleSystem.emitter;
  58856. serializationObject.emitterId = emitterMesh.id;
  58857. }
  58858. else {
  58859. var emitterPosition = particleSystem.emitter;
  58860. serializationObject.emitter = emitterPosition.asArray();
  58861. }
  58862. // Emitter
  58863. if (particleSystem.particleEmitterType) {
  58864. serializationObject.particleEmitterType = particleSystem.particleEmitterType.serialize();
  58865. }
  58866. if (particleSystem.particleTexture) {
  58867. serializationObject.textureName = particleSystem.particleTexture.name;
  58868. serializationObject.invertY = particleSystem.particleTexture._invertY;
  58869. }
  58870. // Animations
  58871. BABYLON.Animation.AppendSerializedAnimations(particleSystem, serializationObject);
  58872. // Particle system
  58873. serializationObject.startDelay = particleSystem.startDelay;
  58874. serializationObject.renderingGroupId = particleSystem.renderingGroupId;
  58875. serializationObject.isBillboardBased = particleSystem.isBillboardBased;
  58876. serializationObject.billboardMode = particleSystem.billboardMode;
  58877. serializationObject.minAngularSpeed = particleSystem.minAngularSpeed;
  58878. serializationObject.maxAngularSpeed = particleSystem.maxAngularSpeed;
  58879. serializationObject.minSize = particleSystem.minSize;
  58880. serializationObject.maxSize = particleSystem.maxSize;
  58881. serializationObject.minScaleX = particleSystem.minScaleX;
  58882. serializationObject.maxScaleX = particleSystem.maxScaleX;
  58883. serializationObject.minScaleY = particleSystem.minScaleY;
  58884. serializationObject.maxScaleY = particleSystem.maxScaleY;
  58885. serializationObject.minEmitPower = particleSystem.minEmitPower;
  58886. serializationObject.maxEmitPower = particleSystem.maxEmitPower;
  58887. serializationObject.minLifeTime = particleSystem.minLifeTime;
  58888. serializationObject.maxLifeTime = particleSystem.maxLifeTime;
  58889. serializationObject.emitRate = particleSystem.emitRate;
  58890. serializationObject.gravity = particleSystem.gravity.asArray();
  58891. serializationObject.noiseStrength = particleSystem.noiseStrength.asArray();
  58892. serializationObject.color1 = particleSystem.color1.asArray();
  58893. serializationObject.color2 = particleSystem.color2.asArray();
  58894. serializationObject.colorDead = particleSystem.colorDead.asArray();
  58895. serializationObject.updateSpeed = particleSystem.updateSpeed;
  58896. serializationObject.targetStopDuration = particleSystem.targetStopDuration;
  58897. serializationObject.blendMode = particleSystem.blendMode;
  58898. serializationObject.preWarmCycles = particleSystem.preWarmCycles;
  58899. serializationObject.preWarmStepOffset = particleSystem.preWarmStepOffset;
  58900. serializationObject.minInitialRotation = particleSystem.minInitialRotation;
  58901. serializationObject.maxInitialRotation = particleSystem.maxInitialRotation;
  58902. serializationObject.startSpriteCellID = particleSystem.startSpriteCellID;
  58903. serializationObject.endSpriteCellID = particleSystem.endSpriteCellID;
  58904. serializationObject.spriteCellChangeSpeed = particleSystem.spriteCellChangeSpeed;
  58905. serializationObject.spriteCellWidth = particleSystem.spriteCellWidth;
  58906. serializationObject.spriteCellHeight = particleSystem.spriteCellHeight;
  58907. serializationObject.spriteRandomStartCell = particleSystem.spriteRandomStartCell;
  58908. serializationObject.isAnimationSheetEnabled = particleSystem.isAnimationSheetEnabled;
  58909. var colorGradients = particleSystem.getColorGradients();
  58910. if (colorGradients) {
  58911. serializationObject.colorGradients = [];
  58912. for (var _i = 0, colorGradients_1 = colorGradients; _i < colorGradients_1.length; _i++) {
  58913. var colorGradient = colorGradients_1[_i];
  58914. var serializedGradient = {
  58915. gradient: colorGradient.gradient,
  58916. color1: colorGradient.color1.asArray()
  58917. };
  58918. if (colorGradient.color2) {
  58919. serializedGradient.color2 = colorGradient.color2.asArray();
  58920. }
  58921. serializationObject.colorGradients.push(serializedGradient);
  58922. }
  58923. }
  58924. var rampGradients = particleSystem.getRampGradients();
  58925. if (rampGradients) {
  58926. serializationObject.rampGradients = [];
  58927. for (var _a = 0, rampGradients_1 = rampGradients; _a < rampGradients_1.length; _a++) {
  58928. var rampGradient = rampGradients_1[_a];
  58929. var serializedGradient = {
  58930. gradient: rampGradient.gradient,
  58931. color: rampGradient.color.asArray()
  58932. };
  58933. serializationObject.rampGradients.push(serializedGradient);
  58934. }
  58935. serializationObject.useRampGradients = particleSystem.useRampGradients;
  58936. }
  58937. var colorRemapGradients = particleSystem.getColorRemapGradients();
  58938. if (colorRemapGradients) {
  58939. serializationObject.colorRemapGradients = [];
  58940. for (var _b = 0, colorRemapGradients_1 = colorRemapGradients; _b < colorRemapGradients_1.length; _b++) {
  58941. var colorRemapGradient = colorRemapGradients_1[_b];
  58942. var serializedGradient = {
  58943. gradient: colorRemapGradient.gradient,
  58944. factor1: colorRemapGradient.factor1
  58945. };
  58946. if (colorRemapGradient.factor2 !== undefined) {
  58947. serializedGradient.factor2 = colorRemapGradient.factor2;
  58948. }
  58949. serializationObject.colorRemapGradients.push(serializedGradient);
  58950. }
  58951. }
  58952. var alphaRemapGradients = particleSystem.getAlphaRemapGradients();
  58953. if (alphaRemapGradients) {
  58954. serializationObject.alphaRemapGradients = [];
  58955. for (var _c = 0, alphaRemapGradients_1 = alphaRemapGradients; _c < alphaRemapGradients_1.length; _c++) {
  58956. var alphaRemapGradient = alphaRemapGradients_1[_c];
  58957. var serializedGradient = {
  58958. gradient: alphaRemapGradient.gradient,
  58959. factor1: alphaRemapGradient.factor1
  58960. };
  58961. if (alphaRemapGradient.factor2 !== undefined) {
  58962. serializedGradient.factor2 = alphaRemapGradient.factor2;
  58963. }
  58964. serializationObject.alphaRemapGradients.push(serializedGradient);
  58965. }
  58966. }
  58967. var sizeGradients = particleSystem.getSizeGradients();
  58968. if (sizeGradients) {
  58969. serializationObject.sizeGradients = [];
  58970. for (var _d = 0, sizeGradients_1 = sizeGradients; _d < sizeGradients_1.length; _d++) {
  58971. var sizeGradient = sizeGradients_1[_d];
  58972. var serializedGradient = {
  58973. gradient: sizeGradient.gradient,
  58974. factor1: sizeGradient.factor1
  58975. };
  58976. if (sizeGradient.factor2 !== undefined) {
  58977. serializedGradient.factor2 = sizeGradient.factor2;
  58978. }
  58979. serializationObject.sizeGradients.push(serializedGradient);
  58980. }
  58981. }
  58982. var angularSpeedGradients = particleSystem.getAngularSpeedGradients();
  58983. if (angularSpeedGradients) {
  58984. serializationObject.angularSpeedGradients = [];
  58985. for (var _e = 0, angularSpeedGradients_1 = angularSpeedGradients; _e < angularSpeedGradients_1.length; _e++) {
  58986. var angularSpeedGradient = angularSpeedGradients_1[_e];
  58987. var serializedGradient = {
  58988. gradient: angularSpeedGradient.gradient,
  58989. factor1: angularSpeedGradient.factor1
  58990. };
  58991. if (angularSpeedGradient.factor2 !== undefined) {
  58992. serializedGradient.factor2 = angularSpeedGradient.factor2;
  58993. }
  58994. serializationObject.angularSpeedGradients.push(serializedGradient);
  58995. }
  58996. }
  58997. var velocityGradients = particleSystem.getVelocityGradients();
  58998. if (velocityGradients) {
  58999. serializationObject.velocityGradients = [];
  59000. for (var _f = 0, velocityGradients_1 = velocityGradients; _f < velocityGradients_1.length; _f++) {
  59001. var velocityGradient = velocityGradients_1[_f];
  59002. var serializedGradient = {
  59003. gradient: velocityGradient.gradient,
  59004. factor1: velocityGradient.factor1
  59005. };
  59006. if (velocityGradient.factor2 !== undefined) {
  59007. serializedGradient.factor2 = velocityGradient.factor2;
  59008. }
  59009. serializationObject.velocityGradients.push(serializedGradient);
  59010. }
  59011. }
  59012. var dragGradients = particleSystem.getDragGradients();
  59013. if (dragGradients) {
  59014. serializationObject.dragyGradients = [];
  59015. for (var _g = 0, dragGradients_1 = dragGradients; _g < dragGradients_1.length; _g++) {
  59016. var dragGradient = dragGradients_1[_g];
  59017. var serializedGradient = {
  59018. gradient: dragGradient.gradient,
  59019. factor1: dragGradient.factor1
  59020. };
  59021. if (dragGradient.factor2 !== undefined) {
  59022. serializedGradient.factor2 = dragGradient.factor2;
  59023. }
  59024. serializationObject.dragGradients.push(serializedGradient);
  59025. }
  59026. }
  59027. var emitRateGradients = particleSystem.getEmitRateGradients();
  59028. if (emitRateGradients) {
  59029. serializationObject.emitRateGradients = [];
  59030. for (var _h = 0, emitRateGradients_1 = emitRateGradients; _h < emitRateGradients_1.length; _h++) {
  59031. var emitRateGradient = emitRateGradients_1[_h];
  59032. var serializedGradient = {
  59033. gradient: emitRateGradient.gradient,
  59034. factor1: emitRateGradient.factor1
  59035. };
  59036. if (emitRateGradient.factor2 !== undefined) {
  59037. serializedGradient.factor2 = emitRateGradient.factor2;
  59038. }
  59039. serializationObject.emitRateGradients.push(serializedGradient);
  59040. }
  59041. }
  59042. var startSizeGradients = particleSystem.getStartSizeGradients();
  59043. if (startSizeGradients) {
  59044. serializationObject.startSizeGradients = [];
  59045. for (var _j = 0, startSizeGradients_1 = startSizeGradients; _j < startSizeGradients_1.length; _j++) {
  59046. var startSizeGradient = startSizeGradients_1[_j];
  59047. var serializedGradient = {
  59048. gradient: startSizeGradient.gradient,
  59049. factor1: startSizeGradient.factor1
  59050. };
  59051. if (startSizeGradient.factor2 !== undefined) {
  59052. serializedGradient.factor2 = startSizeGradient.factor2;
  59053. }
  59054. serializationObject.startSizeGradients.push(serializedGradient);
  59055. }
  59056. }
  59057. var limitVelocityGradients = particleSystem.getLimitVelocityGradients();
  59058. if (limitVelocityGradients) {
  59059. serializationObject.limitVelocityGradients = [];
  59060. for (var _k = 0, limitVelocityGradients_1 = limitVelocityGradients; _k < limitVelocityGradients_1.length; _k++) {
  59061. var limitVelocityGradient = limitVelocityGradients_1[_k];
  59062. var serializedGradient = {
  59063. gradient: limitVelocityGradient.gradient,
  59064. factor1: limitVelocityGradient.factor1
  59065. };
  59066. if (limitVelocityGradient.factor2 !== undefined) {
  59067. serializedGradient.factor2 = limitVelocityGradient.factor2;
  59068. }
  59069. serializationObject.limitVelocityGradients.push(serializedGradient);
  59070. }
  59071. serializationObject.limitVelocityDamping = particleSystem.limitVelocityDamping;
  59072. }
  59073. if (particleSystem.noiseTexture) {
  59074. serializationObject.noiseTexture = particleSystem.noiseTexture.serialize();
  59075. }
  59076. };
  59077. /** @hidden */
  59078. ParticleSystem._Parse = function (parsedParticleSystem, particleSystem, scene, rootUrl) {
  59079. // Texture
  59080. if (parsedParticleSystem.textureName) {
  59081. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene, false, parsedParticleSystem.invertY !== undefined ? parsedParticleSystem.invertY : true);
  59082. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  59083. }
  59084. // Emitter
  59085. if (!parsedParticleSystem.emitterId && parsedParticleSystem.emitterId !== 0 && parsedParticleSystem.emitter === undefined) {
  59086. particleSystem.emitter = BABYLON.Vector3.Zero();
  59087. }
  59088. else if (parsedParticleSystem.emitterId) {
  59089. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  59090. }
  59091. else {
  59092. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  59093. }
  59094. // Misc.
  59095. if (parsedParticleSystem.renderingGroupId !== undefined) {
  59096. particleSystem.renderingGroupId = parsedParticleSystem.renderingGroupId;
  59097. }
  59098. if (parsedParticleSystem.isBillboardBased !== undefined) {
  59099. particleSystem.isBillboardBased = parsedParticleSystem.isBillboardBased;
  59100. }
  59101. if (parsedParticleSystem.billboardMode !== undefined) {
  59102. particleSystem.billboardMode = parsedParticleSystem.billboardMode;
  59103. }
  59104. // Animations
  59105. if (parsedParticleSystem.animations) {
  59106. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  59107. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  59108. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  59109. }
  59110. }
  59111. if (parsedParticleSystem.autoAnimate) {
  59112. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  59113. }
  59114. // Particle system
  59115. particleSystem.startDelay = parsedParticleSystem.startDelay | 0;
  59116. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  59117. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  59118. particleSystem.minSize = parsedParticleSystem.minSize;
  59119. particleSystem.maxSize = parsedParticleSystem.maxSize;
  59120. if (parsedParticleSystem.minScaleX) {
  59121. particleSystem.minScaleX = parsedParticleSystem.minScaleX;
  59122. particleSystem.maxScaleX = parsedParticleSystem.maxScaleX;
  59123. particleSystem.minScaleY = parsedParticleSystem.minScaleY;
  59124. particleSystem.maxScaleY = parsedParticleSystem.maxScaleY;
  59125. }
  59126. if (parsedParticleSystem.preWarmCycles !== undefined) {
  59127. particleSystem.preWarmCycles = parsedParticleSystem.preWarmCycles;
  59128. particleSystem.preWarmStepOffset = parsedParticleSystem.preWarmStepOffset;
  59129. }
  59130. if (parsedParticleSystem.minInitialRotation !== undefined) {
  59131. particleSystem.minInitialRotation = parsedParticleSystem.minInitialRotation;
  59132. particleSystem.maxInitialRotation = parsedParticleSystem.maxInitialRotation;
  59133. }
  59134. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  59135. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  59136. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  59137. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  59138. particleSystem.emitRate = parsedParticleSystem.emitRate;
  59139. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  59140. if (parsedParticleSystem.noiseStrength) {
  59141. particleSystem.noiseStrength = BABYLON.Vector3.FromArray(parsedParticleSystem.noiseStrength);
  59142. }
  59143. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  59144. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  59145. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  59146. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  59147. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  59148. particleSystem.blendMode = parsedParticleSystem.blendMode;
  59149. if (parsedParticleSystem.colorGradients) {
  59150. for (var _i = 0, _a = parsedParticleSystem.colorGradients; _i < _a.length; _i++) {
  59151. var colorGradient = _a[_i];
  59152. particleSystem.addColorGradient(colorGradient.gradient, BABYLON.Color4.FromArray(colorGradient.color1), colorGradient.color2 ? BABYLON.Color4.FromArray(colorGradient.color2) : undefined);
  59153. }
  59154. }
  59155. if (parsedParticleSystem.rampGradients) {
  59156. for (var _b = 0, _c = parsedParticleSystem.rampGradients; _b < _c.length; _b++) {
  59157. var rampGradient = _c[_b];
  59158. particleSystem.addRampGradient(rampGradient.gradient, BABYLON.Color3.FromArray(rampGradient.color));
  59159. }
  59160. particleSystem.useRampGradients = parsedParticleSystem.useRampGradients;
  59161. }
  59162. if (parsedParticleSystem.colorRemapGradients) {
  59163. for (var _d = 0, _e = parsedParticleSystem.colorRemapGradients; _d < _e.length; _d++) {
  59164. var colorRemapGradient = _e[_d];
  59165. particleSystem.addColorRemapGradient(colorRemapGradient.gradient, colorRemapGradient.factor1 !== undefined ? colorRemapGradient.factor1 : colorRemapGradient.factor, colorRemapGradient.factor2);
  59166. }
  59167. }
  59168. if (parsedParticleSystem.alphaRemapGradients) {
  59169. for (var _f = 0, _g = parsedParticleSystem.alphaRemapGradients; _f < _g.length; _f++) {
  59170. var alphaRemapGradient = _g[_f];
  59171. particleSystem.addAlphaRemapGradient(alphaRemapGradient.gradient, alphaRemapGradient.factor1 !== undefined ? alphaRemapGradient.factor1 : alphaRemapGradient.factor, alphaRemapGradient.factor2);
  59172. }
  59173. }
  59174. if (parsedParticleSystem.sizeGradients) {
  59175. for (var _h = 0, _j = parsedParticleSystem.sizeGradients; _h < _j.length; _h++) {
  59176. var sizeGradient = _j[_h];
  59177. particleSystem.addSizeGradient(sizeGradient.gradient, sizeGradient.factor1 !== undefined ? sizeGradient.factor1 : sizeGradient.factor, sizeGradient.factor2);
  59178. }
  59179. }
  59180. if (parsedParticleSystem.sizeGradients) {
  59181. for (var _k = 0, _l = parsedParticleSystem.sizeGradients; _k < _l.length; _k++) {
  59182. var sizeGradient = _l[_k];
  59183. particleSystem.addSizeGradient(sizeGradient.gradient, sizeGradient.factor1 !== undefined ? sizeGradient.factor1 : sizeGradient.factor, sizeGradient.factor2);
  59184. }
  59185. }
  59186. if (parsedParticleSystem.angularSpeedGradients) {
  59187. for (var _m = 0, _o = parsedParticleSystem.angularSpeedGradients; _m < _o.length; _m++) {
  59188. var angularSpeedGradient = _o[_m];
  59189. particleSystem.addAngularSpeedGradient(angularSpeedGradient.gradient, angularSpeedGradient.factor1 !== undefined ? angularSpeedGradient.factor1 : angularSpeedGradient.factor, angularSpeedGradient.factor2);
  59190. }
  59191. }
  59192. if (parsedParticleSystem.velocityGradients) {
  59193. for (var _p = 0, _q = parsedParticleSystem.velocityGradients; _p < _q.length; _p++) {
  59194. var velocityGradient = _q[_p];
  59195. particleSystem.addVelocityGradient(velocityGradient.gradient, velocityGradient.factor1 !== undefined ? velocityGradient.factor1 : velocityGradient.factor, velocityGradient.factor2);
  59196. }
  59197. }
  59198. if (parsedParticleSystem.dragGradients) {
  59199. for (var _r = 0, _s = parsedParticleSystem.dragGradients; _r < _s.length; _r++) {
  59200. var dragGradient = _s[_r];
  59201. particleSystem.addDragGradient(dragGradient.gradient, dragGradient.factor1 !== undefined ? dragGradient.factor1 : dragGradient.factor, dragGradient.factor2);
  59202. }
  59203. }
  59204. if (parsedParticleSystem.emitRateGradients) {
  59205. for (var _t = 0, _u = parsedParticleSystem.emitRateGradients; _t < _u.length; _t++) {
  59206. var emitRateGradient = _u[_t];
  59207. particleSystem.addEmitRateGradient(emitRateGradient.gradient, emitRateGradient.factor1 !== undefined ? emitRateGradient.factor1 : emitRateGradient.factor, emitRateGradient.factor2);
  59208. }
  59209. }
  59210. if (parsedParticleSystem.startSizeGradients) {
  59211. for (var _v = 0, _w = parsedParticleSystem.startSizeGradients; _v < _w.length; _v++) {
  59212. var startSizeGradient = _w[_v];
  59213. particleSystem.addStartSizeGradient(startSizeGradient.gradient, startSizeGradient.factor1 !== undefined ? startSizeGradient.factor1 : startSizeGradient.factor, startSizeGradient.factor2);
  59214. }
  59215. }
  59216. if (parsedParticleSystem.limitVelocityGradients) {
  59217. for (var _x = 0, _y = parsedParticleSystem.limitVelocityGradients; _x < _y.length; _x++) {
  59218. var limitVelocityGradient = _y[_x];
  59219. particleSystem.addLimitVelocityGradient(limitVelocityGradient.gradient, limitVelocityGradient.factor1 !== undefined ? limitVelocityGradient.factor1 : limitVelocityGradient.factor, limitVelocityGradient.factor2);
  59220. }
  59221. particleSystem.limitVelocityDamping = parsedParticleSystem.limitVelocityDamping;
  59222. }
  59223. if (parsedParticleSystem.noiseTexture) {
  59224. particleSystem.noiseTexture = BABYLON.ProceduralTexture.Parse(parsedParticleSystem.noiseTexture, scene, rootUrl);
  59225. }
  59226. // Emitter
  59227. var emitterType;
  59228. if (parsedParticleSystem.particleEmitterType) {
  59229. switch (parsedParticleSystem.particleEmitterType.type) {
  59230. case "SphereParticleEmitter":
  59231. emitterType = new BABYLON.SphereParticleEmitter();
  59232. break;
  59233. case "SphereDirectedParticleEmitter":
  59234. emitterType = new BABYLON.SphereDirectedParticleEmitter();
  59235. break;
  59236. case "ConeEmitter":
  59237. case "ConeParticleEmitter":
  59238. emitterType = new BABYLON.ConeParticleEmitter();
  59239. break;
  59240. case "BoxEmitter":
  59241. case "BoxParticleEmitter":
  59242. default:
  59243. emitterType = new BABYLON.BoxParticleEmitter();
  59244. break;
  59245. }
  59246. emitterType.parse(parsedParticleSystem.particleEmitterType);
  59247. }
  59248. else {
  59249. emitterType = new BABYLON.BoxParticleEmitter();
  59250. emitterType.parse(parsedParticleSystem);
  59251. }
  59252. particleSystem.particleEmitterType = emitterType;
  59253. // Animation sheet
  59254. particleSystem.startSpriteCellID = parsedParticleSystem.startSpriteCellID;
  59255. particleSystem.endSpriteCellID = parsedParticleSystem.endSpriteCellID;
  59256. particleSystem.spriteCellWidth = parsedParticleSystem.spriteCellWidth;
  59257. particleSystem.spriteCellHeight = parsedParticleSystem.spriteCellHeight;
  59258. particleSystem.spriteCellChangeSpeed = parsedParticleSystem.spriteCellChangeSpeed;
  59259. particleSystem.spriteRandomStartCell = parsedParticleSystem.spriteRandomStartCell;
  59260. };
  59261. /**
  59262. * Parses a JSON object to create a particle system.
  59263. * @param parsedParticleSystem The JSON object to parse
  59264. * @param scene The scene to create the particle system in
  59265. * @param rootUrl The root url to use to load external dependencies like texture
  59266. * @returns the Parsed particle system
  59267. */
  59268. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  59269. var name = parsedParticleSystem.name;
  59270. var custom = null;
  59271. var program = null;
  59272. if (parsedParticleSystem.customShader) {
  59273. program = parsedParticleSystem.customShader;
  59274. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  59275. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  59276. }
  59277. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom, parsedParticleSystem.isAnimationSheetEnabled);
  59278. particleSystem.customShader = program;
  59279. if (parsedParticleSystem.id) {
  59280. particleSystem.id = parsedParticleSystem.id;
  59281. }
  59282. // SubEmitters
  59283. if (parsedParticleSystem.subEmitters) {
  59284. particleSystem.subEmitters = [];
  59285. for (var _i = 0, _a = parsedParticleSystem.subEmitters; _i < _a.length; _i++) {
  59286. var cell = _a[_i];
  59287. var cellArray = [];
  59288. for (var _b = 0, cell_1 = cell; _b < cell_1.length; _b++) {
  59289. var sub = cell_1[_b];
  59290. cellArray.push(BABYLON.SubEmitter.Parse(sub, scene, rootUrl));
  59291. }
  59292. particleSystem.subEmitters.push(cellArray);
  59293. }
  59294. }
  59295. // Auto start
  59296. if (parsedParticleSystem.preventAutoStart) {
  59297. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  59298. }
  59299. ParticleSystem._Parse(parsedParticleSystem, particleSystem, scene, rootUrl);
  59300. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  59301. if (!particleSystem.preventAutoStart) {
  59302. particleSystem.start();
  59303. }
  59304. return particleSystem;
  59305. };
  59306. /**
  59307. * Billboard mode will only apply to Y axis
  59308. */
  59309. ParticleSystem.BILLBOARDMODE_Y = 2;
  59310. /**
  59311. * Billboard mode will apply to all axes
  59312. */
  59313. ParticleSystem.BILLBOARDMODE_ALL = 7;
  59314. /**
  59315. * Special billboard mode where the particle will be biilboard to the camera but rotated to align with direction
  59316. */
  59317. ParticleSystem.BILLBOARDMODE_STRETCHED = 8;
  59318. return ParticleSystem;
  59319. }(BABYLON.BaseParticleSystem));
  59320. BABYLON.ParticleSystem = ParticleSystem;
  59321. })(BABYLON || (BABYLON = {}));
  59322. //# sourceMappingURL=babylon.particleSystem.js.map
  59323. var BABYLON;
  59324. (function (BABYLON) {
  59325. /**
  59326. * Particle emitter emitting particles from the inside of a box.
  59327. * It emits the particles randomly between 2 given directions.
  59328. */
  59329. var BoxParticleEmitter = /** @class */ (function () {
  59330. /**
  59331. * Creates a new instance BoxParticleEmitter
  59332. */
  59333. function BoxParticleEmitter() {
  59334. /**
  59335. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  59336. */
  59337. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  59338. /**
  59339. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  59340. */
  59341. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  59342. /**
  59343. * 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.
  59344. */
  59345. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  59346. /**
  59347. * 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.
  59348. */
  59349. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  59350. }
  59351. /**
  59352. * Called by the particle System when the direction is computed for the created particle.
  59353. * @param worldMatrix is the world matrix of the particle system
  59354. * @param directionToUpdate is the direction vector to update with the result
  59355. * @param particle is the particle we are computed the direction for
  59356. */
  59357. BoxParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  59358. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  59359. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  59360. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  59361. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  59362. };
  59363. /**
  59364. * Called by the particle System when the position is computed for the created particle.
  59365. * @param worldMatrix is the world matrix of the particle system
  59366. * @param positionToUpdate is the position vector to update with the result
  59367. * @param particle is the particle we are computed the position for
  59368. */
  59369. BoxParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  59370. var randX = BABYLON.Scalar.RandomRange(this.minEmitBox.x, this.maxEmitBox.x);
  59371. var randY = BABYLON.Scalar.RandomRange(this.minEmitBox.y, this.maxEmitBox.y);
  59372. var randZ = BABYLON.Scalar.RandomRange(this.minEmitBox.z, this.maxEmitBox.z);
  59373. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  59374. };
  59375. /**
  59376. * Clones the current emitter and returns a copy of it
  59377. * @returns the new emitter
  59378. */
  59379. BoxParticleEmitter.prototype.clone = function () {
  59380. var newOne = new BoxParticleEmitter();
  59381. BABYLON.Tools.DeepCopy(this, newOne);
  59382. return newOne;
  59383. };
  59384. /**
  59385. * Called by the GPUParticleSystem to setup the update shader
  59386. * @param effect defines the update shader
  59387. */
  59388. BoxParticleEmitter.prototype.applyToShader = function (effect) {
  59389. effect.setVector3("direction1", this.direction1);
  59390. effect.setVector3("direction2", this.direction2);
  59391. effect.setVector3("minEmitBox", this.minEmitBox);
  59392. effect.setVector3("maxEmitBox", this.maxEmitBox);
  59393. };
  59394. /**
  59395. * Returns a string to use to update the GPU particles update shader
  59396. * @returns a string containng the defines string
  59397. */
  59398. BoxParticleEmitter.prototype.getEffectDefines = function () {
  59399. return "#define BOXEMITTER";
  59400. };
  59401. /**
  59402. * Returns the string "BoxParticleEmitter"
  59403. * @returns a string containing the class name
  59404. */
  59405. BoxParticleEmitter.prototype.getClassName = function () {
  59406. return "BoxParticleEmitter";
  59407. };
  59408. /**
  59409. * Serializes the particle system to a JSON object.
  59410. * @returns the JSON object
  59411. */
  59412. BoxParticleEmitter.prototype.serialize = function () {
  59413. var serializationObject = {};
  59414. serializationObject.type = this.getClassName();
  59415. serializationObject.direction1 = this.direction1.asArray();
  59416. serializationObject.direction2 = this.direction2.asArray();
  59417. serializationObject.minEmitBox = this.minEmitBox.asArray();
  59418. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  59419. return serializationObject;
  59420. };
  59421. /**
  59422. * Parse properties from a JSON object
  59423. * @param serializationObject defines the JSON object
  59424. */
  59425. BoxParticleEmitter.prototype.parse = function (serializationObject) {
  59426. BABYLON.Vector3.FromArrayToRef(serializationObject.direction1, 0, this.direction1);
  59427. BABYLON.Vector3.FromArrayToRef(serializationObject.direction2, 0, this.direction2);
  59428. BABYLON.Vector3.FromArrayToRef(serializationObject.minEmitBox, 0, this.minEmitBox);
  59429. BABYLON.Vector3.FromArrayToRef(serializationObject.maxEmitBox, 0, this.maxEmitBox);
  59430. };
  59431. return BoxParticleEmitter;
  59432. }());
  59433. BABYLON.BoxParticleEmitter = BoxParticleEmitter;
  59434. })(BABYLON || (BABYLON = {}));
  59435. //# sourceMappingURL=babylon.boxParticleEmitter.js.map
  59436. var BABYLON;
  59437. (function (BABYLON) {
  59438. /**
  59439. * Particle emitter emitting particles from the inside of a cylinder.
  59440. * It emits the particles alongside the cylinder radius. The emission direction might be randomized.
  59441. */
  59442. var CylinderParticleEmitter = /** @class */ (function () {
  59443. /**
  59444. * Creates a new instance CylinderParticleEmitter
  59445. * @param radius the radius of the emission cylinder (1 by default)
  59446. * @param height the height of the emission cylinder (1 by default)
  59447. * @param radiusRange the range of the emission cylinder [0-1] 0 Surface only, 1 Entire Radius (1 by default)
  59448. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  59449. */
  59450. function CylinderParticleEmitter(
  59451. /**
  59452. * The radius of the emission cylinder.
  59453. */
  59454. radius,
  59455. /**
  59456. * The height of the emission cylinder.
  59457. */
  59458. height,
  59459. /**
  59460. * The range of emission [0-1] 0 Surface only, 1 Entire Radius.
  59461. */
  59462. radiusRange,
  59463. /**
  59464. * How much to randomize the particle direction [0-1].
  59465. */
  59466. directionRandomizer) {
  59467. if (radius === void 0) { radius = 1; }
  59468. if (height === void 0) { height = 1; }
  59469. if (radiusRange === void 0) { radiusRange = 1; }
  59470. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  59471. this.radius = radius;
  59472. this.height = height;
  59473. this.radiusRange = radiusRange;
  59474. this.directionRandomizer = directionRandomizer;
  59475. }
  59476. /**
  59477. * Called by the particle System when the direction is computed for the created particle.
  59478. * @param worldMatrix is the world matrix of the particle system
  59479. * @param directionToUpdate is the direction vector to update with the result
  59480. * @param particle is the particle we are computed the direction for
  59481. */
  59482. CylinderParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  59483. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  59484. var randY = BABYLON.Scalar.RandomRange(-this.directionRandomizer / 2, this.directionRandomizer / 2);
  59485. var angle = Math.atan2(direction.x, direction.z);
  59486. angle += BABYLON.Scalar.RandomRange(-Math.PI / 2, Math.PI / 2) * this.directionRandomizer;
  59487. direction.y = randY; // set direction y to rand y to mirror normal of cylinder surface
  59488. direction.x = Math.sin(angle);
  59489. direction.z = Math.cos(angle);
  59490. direction.normalize();
  59491. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  59492. };
  59493. /**
  59494. * Called by the particle System when the position is computed for the created particle.
  59495. * @param worldMatrix is the world matrix of the particle system
  59496. * @param positionToUpdate is the position vector to update with the result
  59497. * @param particle is the particle we are computed the position for
  59498. */
  59499. CylinderParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  59500. var yPos = BABYLON.Scalar.RandomRange(-this.height / 2, this.height / 2);
  59501. var angle = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  59502. // Pick a properly distributed point within the circle https://programming.guide/random-point-within-circle.html
  59503. var radiusDistribution = BABYLON.Scalar.RandomRange((1 - this.radiusRange) * (1 - this.radiusRange), 1);
  59504. var positionRadius = Math.sqrt(radiusDistribution) * this.radius;
  59505. var xPos = positionRadius * Math.cos(angle);
  59506. var zPos = positionRadius * Math.sin(angle);
  59507. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(xPos, yPos, zPos, worldMatrix, positionToUpdate);
  59508. };
  59509. /**
  59510. * Clones the current emitter and returns a copy of it
  59511. * @returns the new emitter
  59512. */
  59513. CylinderParticleEmitter.prototype.clone = function () {
  59514. var newOne = new CylinderParticleEmitter(this.radius, this.directionRandomizer);
  59515. BABYLON.Tools.DeepCopy(this, newOne);
  59516. return newOne;
  59517. };
  59518. /**
  59519. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  59520. * @param effect defines the update shader
  59521. */
  59522. CylinderParticleEmitter.prototype.applyToShader = function (effect) {
  59523. effect.setFloat("radius", this.radius);
  59524. effect.setFloat("height", this.height);
  59525. effect.setFloat("radiusRange", this.radiusRange);
  59526. effect.setFloat("directionRandomizer", this.directionRandomizer);
  59527. };
  59528. /**
  59529. * Returns a string to use to update the GPU particles update shader
  59530. * @returns a string containng the defines string
  59531. */
  59532. CylinderParticleEmitter.prototype.getEffectDefines = function () {
  59533. return "#define CYLINDEREMITTER";
  59534. };
  59535. /**
  59536. * Returns the string "CylinderParticleEmitter"
  59537. * @returns a string containing the class name
  59538. */
  59539. CylinderParticleEmitter.prototype.getClassName = function () {
  59540. return "CylinderParticleEmitter";
  59541. };
  59542. /**
  59543. * Serializes the particle system to a JSON object.
  59544. * @returns the JSON object
  59545. */
  59546. CylinderParticleEmitter.prototype.serialize = function () {
  59547. var serializationObject = {};
  59548. serializationObject.type = this.getClassName();
  59549. serializationObject.radius = this.radius;
  59550. serializationObject.height = this.height;
  59551. serializationObject.radiusRange = this.radiusRange;
  59552. serializationObject.directionRandomizer = this.directionRandomizer;
  59553. return serializationObject;
  59554. };
  59555. /**
  59556. * Parse properties from a JSON object
  59557. * @param serializationObject defines the JSON object
  59558. */
  59559. CylinderParticleEmitter.prototype.parse = function (serializationObject) {
  59560. this.radius = serializationObject.radius;
  59561. this.height = serializationObject.height;
  59562. this.radiusRange = serializationObject.radiusRange;
  59563. this.directionRandomizer = serializationObject.directionRandomizer;
  59564. };
  59565. return CylinderParticleEmitter;
  59566. }());
  59567. BABYLON.CylinderParticleEmitter = CylinderParticleEmitter;
  59568. /**
  59569. * Particle emitter emitting particles from the inside of a cylinder.
  59570. * It emits the particles randomly between two vectors.
  59571. */
  59572. var CylinderDirectedParticleEmitter = /** @class */ (function (_super) {
  59573. __extends(CylinderDirectedParticleEmitter, _super);
  59574. /**
  59575. * Creates a new instance CylinderDirectedParticleEmitter
  59576. * @param radius the radius of the emission cylinder (1 by default)
  59577. * @param height the height of the emission cylinder (1 by default)
  59578. * @param radiusRange the range of the emission cylinder [0-1] 0 Surface only, 1 Entire Radius (1 by default)
  59579. * @param direction1 the min limit of the emission direction (up vector by default)
  59580. * @param direction2 the max limit of the emission direction (up vector by default)
  59581. */
  59582. function CylinderDirectedParticleEmitter(radius, height, radiusRange,
  59583. /**
  59584. * The min limit of the emission direction.
  59585. */
  59586. direction1,
  59587. /**
  59588. * The max limit of the emission direction.
  59589. */
  59590. direction2) {
  59591. if (radius === void 0) { radius = 1; }
  59592. if (height === void 0) { height = 1; }
  59593. if (radiusRange === void 0) { radiusRange = 1; }
  59594. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1, 0); }
  59595. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1, 0); }
  59596. var _this = _super.call(this, radius, height, radiusRange) || this;
  59597. _this.direction1 = direction1;
  59598. _this.direction2 = direction2;
  59599. return _this;
  59600. }
  59601. /**
  59602. * Called by the particle System when the direction is computed for the created particle.
  59603. * @param worldMatrix is the world matrix of the particle system
  59604. * @param directionToUpdate is the direction vector to update with the result
  59605. * @param particle is the particle we are computed the direction for
  59606. */
  59607. CylinderDirectedParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  59608. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  59609. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  59610. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  59611. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  59612. };
  59613. /**
  59614. * Clones the current emitter and returns a copy of it
  59615. * @returns the new emitter
  59616. */
  59617. CylinderDirectedParticleEmitter.prototype.clone = function () {
  59618. var newOne = new CylinderDirectedParticleEmitter(this.radius, this.height, this.radiusRange, this.direction1, this.direction2);
  59619. BABYLON.Tools.DeepCopy(this, newOne);
  59620. return newOne;
  59621. };
  59622. /**
  59623. * Called by the GPUParticleSystem to setup the update shader
  59624. * @param effect defines the update shader
  59625. */
  59626. CylinderDirectedParticleEmitter.prototype.applyToShader = function (effect) {
  59627. effect.setFloat("radius", this.radius);
  59628. effect.setFloat("height", this.height);
  59629. effect.setFloat("radiusRange", this.radiusRange);
  59630. effect.setVector3("direction1", this.direction1);
  59631. effect.setVector3("direction2", this.direction2);
  59632. };
  59633. /**
  59634. * Returns a string to use to update the GPU particles update shader
  59635. * @returns a string containng the defines string
  59636. */
  59637. CylinderDirectedParticleEmitter.prototype.getEffectDefines = function () {
  59638. return "#define CYLINDEREMITTER\n#define DIRECTEDCYLINDEREMITTER";
  59639. };
  59640. /**
  59641. * Returns the string "CylinderDirectedParticleEmitter"
  59642. * @returns a string containing the class name
  59643. */
  59644. CylinderDirectedParticleEmitter.prototype.getClassName = function () {
  59645. return "CylinderDirectedParticleEmitter";
  59646. };
  59647. /**
  59648. * Serializes the particle system to a JSON object.
  59649. * @returns the JSON object
  59650. */
  59651. CylinderDirectedParticleEmitter.prototype.serialize = function () {
  59652. var serializationObject = _super.prototype.serialize.call(this);
  59653. serializationObject.direction1 = this.direction1.asArray();
  59654. serializationObject.direction2 = this.direction2.asArray();
  59655. return serializationObject;
  59656. };
  59657. /**
  59658. * Parse properties from a JSON object
  59659. * @param serializationObject defines the JSON object
  59660. */
  59661. CylinderDirectedParticleEmitter.prototype.parse = function (serializationObject) {
  59662. _super.prototype.parse.call(this, serializationObject);
  59663. this.direction1.copyFrom(serializationObject.direction1);
  59664. this.direction2.copyFrom(serializationObject.direction2);
  59665. };
  59666. return CylinderDirectedParticleEmitter;
  59667. }(CylinderParticleEmitter));
  59668. BABYLON.CylinderDirectedParticleEmitter = CylinderDirectedParticleEmitter;
  59669. })(BABYLON || (BABYLON = {}));
  59670. //# sourceMappingURL=babylon.cylinderParticleEmitter.js.map
  59671. var BABYLON;
  59672. (function (BABYLON) {
  59673. /**
  59674. * Particle emitter emitting particles from the inside of a cone.
  59675. * It emits the particles alongside the cone volume from the base to the particle.
  59676. * The emission direction might be randomized.
  59677. */
  59678. var ConeParticleEmitter = /** @class */ (function () {
  59679. /**
  59680. * Creates a new instance ConeParticleEmitter
  59681. * @param radius the radius of the emission cone (1 by default)
  59682. * @param angles the cone base angle (PI by default)
  59683. * @param directionRandomizer defines how much to randomize the particle direction [0-1] (default is 0)
  59684. */
  59685. function ConeParticleEmitter(radius, angle,
  59686. /** defines how much to randomize the particle direction [0-1] (default is 0) */
  59687. directionRandomizer) {
  59688. if (radius === void 0) { radius = 1; }
  59689. if (angle === void 0) { angle = Math.PI; }
  59690. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  59691. this.directionRandomizer = directionRandomizer;
  59692. /**
  59693. * Gets or sets a value indicating where on the radius the start position should be picked (1 = everywhere, 0 = only surface)
  59694. */
  59695. this.radiusRange = 1;
  59696. /**
  59697. * Gets or sets a value indicating where on the height the start position should be picked (1 = everywhere, 0 = only surface)
  59698. */
  59699. this.heightRange = 1;
  59700. /**
  59701. * Gets or sets a value indicating if all the particles should be emitted from the spawn point only (the base of the cone)
  59702. */
  59703. this.emitFromSpawnPointOnly = false;
  59704. this.angle = angle;
  59705. this.radius = radius;
  59706. }
  59707. Object.defineProperty(ConeParticleEmitter.prototype, "radius", {
  59708. /**
  59709. * Gets or sets the radius of the emission cone
  59710. */
  59711. get: function () {
  59712. return this._radius;
  59713. },
  59714. set: function (value) {
  59715. this._radius = value;
  59716. this._buildHeight();
  59717. },
  59718. enumerable: true,
  59719. configurable: true
  59720. });
  59721. Object.defineProperty(ConeParticleEmitter.prototype, "angle", {
  59722. /**
  59723. * Gets or sets the angle of the emission cone
  59724. */
  59725. get: function () {
  59726. return this._angle;
  59727. },
  59728. set: function (value) {
  59729. this._angle = value;
  59730. this._buildHeight();
  59731. },
  59732. enumerable: true,
  59733. configurable: true
  59734. });
  59735. ConeParticleEmitter.prototype._buildHeight = function () {
  59736. if (this._angle !== 0) {
  59737. this._height = this._radius / Math.tan(this._angle / 2);
  59738. }
  59739. else {
  59740. this._height = 1;
  59741. }
  59742. };
  59743. /**
  59744. * Called by the particle System when the direction is computed for the created particle.
  59745. * @param worldMatrix is the world matrix of the particle system
  59746. * @param directionToUpdate is the direction vector to update with the result
  59747. * @param particle is the particle we are computed the direction for
  59748. */
  59749. ConeParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  59750. if (Math.abs(Math.cos(this._angle)) === 1.0) {
  59751. BABYLON.Vector3.TransformNormalFromFloatsToRef(0, 1.0, 0, worldMatrix, directionToUpdate);
  59752. }
  59753. else {
  59754. // measure the direction Vector from the emitter to the particle.
  59755. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  59756. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  59757. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  59758. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  59759. direction.x += randX;
  59760. direction.y += randY;
  59761. direction.z += randZ;
  59762. direction.normalize();
  59763. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  59764. }
  59765. };
  59766. /**
  59767. * Called by the particle System when the position is computed for the created particle.
  59768. * @param worldMatrix is the world matrix of the particle system
  59769. * @param positionToUpdate is the position vector to update with the result
  59770. * @param particle is the particle we are computed the position for
  59771. */
  59772. ConeParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  59773. var s = BABYLON.Scalar.RandomRange(0, Math.PI * 2);
  59774. var h;
  59775. if (!this.emitFromSpawnPointOnly) {
  59776. h = BABYLON.Scalar.RandomRange(0, this.heightRange);
  59777. // Better distribution in a cone at normal angles.
  59778. h = 1 - h * h;
  59779. }
  59780. else {
  59781. h = 0.0001;
  59782. }
  59783. var radius = this._radius - BABYLON.Scalar.RandomRange(0, this._radius * this.radiusRange);
  59784. radius = radius * h;
  59785. var randX = radius * Math.sin(s);
  59786. var randZ = radius * Math.cos(s);
  59787. var randY = h * this._height;
  59788. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  59789. };
  59790. /**
  59791. * Clones the current emitter and returns a copy of it
  59792. * @returns the new emitter
  59793. */
  59794. ConeParticleEmitter.prototype.clone = function () {
  59795. var newOne = new ConeParticleEmitter(this._radius, this._angle, this.directionRandomizer);
  59796. BABYLON.Tools.DeepCopy(this, newOne);
  59797. return newOne;
  59798. };
  59799. /**
  59800. * Called by the GPUParticleSystem to setup the update shader
  59801. * @param effect defines the update shader
  59802. */
  59803. ConeParticleEmitter.prototype.applyToShader = function (effect) {
  59804. effect.setFloat2("radius", this._radius, this.radiusRange);
  59805. effect.setFloat("coneAngle", this._angle);
  59806. effect.setFloat2("height", this._height, this.heightRange);
  59807. effect.setFloat("directionRandomizer", this.directionRandomizer);
  59808. };
  59809. /**
  59810. * Returns a string to use to update the GPU particles update shader
  59811. * @returns a string containng the defines string
  59812. */
  59813. ConeParticleEmitter.prototype.getEffectDefines = function () {
  59814. var defines = "#define CONEEMITTER";
  59815. if (this.emitFromSpawnPointOnly) {
  59816. defines += "\n#define CONEEMITTERSPAWNPOINT";
  59817. }
  59818. return defines;
  59819. };
  59820. /**
  59821. * Returns the string "ConeParticleEmitter"
  59822. * @returns a string containing the class name
  59823. */
  59824. ConeParticleEmitter.prototype.getClassName = function () {
  59825. return "ConeParticleEmitter";
  59826. };
  59827. /**
  59828. * Serializes the particle system to a JSON object.
  59829. * @returns the JSON object
  59830. */
  59831. ConeParticleEmitter.prototype.serialize = function () {
  59832. var serializationObject = {};
  59833. serializationObject.type = this.getClassName();
  59834. serializationObject.radius = this._radius;
  59835. serializationObject.angle = this._angle;
  59836. serializationObject.directionRandomizer = this.directionRandomizer;
  59837. return serializationObject;
  59838. };
  59839. /**
  59840. * Parse properties from a JSON object
  59841. * @param serializationObject defines the JSON object
  59842. */
  59843. ConeParticleEmitter.prototype.parse = function (serializationObject) {
  59844. this.radius = serializationObject.radius;
  59845. this.angle = serializationObject.angle;
  59846. this.directionRandomizer = serializationObject.directionRandomizer;
  59847. };
  59848. return ConeParticleEmitter;
  59849. }());
  59850. BABYLON.ConeParticleEmitter = ConeParticleEmitter;
  59851. })(BABYLON || (BABYLON = {}));
  59852. //# sourceMappingURL=babylon.coneParticleEmitter.js.map
  59853. var BABYLON;
  59854. (function (BABYLON) {
  59855. /**
  59856. * Particle emitter emitting particles from the inside of a sphere.
  59857. * It emits the particles alongside the sphere radius. The emission direction might be randomized.
  59858. */
  59859. var SphereParticleEmitter = /** @class */ (function () {
  59860. /**
  59861. * Creates a new instance SphereParticleEmitter
  59862. * @param radius the radius of the emission sphere (1 by default)
  59863. * @param radiusRange the range of the emission sphere [0-1] 0 Surface only, 1 Entire Radius (1 by default)
  59864. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  59865. */
  59866. function SphereParticleEmitter(
  59867. /**
  59868. * The radius of the emission sphere.
  59869. */
  59870. radius,
  59871. /**
  59872. * The range of emission [0-1] 0 Surface only, 1 Entire Radius.
  59873. */
  59874. radiusRange,
  59875. /**
  59876. * How much to randomize the particle direction [0-1].
  59877. */
  59878. directionRandomizer) {
  59879. if (radius === void 0) { radius = 1; }
  59880. if (radiusRange === void 0) { radiusRange = 1; }
  59881. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  59882. this.radius = radius;
  59883. this.radiusRange = radiusRange;
  59884. this.directionRandomizer = directionRandomizer;
  59885. }
  59886. /**
  59887. * Called by the particle System when the direction is computed for the created particle.
  59888. * @param worldMatrix is the world matrix of the particle system
  59889. * @param directionToUpdate is the direction vector to update with the result
  59890. * @param particle is the particle we are computed the direction for
  59891. */
  59892. SphereParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  59893. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  59894. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  59895. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  59896. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  59897. direction.x += randX;
  59898. direction.y += randY;
  59899. direction.z += randZ;
  59900. direction.normalize();
  59901. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  59902. };
  59903. /**
  59904. * Called by the particle System when the position is computed for the created particle.
  59905. * @param worldMatrix is the world matrix of the particle system
  59906. * @param positionToUpdate is the position vector to update with the result
  59907. * @param particle is the particle we are computed the position for
  59908. */
  59909. SphereParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  59910. var randRadius = this.radius - BABYLON.Scalar.RandomRange(0, this.radius * this.radiusRange);
  59911. var v = BABYLON.Scalar.RandomRange(0, 1.0);
  59912. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  59913. var theta = Math.acos(2 * v - 1);
  59914. var randX = randRadius * Math.cos(phi) * Math.sin(theta);
  59915. var randY = randRadius * Math.cos(theta);
  59916. var randZ = randRadius * Math.sin(phi) * Math.sin(theta);
  59917. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  59918. };
  59919. /**
  59920. * Clones the current emitter and returns a copy of it
  59921. * @returns the new emitter
  59922. */
  59923. SphereParticleEmitter.prototype.clone = function () {
  59924. var newOne = new SphereParticleEmitter(this.radius, this.directionRandomizer);
  59925. BABYLON.Tools.DeepCopy(this, newOne);
  59926. return newOne;
  59927. };
  59928. /**
  59929. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  59930. * @param effect defines the update shader
  59931. */
  59932. SphereParticleEmitter.prototype.applyToShader = function (effect) {
  59933. effect.setFloat("radius", this.radius);
  59934. effect.setFloat("radiusRange", this.radiusRange);
  59935. effect.setFloat("directionRandomizer", this.directionRandomizer);
  59936. };
  59937. /**
  59938. * Returns a string to use to update the GPU particles update shader
  59939. * @returns a string containng the defines string
  59940. */
  59941. SphereParticleEmitter.prototype.getEffectDefines = function () {
  59942. return "#define SPHEREEMITTER";
  59943. };
  59944. /**
  59945. * Returns the string "SphereParticleEmitter"
  59946. * @returns a string containing the class name
  59947. */
  59948. SphereParticleEmitter.prototype.getClassName = function () {
  59949. return "SphereParticleEmitter";
  59950. };
  59951. /**
  59952. * Serializes the particle system to a JSON object.
  59953. * @returns the JSON object
  59954. */
  59955. SphereParticleEmitter.prototype.serialize = function () {
  59956. var serializationObject = {};
  59957. serializationObject.type = this.getClassName();
  59958. serializationObject.radius = this.radius;
  59959. serializationObject.radiusRange = this.radiusRange;
  59960. serializationObject.directionRandomizer = this.directionRandomizer;
  59961. return serializationObject;
  59962. };
  59963. /**
  59964. * Parse properties from a JSON object
  59965. * @param serializationObject defines the JSON object
  59966. */
  59967. SphereParticleEmitter.prototype.parse = function (serializationObject) {
  59968. this.radius = serializationObject.radius;
  59969. this.radiusRange = serializationObject.radiusRange;
  59970. this.directionRandomizer = serializationObject.directionRandomizer;
  59971. };
  59972. return SphereParticleEmitter;
  59973. }());
  59974. BABYLON.SphereParticleEmitter = SphereParticleEmitter;
  59975. /**
  59976. * Particle emitter emitting particles from the inside of a sphere.
  59977. * It emits the particles randomly between two vectors.
  59978. */
  59979. var SphereDirectedParticleEmitter = /** @class */ (function (_super) {
  59980. __extends(SphereDirectedParticleEmitter, _super);
  59981. /**
  59982. * Creates a new instance SphereDirectedParticleEmitter
  59983. * @param radius the radius of the emission sphere (1 by default)
  59984. * @param direction1 the min limit of the emission direction (up vector by default)
  59985. * @param direction2 the max limit of the emission direction (up vector by default)
  59986. */
  59987. function SphereDirectedParticleEmitter(radius,
  59988. /**
  59989. * The min limit of the emission direction.
  59990. */
  59991. direction1,
  59992. /**
  59993. * The max limit of the emission direction.
  59994. */
  59995. direction2) {
  59996. if (radius === void 0) { radius = 1; }
  59997. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1, 0); }
  59998. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1, 0); }
  59999. var _this = _super.call(this, radius) || this;
  60000. _this.direction1 = direction1;
  60001. _this.direction2 = direction2;
  60002. return _this;
  60003. }
  60004. /**
  60005. * Called by the particle System when the direction is computed for the created particle.
  60006. * @param worldMatrix is the world matrix of the particle system
  60007. * @param directionToUpdate is the direction vector to update with the result
  60008. * @param particle is the particle we are computed the direction for
  60009. */
  60010. SphereDirectedParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  60011. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  60012. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  60013. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  60014. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  60015. };
  60016. /**
  60017. * Clones the current emitter and returns a copy of it
  60018. * @returns the new emitter
  60019. */
  60020. SphereDirectedParticleEmitter.prototype.clone = function () {
  60021. var newOne = new SphereDirectedParticleEmitter(this.radius, this.direction1, this.direction2);
  60022. BABYLON.Tools.DeepCopy(this, newOne);
  60023. return newOne;
  60024. };
  60025. /**
  60026. * Called by the GPUParticleSystem to setup the update shader
  60027. * @param effect defines the update shader
  60028. */
  60029. SphereDirectedParticleEmitter.prototype.applyToShader = function (effect) {
  60030. effect.setFloat("radius", this.radius);
  60031. effect.setFloat("radiusRange", this.radiusRange);
  60032. effect.setVector3("direction1", this.direction1);
  60033. effect.setVector3("direction2", this.direction2);
  60034. };
  60035. /**
  60036. * Returns a string to use to update the GPU particles update shader
  60037. * @returns a string containng the defines string
  60038. */
  60039. SphereDirectedParticleEmitter.prototype.getEffectDefines = function () {
  60040. return "#define SPHEREEMITTER\n#define DIRECTEDSPHEREEMITTER";
  60041. };
  60042. /**
  60043. * Returns the string "SphereDirectedParticleEmitter"
  60044. * @returns a string containing the class name
  60045. */
  60046. SphereDirectedParticleEmitter.prototype.getClassName = function () {
  60047. return "SphereDirectedParticleEmitter";
  60048. };
  60049. /**
  60050. * Serializes the particle system to a JSON object.
  60051. * @returns the JSON object
  60052. */
  60053. SphereDirectedParticleEmitter.prototype.serialize = function () {
  60054. var serializationObject = _super.prototype.serialize.call(this);
  60055. serializationObject.direction1 = this.direction1.asArray();
  60056. serializationObject.direction2 = this.direction2.asArray();
  60057. return serializationObject;
  60058. };
  60059. /**
  60060. * Parse properties from a JSON object
  60061. * @param serializationObject defines the JSON object
  60062. */
  60063. SphereDirectedParticleEmitter.prototype.parse = function (serializationObject) {
  60064. _super.prototype.parse.call(this, serializationObject);
  60065. this.direction1.copyFrom(serializationObject.direction1);
  60066. this.direction2.copyFrom(serializationObject.direction2);
  60067. };
  60068. return SphereDirectedParticleEmitter;
  60069. }(SphereParticleEmitter));
  60070. BABYLON.SphereDirectedParticleEmitter = SphereDirectedParticleEmitter;
  60071. })(BABYLON || (BABYLON = {}));
  60072. //# sourceMappingURL=babylon.sphereParticleEmitter.js.map
  60073. var BABYLON;
  60074. (function (BABYLON) {
  60075. /**
  60076. * Particle emitter emitting particles from the inside of a hemisphere.
  60077. * It emits the particles alongside the hemisphere radius. The emission direction might be randomized.
  60078. */
  60079. var HemisphericParticleEmitter = /** @class */ (function () {
  60080. /**
  60081. * Creates a new instance HemisphericParticleEmitter
  60082. * @param radius the radius of the emission hemisphere (1 by default)
  60083. * @param radiusRange the range of the emission hemisphere [0-1] 0 Surface only, 1 Entire Radius (1 by default)
  60084. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  60085. */
  60086. function HemisphericParticleEmitter(
  60087. /**
  60088. * The radius of the emission hemisphere.
  60089. */
  60090. radius,
  60091. /**
  60092. * The range of emission [0-1] 0 Surface only, 1 Entire Radius.
  60093. */
  60094. radiusRange,
  60095. /**
  60096. * How much to randomize the particle direction [0-1].
  60097. */
  60098. directionRandomizer) {
  60099. if (radius === void 0) { radius = 1; }
  60100. if (radiusRange === void 0) { radiusRange = 1; }
  60101. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  60102. this.radius = radius;
  60103. this.radiusRange = radiusRange;
  60104. this.directionRandomizer = directionRandomizer;
  60105. }
  60106. /**
  60107. * Called by the particle System when the direction is computed for the created particle.
  60108. * @param worldMatrix is the world matrix of the particle system
  60109. * @param directionToUpdate is the direction vector to update with the result
  60110. * @param particle is the particle we are computed the direction for
  60111. */
  60112. HemisphericParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  60113. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  60114. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  60115. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  60116. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  60117. direction.x += randX;
  60118. direction.y += randY;
  60119. direction.z += randZ;
  60120. direction.normalize();
  60121. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  60122. };
  60123. /**
  60124. * Called by the particle System when the position is computed for the created particle.
  60125. * @param worldMatrix is the world matrix of the particle system
  60126. * @param positionToUpdate is the position vector to update with the result
  60127. * @param particle is the particle we are computed the position for
  60128. */
  60129. HemisphericParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  60130. var randRadius = this.radius - BABYLON.Scalar.RandomRange(0, this.radius * this.radiusRange);
  60131. var v = BABYLON.Scalar.RandomRange(0, 1.0);
  60132. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  60133. var theta = Math.acos(2 * v - 1);
  60134. var randX = randRadius * Math.cos(phi) * Math.sin(theta);
  60135. var randY = randRadius * Math.cos(theta);
  60136. var randZ = randRadius * Math.sin(phi) * Math.sin(theta);
  60137. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, Math.abs(randY), randZ, worldMatrix, positionToUpdate);
  60138. };
  60139. /**
  60140. * Clones the current emitter and returns a copy of it
  60141. * @returns the new emitter
  60142. */
  60143. HemisphericParticleEmitter.prototype.clone = function () {
  60144. var newOne = new HemisphericParticleEmitter(this.radius, this.directionRandomizer);
  60145. BABYLON.Tools.DeepCopy(this, newOne);
  60146. return newOne;
  60147. };
  60148. /**
  60149. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  60150. * @param effect defines the update shader
  60151. */
  60152. HemisphericParticleEmitter.prototype.applyToShader = function (effect) {
  60153. effect.setFloat("radius", this.radius);
  60154. effect.setFloat("radiusRange", this.radiusRange);
  60155. effect.setFloat("directionRandomizer", this.directionRandomizer);
  60156. };
  60157. /**
  60158. * Returns a string to use to update the GPU particles update shader
  60159. * @returns a string containng the defines string
  60160. */
  60161. HemisphericParticleEmitter.prototype.getEffectDefines = function () {
  60162. return "#define HEMISPHERICEMITTER";
  60163. };
  60164. /**
  60165. * Returns the string "HemisphericParticleEmitter"
  60166. * @returns a string containing the class name
  60167. */
  60168. HemisphericParticleEmitter.prototype.getClassName = function () {
  60169. return "HemisphericParticleEmitter";
  60170. };
  60171. /**
  60172. * Serializes the particle system to a JSON object.
  60173. * @returns the JSON object
  60174. */
  60175. HemisphericParticleEmitter.prototype.serialize = function () {
  60176. var serializationObject = {};
  60177. serializationObject.type = this.getClassName();
  60178. serializationObject.radius = this.radius;
  60179. serializationObject.radiusRange = this.radiusRange;
  60180. serializationObject.directionRandomizer = this.directionRandomizer;
  60181. return serializationObject;
  60182. };
  60183. /**
  60184. * Parse properties from a JSON object
  60185. * @param serializationObject defines the JSON object
  60186. */
  60187. HemisphericParticleEmitter.prototype.parse = function (serializationObject) {
  60188. this.radius = serializationObject.radius;
  60189. this.radiusRange = serializationObject.radiusRange;
  60190. this.directionRandomizer = serializationObject.directionRandomizer;
  60191. };
  60192. return HemisphericParticleEmitter;
  60193. }());
  60194. BABYLON.HemisphericParticleEmitter = HemisphericParticleEmitter;
  60195. })(BABYLON || (BABYLON = {}));
  60196. //# sourceMappingURL=babylon.hemisphericParticleEmitter.js.map
  60197. var BABYLON;
  60198. (function (BABYLON) {
  60199. /**
  60200. * Particle emitter emitting particles from a point.
  60201. * It emits the particles randomly between 2 given directions.
  60202. */
  60203. var PointParticleEmitter = /** @class */ (function () {
  60204. /**
  60205. * Creates a new instance PointParticleEmitter
  60206. */
  60207. function PointParticleEmitter() {
  60208. /**
  60209. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  60210. */
  60211. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  60212. /**
  60213. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  60214. */
  60215. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  60216. }
  60217. /**
  60218. * Called by the particle System when the direction is computed for the created particle.
  60219. * @param worldMatrix is the world matrix of the particle system
  60220. * @param directionToUpdate is the direction vector to update with the result
  60221. * @param particle is the particle we are computed the direction for
  60222. */
  60223. PointParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  60224. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  60225. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  60226. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  60227. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  60228. };
  60229. /**
  60230. * Called by the particle System when the position is computed for the created particle.
  60231. * @param worldMatrix is the world matrix of the particle system
  60232. * @param positionToUpdate is the position vector to update with the result
  60233. * @param particle is the particle we are computed the position for
  60234. */
  60235. PointParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  60236. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0, 0, 0, worldMatrix, positionToUpdate);
  60237. };
  60238. /**
  60239. * Clones the current emitter and returns a copy of it
  60240. * @returns the new emitter
  60241. */
  60242. PointParticleEmitter.prototype.clone = function () {
  60243. var newOne = new PointParticleEmitter();
  60244. BABYLON.Tools.DeepCopy(this, newOne);
  60245. return newOne;
  60246. };
  60247. /**
  60248. * Called by the GPUParticleSystem to setup the update shader
  60249. * @param effect defines the update shader
  60250. */
  60251. PointParticleEmitter.prototype.applyToShader = function (effect) {
  60252. effect.setVector3("direction1", this.direction1);
  60253. effect.setVector3("direction2", this.direction2);
  60254. };
  60255. /**
  60256. * Returns a string to use to update the GPU particles update shader
  60257. * @returns a string containng the defines string
  60258. */
  60259. PointParticleEmitter.prototype.getEffectDefines = function () {
  60260. return "#define POINTEMITTER";
  60261. };
  60262. /**
  60263. * Returns the string "PointParticleEmitter"
  60264. * @returns a string containing the class name
  60265. */
  60266. PointParticleEmitter.prototype.getClassName = function () {
  60267. return "PointParticleEmitter";
  60268. };
  60269. /**
  60270. * Serializes the particle system to a JSON object.
  60271. * @returns the JSON object
  60272. */
  60273. PointParticleEmitter.prototype.serialize = function () {
  60274. var serializationObject = {};
  60275. serializationObject.type = this.getClassName();
  60276. serializationObject.direction1 = this.direction1.asArray();
  60277. serializationObject.direction2 = this.direction2.asArray();
  60278. return serializationObject;
  60279. };
  60280. /**
  60281. * Parse properties from a JSON object
  60282. * @param serializationObject defines the JSON object
  60283. */
  60284. PointParticleEmitter.prototype.parse = function (serializationObject) {
  60285. BABYLON.Vector3.FromArrayToRef(serializationObject.direction1, 0, this.direction1);
  60286. BABYLON.Vector3.FromArrayToRef(serializationObject.direction2, 0, this.direction2);
  60287. };
  60288. return PointParticleEmitter;
  60289. }());
  60290. BABYLON.PointParticleEmitter = PointParticleEmitter;
  60291. })(BABYLON || (BABYLON = {}));
  60292. //# sourceMappingURL=babylon.pointParticleEmitter.js.map
  60293. var BABYLON;
  60294. (function (BABYLON) {
  60295. // Adds the parsers to the scene parsers.
  60296. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM, function (parsedData, scene, container, rootUrl) {
  60297. var individualParser = BABYLON.AbstractScene.GetIndividualParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM);
  60298. if (!individualParser) {
  60299. return;
  60300. }
  60301. // Particles Systems
  60302. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  60303. for (var index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  60304. var parsedParticleSystem = parsedData.particleSystems[index];
  60305. container.particleSystems.push(individualParser(parsedParticleSystem, scene, rootUrl));
  60306. }
  60307. }
  60308. });
  60309. BABYLON.AbstractScene.AddIndividualParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM, function (parsedParticleSystem, scene, rootUrl) {
  60310. if (parsedParticleSystem.activeParticleCount) {
  60311. var ps = BABYLON.GPUParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  60312. return ps;
  60313. }
  60314. else {
  60315. var ps = BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  60316. return ps;
  60317. }
  60318. });
  60319. BABYLON.Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  60320. if (uniformsNames === void 0) { uniformsNames = []; }
  60321. if (samplers === void 0) { samplers = []; }
  60322. if (defines === void 0) { defines = ""; }
  60323. var attributesNamesOrOptions = BABYLON.ParticleSystem._GetAttributeNamesOrOptions();
  60324. var effectCreationOption = BABYLON.ParticleSystem._GetEffectCreationOptions();
  60325. if (defines.indexOf(" BILLBOARD") === -1) {
  60326. defines += "\n#define BILLBOARD\n";
  60327. }
  60328. if (samplers.indexOf("diffuseSampler") === -1) {
  60329. samplers.push("diffuseSampler");
  60330. }
  60331. return this.createEffect({
  60332. vertex: "particles",
  60333. fragmentElement: fragmentName
  60334. }, attributesNamesOrOptions, effectCreationOption.concat(uniformsNames), samplers, defines, fallbacks, onCompiled, onError);
  60335. };
  60336. BABYLON.Mesh.prototype.getEmittedParticleSystems = function () {
  60337. var results = new Array();
  60338. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  60339. var particleSystem = this.getScene().particleSystems[index];
  60340. if (particleSystem.emitter === this) {
  60341. results.push(particleSystem);
  60342. }
  60343. }
  60344. return results;
  60345. };
  60346. BABYLON.Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  60347. var results = new Array();
  60348. var descendants = this.getDescendants();
  60349. descendants.push(this);
  60350. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  60351. var particleSystem = this.getScene().particleSystems[index];
  60352. var emitter = particleSystem.emitter;
  60353. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  60354. results.push(particleSystem);
  60355. }
  60356. }
  60357. return results;
  60358. };
  60359. })(BABYLON || (BABYLON = {}));
  60360. //# sourceMappingURL=babylon.particleSystemComponent.js.map
  60361. var BABYLON;
  60362. (function (BABYLON) {
  60363. /**
  60364. * Type of sub emitter
  60365. */
  60366. var SubEmitterType;
  60367. (function (SubEmitterType) {
  60368. /**
  60369. * Attached to the particle over it's lifetime
  60370. */
  60371. SubEmitterType[SubEmitterType["ATTACHED"] = 0] = "ATTACHED";
  60372. /**
  60373. * Created when the particle dies
  60374. */
  60375. SubEmitterType[SubEmitterType["END"] = 1] = "END";
  60376. })(SubEmitterType = BABYLON.SubEmitterType || (BABYLON.SubEmitterType = {}));
  60377. /**
  60378. * Sub emitter class used to emit particles from an existing particle
  60379. */
  60380. var SubEmitter = /** @class */ (function () {
  60381. /**
  60382. * Creates a sub emitter
  60383. * @param particleSystem the particle system to be used by the sub emitter
  60384. */
  60385. function SubEmitter(
  60386. /**
  60387. * the particle system to be used by the sub emitter
  60388. */
  60389. particleSystem) {
  60390. this.particleSystem = particleSystem;
  60391. /**
  60392. * Type of the submitter (Default: END)
  60393. */
  60394. this.type = SubEmitterType.END;
  60395. /**
  60396. * If the particle should inherit the direction from the particle it's attached to. (+Y will face the direction the particle is moving) (Default: false)
  60397. * Note: This only is supported when using an emitter of type Mesh
  60398. */
  60399. this.inheritDirection = false;
  60400. /**
  60401. * How much of the attached particles speed should be added to the sub emitted particle (default: 0)
  60402. */
  60403. this.inheritedVelocityAmount = 0;
  60404. }
  60405. /**
  60406. * Clones the sub emitter
  60407. * @returns the cloned sub emitter
  60408. */
  60409. SubEmitter.prototype.clone = function () {
  60410. // Clone particle system
  60411. var emitter = this.particleSystem.emitter;
  60412. if (!emitter) {
  60413. emitter = new BABYLON.Vector3();
  60414. }
  60415. else if (emitter instanceof BABYLON.Vector3) {
  60416. emitter = emitter.clone();
  60417. }
  60418. else if (emitter instanceof BABYLON.AbstractMesh) {
  60419. emitter = new BABYLON.Mesh("", emitter.getScene());
  60420. emitter.isVisible = false;
  60421. }
  60422. var clone = new SubEmitter(this.particleSystem.clone("", emitter));
  60423. // Clone properties
  60424. clone.type = this.type;
  60425. clone.inheritDirection = this.inheritDirection;
  60426. clone.inheritedVelocityAmount = this.inheritedVelocityAmount;
  60427. clone.particleSystem._disposeEmitterOnDispose = true;
  60428. clone.particleSystem.disposeOnStop = true;
  60429. return clone;
  60430. };
  60431. /**
  60432. * Serialize current object to a JSON object
  60433. * @returns the serialized object
  60434. */
  60435. SubEmitter.prototype.serialize = function () {
  60436. var serializationObject = {};
  60437. serializationObject.type = this.type;
  60438. serializationObject.inheritDirection = this.inheritDirection;
  60439. serializationObject.inheritedVelocityAmount = this.inheritedVelocityAmount;
  60440. serializationObject.particleSystem = this.particleSystem.serialize();
  60441. return serializationObject;
  60442. };
  60443. /**
  60444. * Creates a new SubEmitter from a serialized JSON version
  60445. * @param serializationObject defines the JSON object to read from
  60446. * @param scene defines the hosting scene
  60447. * @param rootUrl defines the rootUrl for data loading
  60448. * @returns a new SubEmitter
  60449. */
  60450. SubEmitter.Parse = function (serializationObject, scene, rootUrl) {
  60451. var system = serializationObject.particleSystem;
  60452. var subEmitter = new SubEmitter(BABYLON.ParticleSystem.Parse(system, scene, rootUrl));
  60453. subEmitter.type = serializationObject.type;
  60454. subEmitter.inheritDirection = serializationObject.inheritDirection;
  60455. subEmitter.inheritedVelocityAmount = serializationObject.inheritedVelocityAmount;
  60456. return subEmitter;
  60457. };
  60458. /** Release associated resources */
  60459. SubEmitter.prototype.dispose = function () {
  60460. this.particleSystem.dispose();
  60461. };
  60462. return SubEmitter;
  60463. }());
  60464. BABYLON.SubEmitter = SubEmitter;
  60465. })(BABYLON || (BABYLON = {}));
  60466. //# sourceMappingURL=babylon.subEmitter.js.map
  60467. var BABYLON;
  60468. (function (BABYLON) {
  60469. var ShaderMaterial = /** @class */ (function (_super) {
  60470. __extends(ShaderMaterial, _super);
  60471. function ShaderMaterial(name, scene, shaderPath, options) {
  60472. var _this = _super.call(this, name, scene) || this;
  60473. _this._textures = {};
  60474. _this._textureArrays = {};
  60475. _this._floats = {};
  60476. _this._ints = {};
  60477. _this._floatsArrays = {};
  60478. _this._colors3 = {};
  60479. _this._colors3Arrays = {};
  60480. _this._colors4 = {};
  60481. _this._vectors2 = {};
  60482. _this._vectors3 = {};
  60483. _this._vectors4 = {};
  60484. _this._matrices = {};
  60485. _this._matrices3x3 = {};
  60486. _this._matrices2x2 = {};
  60487. _this._vectors2Arrays = {};
  60488. _this._vectors3Arrays = {};
  60489. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  60490. _this._shaderPath = shaderPath;
  60491. options.needAlphaBlending = options.needAlphaBlending || false;
  60492. options.needAlphaTesting = options.needAlphaTesting || false;
  60493. options.attributes = options.attributes || ["position", "normal", "uv"];
  60494. options.uniforms = options.uniforms || ["worldViewProjection"];
  60495. options.uniformBuffers = options.uniformBuffers || [];
  60496. options.samplers = options.samplers || [];
  60497. options.defines = options.defines || [];
  60498. _this._options = options;
  60499. return _this;
  60500. }
  60501. ShaderMaterial.prototype.getClassName = function () {
  60502. return "ShaderMaterial";
  60503. };
  60504. ShaderMaterial.prototype.needAlphaBlending = function () {
  60505. return this._options.needAlphaBlending;
  60506. };
  60507. ShaderMaterial.prototype.needAlphaTesting = function () {
  60508. return this._options.needAlphaTesting;
  60509. };
  60510. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  60511. if (this._options.uniforms.indexOf(uniformName) === -1) {
  60512. this._options.uniforms.push(uniformName);
  60513. }
  60514. };
  60515. ShaderMaterial.prototype.setTexture = function (name, texture) {
  60516. if (this._options.samplers.indexOf(name) === -1) {
  60517. this._options.samplers.push(name);
  60518. }
  60519. this._textures[name] = texture;
  60520. return this;
  60521. };
  60522. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  60523. if (this._options.samplers.indexOf(name) === -1) {
  60524. this._options.samplers.push(name);
  60525. }
  60526. this._checkUniform(name);
  60527. this._textureArrays[name] = textures;
  60528. return this;
  60529. };
  60530. ShaderMaterial.prototype.setFloat = function (name, value) {
  60531. this._checkUniform(name);
  60532. this._floats[name] = value;
  60533. return this;
  60534. };
  60535. ShaderMaterial.prototype.setInt = function (name, value) {
  60536. this._checkUniform(name);
  60537. this._ints[name] = value;
  60538. return this;
  60539. };
  60540. ShaderMaterial.prototype.setFloats = function (name, value) {
  60541. this._checkUniform(name);
  60542. this._floatsArrays[name] = value;
  60543. return this;
  60544. };
  60545. ShaderMaterial.prototype.setColor3 = function (name, value) {
  60546. this._checkUniform(name);
  60547. this._colors3[name] = value;
  60548. return this;
  60549. };
  60550. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  60551. this._checkUniform(name);
  60552. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  60553. color.toArray(arr, arr.length);
  60554. return arr;
  60555. }, []);
  60556. return this;
  60557. };
  60558. ShaderMaterial.prototype.setColor4 = function (name, value) {
  60559. this._checkUniform(name);
  60560. this._colors4[name] = value;
  60561. return this;
  60562. };
  60563. ShaderMaterial.prototype.setVector2 = function (name, value) {
  60564. this._checkUniform(name);
  60565. this._vectors2[name] = value;
  60566. return this;
  60567. };
  60568. ShaderMaterial.prototype.setVector3 = function (name, value) {
  60569. this._checkUniform(name);
  60570. this._vectors3[name] = value;
  60571. return this;
  60572. };
  60573. ShaderMaterial.prototype.setVector4 = function (name, value) {
  60574. this._checkUniform(name);
  60575. this._vectors4[name] = value;
  60576. return this;
  60577. };
  60578. ShaderMaterial.prototype.setMatrix = function (name, value) {
  60579. this._checkUniform(name);
  60580. this._matrices[name] = value;
  60581. return this;
  60582. };
  60583. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  60584. this._checkUniform(name);
  60585. this._matrices3x3[name] = value;
  60586. return this;
  60587. };
  60588. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  60589. this._checkUniform(name);
  60590. this._matrices2x2[name] = value;
  60591. return this;
  60592. };
  60593. ShaderMaterial.prototype.setArray2 = function (name, value) {
  60594. this._checkUniform(name);
  60595. this._vectors2Arrays[name] = value;
  60596. return this;
  60597. };
  60598. ShaderMaterial.prototype.setArray3 = function (name, value) {
  60599. this._checkUniform(name);
  60600. this._vectors3Arrays[name] = value;
  60601. return this;
  60602. };
  60603. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  60604. if (!mesh) {
  60605. return true;
  60606. }
  60607. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  60608. return false;
  60609. }
  60610. return false;
  60611. };
  60612. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  60613. var scene = this.getScene();
  60614. var engine = scene.getEngine();
  60615. if (!this.checkReadyOnEveryCall) {
  60616. if (this._renderId === scene.getRenderId()) {
  60617. if (this._checkCache(scene, mesh, useInstances)) {
  60618. return true;
  60619. }
  60620. }
  60621. }
  60622. // Instances
  60623. var defines = [];
  60624. var attribs = [];
  60625. var fallbacks = new BABYLON.EffectFallbacks();
  60626. if (useInstances) {
  60627. defines.push("#define INSTANCES");
  60628. }
  60629. for (var index = 0; index < this._options.defines.length; index++) {
  60630. defines.push(this._options.defines[index]);
  60631. }
  60632. for (var index = 0; index < this._options.attributes.length; index++) {
  60633. attribs.push(this._options.attributes[index]);
  60634. }
  60635. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  60636. attribs.push(BABYLON.VertexBuffer.ColorKind);
  60637. defines.push("#define VERTEXCOLOR");
  60638. }
  60639. // Bones
  60640. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  60641. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  60642. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  60643. if (mesh.numBoneInfluencers > 4) {
  60644. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  60645. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  60646. }
  60647. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  60648. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  60649. fallbacks.addCPUSkinningFallback(0, mesh);
  60650. if (this._options.uniforms.indexOf("mBones") === -1) {
  60651. this._options.uniforms.push("mBones");
  60652. }
  60653. }
  60654. else {
  60655. defines.push("#define NUM_BONE_INFLUENCERS 0");
  60656. }
  60657. // Textures
  60658. for (var name in this._textures) {
  60659. if (!this._textures[name].isReady()) {
  60660. return false;
  60661. }
  60662. }
  60663. // Alpha test
  60664. if (mesh && this._shouldTurnAlphaTestOn(mesh)) {
  60665. defines.push("#define ALPHATEST");
  60666. }
  60667. var previousEffect = this._effect;
  60668. var join = defines.join("\n");
  60669. this._effect = engine.createEffect(this._shaderPath, {
  60670. attributes: attribs,
  60671. uniformsNames: this._options.uniforms,
  60672. uniformBuffersNames: this._options.uniformBuffers,
  60673. samplers: this._options.samplers,
  60674. defines: join,
  60675. fallbacks: fallbacks,
  60676. onCompiled: this.onCompiled,
  60677. onError: this.onError
  60678. }, engine);
  60679. if (!this._effect.isReady()) {
  60680. return false;
  60681. }
  60682. if (previousEffect !== this._effect) {
  60683. scene.resetCachedMaterial();
  60684. }
  60685. this._renderId = scene.getRenderId();
  60686. return true;
  60687. };
  60688. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  60689. var scene = this.getScene();
  60690. if (!this._effect) {
  60691. return;
  60692. }
  60693. if (this._options.uniforms.indexOf("world") !== -1) {
  60694. this._effect.setMatrix("world", world);
  60695. }
  60696. if (this._options.uniforms.indexOf("worldView") !== -1) {
  60697. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  60698. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  60699. }
  60700. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  60701. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  60702. }
  60703. };
  60704. ShaderMaterial.prototype.bind = function (world, mesh) {
  60705. // Std values
  60706. this.bindOnlyWorldMatrix(world);
  60707. if (this._effect && this.getScene().getCachedMaterial() !== this) {
  60708. if (this._options.uniforms.indexOf("view") !== -1) {
  60709. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  60710. }
  60711. if (this._options.uniforms.indexOf("projection") !== -1) {
  60712. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  60713. }
  60714. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  60715. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  60716. }
  60717. // Bones
  60718. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  60719. var name;
  60720. // Texture
  60721. for (name in this._textures) {
  60722. this._effect.setTexture(name, this._textures[name]);
  60723. }
  60724. // Texture arrays
  60725. for (name in this._textureArrays) {
  60726. this._effect.setTextureArray(name, this._textureArrays[name]);
  60727. }
  60728. // Int
  60729. for (name in this._ints) {
  60730. this._effect.setInt(name, this._ints[name]);
  60731. }
  60732. // Float
  60733. for (name in this._floats) {
  60734. this._effect.setFloat(name, this._floats[name]);
  60735. }
  60736. // Floats
  60737. for (name in this._floatsArrays) {
  60738. this._effect.setArray(name, this._floatsArrays[name]);
  60739. }
  60740. // Color3
  60741. for (name in this._colors3) {
  60742. this._effect.setColor3(name, this._colors3[name]);
  60743. }
  60744. for (name in this._colors3Arrays) {
  60745. this._effect.setArray3(name, this._colors3Arrays[name]);
  60746. }
  60747. // Color4
  60748. for (name in this._colors4) {
  60749. var color = this._colors4[name];
  60750. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  60751. }
  60752. // Vector2
  60753. for (name in this._vectors2) {
  60754. this._effect.setVector2(name, this._vectors2[name]);
  60755. }
  60756. // Vector3
  60757. for (name in this._vectors3) {
  60758. this._effect.setVector3(name, this._vectors3[name]);
  60759. }
  60760. // Vector4
  60761. for (name in this._vectors4) {
  60762. this._effect.setVector4(name, this._vectors4[name]);
  60763. }
  60764. // Matrix
  60765. for (name in this._matrices) {
  60766. this._effect.setMatrix(name, this._matrices[name]);
  60767. }
  60768. // Matrix 3x3
  60769. for (name in this._matrices3x3) {
  60770. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  60771. }
  60772. // Matrix 2x2
  60773. for (name in this._matrices2x2) {
  60774. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  60775. }
  60776. // Vector2Array
  60777. for (name in this._vectors2Arrays) {
  60778. this._effect.setArray2(name, this._vectors2Arrays[name]);
  60779. }
  60780. // Vector3Array
  60781. for (name in this._vectors3Arrays) {
  60782. this._effect.setArray3(name, this._vectors3Arrays[name]);
  60783. }
  60784. }
  60785. this._afterBind(mesh);
  60786. };
  60787. ShaderMaterial.prototype.getActiveTextures = function () {
  60788. var activeTextures = _super.prototype.getActiveTextures.call(this);
  60789. for (var name in this._textures) {
  60790. activeTextures.push(this._textures[name]);
  60791. }
  60792. for (var name in this._textureArrays) {
  60793. var array = this._textureArrays[name];
  60794. for (var index = 0; index < array.length; index++) {
  60795. activeTextures.push(array[index]);
  60796. }
  60797. }
  60798. return activeTextures;
  60799. };
  60800. ShaderMaterial.prototype.hasTexture = function (texture) {
  60801. if (_super.prototype.hasTexture.call(this, texture)) {
  60802. return true;
  60803. }
  60804. for (var name in this._textures) {
  60805. if (this._textures[name] === texture) {
  60806. return true;
  60807. }
  60808. }
  60809. for (var name in this._textureArrays) {
  60810. var array = this._textureArrays[name];
  60811. for (var index = 0; index < array.length; index++) {
  60812. if (array[index] === texture) {
  60813. return true;
  60814. }
  60815. }
  60816. }
  60817. return false;
  60818. };
  60819. ShaderMaterial.prototype.clone = function (name) {
  60820. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  60821. return newShaderMaterial;
  60822. };
  60823. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  60824. if (forceDisposeTextures) {
  60825. var name;
  60826. for (name in this._textures) {
  60827. this._textures[name].dispose();
  60828. }
  60829. for (name in this._textureArrays) {
  60830. var array = this._textureArrays[name];
  60831. for (var index = 0; index < array.length; index++) {
  60832. array[index].dispose();
  60833. }
  60834. }
  60835. }
  60836. this._textures = {};
  60837. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  60838. };
  60839. ShaderMaterial.prototype.serialize = function () {
  60840. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  60841. serializationObject.customType = "BABYLON.ShaderMaterial";
  60842. serializationObject.options = this._options;
  60843. serializationObject.shaderPath = this._shaderPath;
  60844. var name;
  60845. // Texture
  60846. serializationObject.textures = {};
  60847. for (name in this._textures) {
  60848. serializationObject.textures[name] = this._textures[name].serialize();
  60849. }
  60850. // Texture arrays
  60851. serializationObject.textureArrays = {};
  60852. for (name in this._textureArrays) {
  60853. serializationObject.textureArrays[name] = [];
  60854. var array = this._textureArrays[name];
  60855. for (var index = 0; index < array.length; index++) {
  60856. serializationObject.textureArrays[name].push(array[index].serialize());
  60857. }
  60858. }
  60859. // Float
  60860. serializationObject.floats = {};
  60861. for (name in this._floats) {
  60862. serializationObject.floats[name] = this._floats[name];
  60863. }
  60864. // Float s
  60865. serializationObject.FloatArrays = {};
  60866. for (name in this._floatsArrays) {
  60867. serializationObject.FloatArrays[name] = this._floatsArrays[name];
  60868. }
  60869. // Color3
  60870. serializationObject.colors3 = {};
  60871. for (name in this._colors3) {
  60872. serializationObject.colors3[name] = this._colors3[name].asArray();
  60873. }
  60874. // Color3 array
  60875. serializationObject.colors3Arrays = {};
  60876. for (name in this._colors3Arrays) {
  60877. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  60878. }
  60879. // Color4
  60880. serializationObject.colors4 = {};
  60881. for (name in this._colors4) {
  60882. serializationObject.colors4[name] = this._colors4[name].asArray();
  60883. }
  60884. // Vector2
  60885. serializationObject.vectors2 = {};
  60886. for (name in this._vectors2) {
  60887. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  60888. }
  60889. // Vector3
  60890. serializationObject.vectors3 = {};
  60891. for (name in this._vectors3) {
  60892. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  60893. }
  60894. // Vector4
  60895. serializationObject.vectors4 = {};
  60896. for (name in this._vectors4) {
  60897. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  60898. }
  60899. // Matrix
  60900. serializationObject.matrices = {};
  60901. for (name in this._matrices) {
  60902. serializationObject.matrices[name] = this._matrices[name].asArray();
  60903. }
  60904. // Matrix 3x3
  60905. serializationObject.matrices3x3 = {};
  60906. for (name in this._matrices3x3) {
  60907. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  60908. }
  60909. // Matrix 2x2
  60910. serializationObject.matrices2x2 = {};
  60911. for (name in this._matrices2x2) {
  60912. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  60913. }
  60914. // Vector2Array
  60915. serializationObject.vectors2Arrays = {};
  60916. for (name in this._vectors2Arrays) {
  60917. serializationObject.vectors2Arrays[name] = this._vectors2Arrays[name];
  60918. }
  60919. // Vector3Array
  60920. serializationObject.vectors3Arrays = {};
  60921. for (name in this._vectors3Arrays) {
  60922. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  60923. }
  60924. return serializationObject;
  60925. };
  60926. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  60927. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  60928. var name;
  60929. // Texture
  60930. for (name in source.textures) {
  60931. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  60932. }
  60933. // Texture arrays
  60934. for (name in source.textureArrays) {
  60935. var array = source.textureArrays[name];
  60936. var textureArray = new Array();
  60937. for (var index = 0; index < array.length; index++) {
  60938. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  60939. }
  60940. material.setTextureArray(name, textureArray);
  60941. }
  60942. // Float
  60943. for (name in source.floats) {
  60944. material.setFloat(name, source.floats[name]);
  60945. }
  60946. // Float s
  60947. for (name in source.floatsArrays) {
  60948. material.setFloats(name, source.floatsArrays[name]);
  60949. }
  60950. // Color3
  60951. for (name in source.colors3) {
  60952. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  60953. }
  60954. // Color3 arrays
  60955. for (name in source.colors3Arrays) {
  60956. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  60957. if (i % 3 === 0) {
  60958. arr.push([num]);
  60959. }
  60960. else {
  60961. arr[arr.length - 1].push(num);
  60962. }
  60963. return arr;
  60964. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  60965. material.setColor3Array(name, colors);
  60966. }
  60967. // Color4
  60968. for (name in source.colors4) {
  60969. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  60970. }
  60971. // Vector2
  60972. for (name in source.vectors2) {
  60973. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  60974. }
  60975. // Vector3
  60976. for (name in source.vectors3) {
  60977. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  60978. }
  60979. // Vector4
  60980. for (name in source.vectors4) {
  60981. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  60982. }
  60983. // Matrix
  60984. for (name in source.matrices) {
  60985. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  60986. }
  60987. // Matrix 3x3
  60988. for (name in source.matrices3x3) {
  60989. material.setMatrix3x3(name, source.matrices3x3[name]);
  60990. }
  60991. // Matrix 2x2
  60992. for (name in source.matrices2x2) {
  60993. material.setMatrix2x2(name, source.matrices2x2[name]);
  60994. }
  60995. // Vector2Array
  60996. for (name in source.vectors2Arrays) {
  60997. material.setArray2(name, source.vectors2Arrays[name]);
  60998. }
  60999. // Vector3Array
  61000. for (name in source.vectors3Arrays) {
  61001. material.setArray3(name, source.vectors3Arrays[name]);
  61002. }
  61003. return material;
  61004. };
  61005. return ShaderMaterial;
  61006. }(BABYLON.Material));
  61007. BABYLON.ShaderMaterial = ShaderMaterial;
  61008. })(BABYLON || (BABYLON = {}));
  61009. //# sourceMappingURL=babylon.shaderMaterial.js.map
  61010. var BABYLON;
  61011. (function (BABYLON) {
  61012. var GroundMesh = /** @class */ (function (_super) {
  61013. __extends(GroundMesh, _super);
  61014. function GroundMesh(name, scene) {
  61015. var _this = _super.call(this, name, scene) || this;
  61016. _this.generateOctree = false;
  61017. return _this;
  61018. }
  61019. GroundMesh.prototype.getClassName = function () {
  61020. return "GroundMesh";
  61021. };
  61022. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  61023. get: function () {
  61024. return Math.min(this._subdivisionsX, this._subdivisionsY);
  61025. },
  61026. enumerable: true,
  61027. configurable: true
  61028. });
  61029. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  61030. get: function () {
  61031. return this._subdivisionsX;
  61032. },
  61033. enumerable: true,
  61034. configurable: true
  61035. });
  61036. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  61037. get: function () {
  61038. return this._subdivisionsY;
  61039. },
  61040. enumerable: true,
  61041. configurable: true
  61042. });
  61043. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  61044. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  61045. this._subdivisionsX = chunksCount;
  61046. this._subdivisionsY = chunksCount;
  61047. this.subdivide(chunksCount);
  61048. // Call the octree system optimization if it is defined.
  61049. var thisAsAny = this;
  61050. if (thisAsAny.createOrUpdateSubmeshesOctree) {
  61051. thisAsAny.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  61052. }
  61053. };
  61054. /**
  61055. * Returns a height (y) value in the Worl system :
  61056. * the ground altitude at the coordinates (x, z) expressed in the World system.
  61057. * Returns the ground y position if (x, z) are outside the ground surface.
  61058. */
  61059. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  61060. var world = this.getWorldMatrix();
  61061. var invMat = BABYLON.Tmp.Matrix[5];
  61062. world.invertToRef(invMat);
  61063. var tmpVect = BABYLON.Tmp.Vector3[8];
  61064. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  61065. x = tmpVect.x;
  61066. z = tmpVect.z;
  61067. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  61068. return this.position.y;
  61069. }
  61070. if (!this._heightQuads || this._heightQuads.length == 0) {
  61071. this._initHeightQuads();
  61072. this._computeHeightQuads();
  61073. }
  61074. var facet = this._getFacetAt(x, z);
  61075. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  61076. // return y in the World system
  61077. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  61078. return tmpVect.y;
  61079. };
  61080. /**
  61081. * Returns a normalized vector (Vector3) orthogonal to the ground
  61082. * at the ground coordinates (x, z) expressed in the World system.
  61083. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  61084. */
  61085. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  61086. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  61087. this.getNormalAtCoordinatesToRef(x, z, normal);
  61088. return normal;
  61089. };
  61090. /**
  61091. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  61092. * at the ground coordinates (x, z) expressed in the World system.
  61093. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  61094. * Returns the GroundMesh.
  61095. */
  61096. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  61097. var world = this.getWorldMatrix();
  61098. var tmpMat = BABYLON.Tmp.Matrix[5];
  61099. world.invertToRef(tmpMat);
  61100. var tmpVect = BABYLON.Tmp.Vector3[8];
  61101. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  61102. x = tmpVect.x;
  61103. z = tmpVect.z;
  61104. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  61105. return this;
  61106. }
  61107. if (!this._heightQuads || this._heightQuads.length == 0) {
  61108. this._initHeightQuads();
  61109. this._computeHeightQuads();
  61110. }
  61111. var facet = this._getFacetAt(x, z);
  61112. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  61113. return this;
  61114. };
  61115. /**
  61116. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  61117. * if the ground has been updated.
  61118. * This can be used in the render loop.
  61119. * Returns the GroundMesh.
  61120. */
  61121. GroundMesh.prototype.updateCoordinateHeights = function () {
  61122. if (!this._heightQuads || this._heightQuads.length == 0) {
  61123. this._initHeightQuads();
  61124. }
  61125. this._computeHeightQuads();
  61126. return this;
  61127. };
  61128. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  61129. GroundMesh.prototype._getFacetAt = function (x, z) {
  61130. // retrieve col and row from x, z coordinates in the ground local system
  61131. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  61132. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  61133. var quad = this._heightQuads[row * this._subdivisionsX + col];
  61134. var facet;
  61135. if (z < quad.slope.x * x + quad.slope.y) {
  61136. facet = quad.facet1;
  61137. }
  61138. else {
  61139. facet = quad.facet2;
  61140. }
  61141. return facet;
  61142. };
  61143. // Creates and populates the heightMap array with "facet" elements :
  61144. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  61145. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  61146. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  61147. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  61148. // Returns the GroundMesh.
  61149. GroundMesh.prototype._initHeightQuads = function () {
  61150. var subdivisionsX = this._subdivisionsX;
  61151. var subdivisionsY = this._subdivisionsY;
  61152. this._heightQuads = new Array();
  61153. for (var row = 0; row < subdivisionsY; row++) {
  61154. for (var col = 0; col < subdivisionsX; col++) {
  61155. 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) };
  61156. this._heightQuads[row * subdivisionsX + col] = quad;
  61157. }
  61158. }
  61159. return this;
  61160. };
  61161. // Compute each quad element values and update the the heightMap array :
  61162. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  61163. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  61164. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  61165. // Returns the GroundMesh.
  61166. GroundMesh.prototype._computeHeightQuads = function () {
  61167. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  61168. if (!positions) {
  61169. return this;
  61170. }
  61171. var v1 = BABYLON.Tmp.Vector3[3];
  61172. var v2 = BABYLON.Tmp.Vector3[2];
  61173. var v3 = BABYLON.Tmp.Vector3[1];
  61174. var v4 = BABYLON.Tmp.Vector3[0];
  61175. var v1v2 = BABYLON.Tmp.Vector3[4];
  61176. var v1v3 = BABYLON.Tmp.Vector3[5];
  61177. var v1v4 = BABYLON.Tmp.Vector3[6];
  61178. var norm1 = BABYLON.Tmp.Vector3[7];
  61179. var norm2 = BABYLON.Tmp.Vector3[8];
  61180. var i = 0;
  61181. var j = 0;
  61182. var k = 0;
  61183. var cd = 0; // 2D slope coefficient : z = cd * x + h
  61184. var h = 0;
  61185. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  61186. var d2 = 0;
  61187. var subdivisionsX = this._subdivisionsX;
  61188. var subdivisionsY = this._subdivisionsY;
  61189. for (var row = 0; row < subdivisionsY; row++) {
  61190. for (var col = 0; col < subdivisionsX; col++) {
  61191. i = col * 3;
  61192. j = row * (subdivisionsX + 1) * 3;
  61193. k = (row + 1) * (subdivisionsX + 1) * 3;
  61194. v1.x = positions[j + i];
  61195. v1.y = positions[j + i + 1];
  61196. v1.z = positions[j + i + 2];
  61197. v2.x = positions[j + i + 3];
  61198. v2.y = positions[j + i + 4];
  61199. v2.z = positions[j + i + 5];
  61200. v3.x = positions[k + i];
  61201. v3.y = positions[k + i + 1];
  61202. v3.z = positions[k + i + 2];
  61203. v4.x = positions[k + i + 3];
  61204. v4.y = positions[k + i + 4];
  61205. v4.z = positions[k + i + 5];
  61206. // 2D slope V1V4
  61207. cd = (v4.z - v1.z) / (v4.x - v1.x);
  61208. h = v1.z - cd * v1.x; // v1 belongs to the slope
  61209. // facet equations :
  61210. // we compute each facet normal vector
  61211. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  61212. // we compute the value d by applying the equation to v1 which belongs to the plane
  61213. // then we store the facet equation in a Vector4
  61214. v2.subtractToRef(v1, v1v2);
  61215. v3.subtractToRef(v1, v1v3);
  61216. v4.subtractToRef(v1, v1v4);
  61217. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  61218. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  61219. norm1.normalize();
  61220. norm2.normalize();
  61221. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  61222. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  61223. var quad = this._heightQuads[row * subdivisionsX + col];
  61224. quad.slope.copyFromFloats(cd, h);
  61225. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  61226. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  61227. }
  61228. }
  61229. return this;
  61230. };
  61231. GroundMesh.prototype.serialize = function (serializationObject) {
  61232. _super.prototype.serialize.call(this, serializationObject);
  61233. serializationObject.subdivisionsX = this._subdivisionsX;
  61234. serializationObject.subdivisionsY = this._subdivisionsY;
  61235. serializationObject.minX = this._minX;
  61236. serializationObject.maxX = this._maxX;
  61237. serializationObject.minZ = this._minZ;
  61238. serializationObject.maxZ = this._maxZ;
  61239. serializationObject.width = this._width;
  61240. serializationObject.height = this._height;
  61241. };
  61242. GroundMesh.Parse = function (parsedMesh, scene) {
  61243. var result = new GroundMesh(parsedMesh.name, scene);
  61244. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  61245. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  61246. result._minX = parsedMesh.minX;
  61247. result._maxX = parsedMesh.maxX;
  61248. result._minZ = parsedMesh.minZ;
  61249. result._maxZ = parsedMesh.maxZ;
  61250. result._width = parsedMesh.width;
  61251. result._height = parsedMesh.height;
  61252. return result;
  61253. };
  61254. return GroundMesh;
  61255. }(BABYLON.Mesh));
  61256. BABYLON.GroundMesh = GroundMesh;
  61257. })(BABYLON || (BABYLON = {}));
  61258. //# sourceMappingURL=babylon.groundMesh.js.map
  61259. var BABYLON;
  61260. (function (BABYLON) {
  61261. /**
  61262. * Creates an instance based on a source mesh.
  61263. */
  61264. var InstancedMesh = /** @class */ (function (_super) {
  61265. __extends(InstancedMesh, _super);
  61266. function InstancedMesh(name, source) {
  61267. var _this = _super.call(this, name, source.getScene()) || this;
  61268. source.instances.push(_this);
  61269. _this._sourceMesh = source;
  61270. _this.position.copyFrom(source.position);
  61271. _this.rotation.copyFrom(source.rotation);
  61272. _this.scaling.copyFrom(source.scaling);
  61273. if (source.rotationQuaternion) {
  61274. _this.rotationQuaternion = source.rotationQuaternion.clone();
  61275. }
  61276. _this.infiniteDistance = source.infiniteDistance;
  61277. _this.setPivotMatrix(source.getPivotMatrix());
  61278. _this.refreshBoundingInfo();
  61279. _this._syncSubMeshes();
  61280. return _this;
  61281. }
  61282. /**
  61283. * Returns the string "InstancedMesh".
  61284. */
  61285. InstancedMesh.prototype.getClassName = function () {
  61286. return "InstancedMesh";
  61287. };
  61288. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  61289. // Methods
  61290. get: function () {
  61291. return this._sourceMesh.receiveShadows;
  61292. },
  61293. enumerable: true,
  61294. configurable: true
  61295. });
  61296. Object.defineProperty(InstancedMesh.prototype, "material", {
  61297. get: function () {
  61298. return this._sourceMesh.material;
  61299. },
  61300. enumerable: true,
  61301. configurable: true
  61302. });
  61303. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  61304. get: function () {
  61305. return this._sourceMesh.visibility;
  61306. },
  61307. enumerable: true,
  61308. configurable: true
  61309. });
  61310. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  61311. get: function () {
  61312. return this._sourceMesh.skeleton;
  61313. },
  61314. enumerable: true,
  61315. configurable: true
  61316. });
  61317. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  61318. get: function () {
  61319. return this._sourceMesh.renderingGroupId;
  61320. },
  61321. set: function (value) {
  61322. if (!this._sourceMesh || value === this._sourceMesh.renderingGroupId) {
  61323. return;
  61324. }
  61325. //no-op with warning
  61326. BABYLON.Tools.Warn("Note - setting renderingGroupId of an instanced mesh has no effect on the scene");
  61327. },
  61328. enumerable: true,
  61329. configurable: true
  61330. });
  61331. /**
  61332. * Returns the total number of vertices (integer).
  61333. */
  61334. InstancedMesh.prototype.getTotalVertices = function () {
  61335. return this._sourceMesh.getTotalVertices();
  61336. };
  61337. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  61338. get: function () {
  61339. return this._sourceMesh;
  61340. },
  61341. enumerable: true,
  61342. configurable: true
  61343. });
  61344. /**
  61345. * Is this node ready to be used/rendered
  61346. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  61347. * @return {boolean} is it ready
  61348. */
  61349. InstancedMesh.prototype.isReady = function (completeCheck) {
  61350. if (completeCheck === void 0) { completeCheck = false; }
  61351. return this._sourceMesh.isReady(completeCheck, true);
  61352. };
  61353. /**
  61354. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  61355. */
  61356. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  61357. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  61358. };
  61359. /**
  61360. * Sets the vertex data of the mesh geometry for the requested `kind`.
  61361. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  61362. * The `data` are either a numeric array either a Float32Array.
  61363. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  61364. * 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).
  61365. * Note that a new underlying VertexBuffer object is created each call.
  61366. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  61367. *
  61368. * Possible `kind` values :
  61369. * - BABYLON.VertexBuffer.PositionKind
  61370. * - BABYLON.VertexBuffer.UVKind
  61371. * - BABYLON.VertexBuffer.UV2Kind
  61372. * - BABYLON.VertexBuffer.UV3Kind
  61373. * - BABYLON.VertexBuffer.UV4Kind
  61374. * - BABYLON.VertexBuffer.UV5Kind
  61375. * - BABYLON.VertexBuffer.UV6Kind
  61376. * - BABYLON.VertexBuffer.ColorKind
  61377. * - BABYLON.VertexBuffer.MatricesIndicesKind
  61378. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  61379. * - BABYLON.VertexBuffer.MatricesWeightsKind
  61380. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  61381. *
  61382. * Returns the Mesh.
  61383. */
  61384. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  61385. if (this.sourceMesh) {
  61386. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  61387. }
  61388. return this.sourceMesh;
  61389. };
  61390. /**
  61391. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  61392. * If the mesh has no geometry, it is simply returned as it is.
  61393. * The `data` are either a numeric array either a Float32Array.
  61394. * No new underlying VertexBuffer object is created.
  61395. * 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.
  61396. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  61397. *
  61398. * Possible `kind` values :
  61399. * - BABYLON.VertexBuffer.PositionKind
  61400. * - BABYLON.VertexBuffer.UVKind
  61401. * - BABYLON.VertexBuffer.UV2Kind
  61402. * - BABYLON.VertexBuffer.UV3Kind
  61403. * - BABYLON.VertexBuffer.UV4Kind
  61404. * - BABYLON.VertexBuffer.UV5Kind
  61405. * - BABYLON.VertexBuffer.UV6Kind
  61406. * - BABYLON.VertexBuffer.ColorKind
  61407. * - BABYLON.VertexBuffer.MatricesIndicesKind
  61408. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  61409. * - BABYLON.VertexBuffer.MatricesWeightsKind
  61410. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  61411. *
  61412. * Returns the Mesh.
  61413. */
  61414. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  61415. if (this.sourceMesh) {
  61416. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  61417. }
  61418. return this.sourceMesh;
  61419. };
  61420. /**
  61421. * Sets the mesh indices.
  61422. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  61423. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  61424. * This method creates a new index buffer each call.
  61425. * Returns the Mesh.
  61426. */
  61427. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  61428. if (totalVertices === void 0) { totalVertices = null; }
  61429. if (this.sourceMesh) {
  61430. this.sourceMesh.setIndices(indices, totalVertices);
  61431. }
  61432. return this.sourceMesh;
  61433. };
  61434. /**
  61435. * Boolean : True if the mesh owns the requested kind of data.
  61436. */
  61437. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  61438. return this._sourceMesh.isVerticesDataPresent(kind);
  61439. };
  61440. /**
  61441. * Returns an array of indices (IndicesArray).
  61442. */
  61443. InstancedMesh.prototype.getIndices = function () {
  61444. return this._sourceMesh.getIndices();
  61445. };
  61446. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  61447. get: function () {
  61448. return this._sourceMesh._positions;
  61449. },
  61450. enumerable: true,
  61451. configurable: true
  61452. });
  61453. /**
  61454. * Sets a new updated BoundingInfo to the mesh.
  61455. * Returns the mesh.
  61456. */
  61457. InstancedMesh.prototype.refreshBoundingInfo = function () {
  61458. var meshBB = this._sourceMesh.getBoundingInfo();
  61459. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  61460. this._updateBoundingInfo();
  61461. return this;
  61462. };
  61463. /** @hidden */
  61464. InstancedMesh.prototype._preActivate = function () {
  61465. if (this._currentLOD) {
  61466. this._currentLOD._preActivate();
  61467. }
  61468. return this;
  61469. };
  61470. /** @hidden */
  61471. InstancedMesh.prototype._activate = function (renderId) {
  61472. if (this._currentLOD) {
  61473. this._currentLOD._registerInstanceForRenderId(this, renderId);
  61474. }
  61475. return this;
  61476. };
  61477. /**
  61478. * Returns the current associated LOD AbstractMesh.
  61479. */
  61480. InstancedMesh.prototype.getLOD = function (camera) {
  61481. if (!camera) {
  61482. return this;
  61483. }
  61484. var boundingInfo = this.getBoundingInfo();
  61485. this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere);
  61486. if (this._currentLOD === this.sourceMesh) {
  61487. return this;
  61488. }
  61489. return this._currentLOD;
  61490. };
  61491. /** @hidden */
  61492. InstancedMesh.prototype._syncSubMeshes = function () {
  61493. this.releaseSubMeshes();
  61494. if (this._sourceMesh.subMeshes) {
  61495. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  61496. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  61497. }
  61498. }
  61499. return this;
  61500. };
  61501. /** @hidden */
  61502. InstancedMesh.prototype._generatePointsArray = function () {
  61503. return this._sourceMesh._generatePointsArray();
  61504. };
  61505. /**
  61506. * Creates a new InstancedMesh from the current mesh.
  61507. * - name (string) : the cloned mesh name
  61508. * - newParent (optional Node) : the optional Node to parent the clone to.
  61509. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  61510. *
  61511. * Returns the clone.
  61512. */
  61513. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  61514. var result = this._sourceMesh.createInstance(name);
  61515. // Deep copy
  61516. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  61517. // Bounding info
  61518. this.refreshBoundingInfo();
  61519. // Parent
  61520. if (newParent) {
  61521. result.parent = newParent;
  61522. }
  61523. if (!doNotCloneChildren) {
  61524. // Children
  61525. for (var index = 0; index < this.getScene().meshes.length; index++) {
  61526. var mesh = this.getScene().meshes[index];
  61527. if (mesh.parent === this) {
  61528. mesh.clone(mesh.name, result);
  61529. }
  61530. }
  61531. }
  61532. result.computeWorldMatrix(true);
  61533. return result;
  61534. };
  61535. /**
  61536. * Disposes the InstancedMesh.
  61537. * Returns nothing.
  61538. */
  61539. InstancedMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  61540. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  61541. // Remove from mesh
  61542. var index = this._sourceMesh.instances.indexOf(this);
  61543. this._sourceMesh.instances.splice(index, 1);
  61544. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  61545. };
  61546. return InstancedMesh;
  61547. }(BABYLON.AbstractMesh));
  61548. BABYLON.InstancedMesh = InstancedMesh;
  61549. })(BABYLON || (BABYLON = {}));
  61550. //# sourceMappingURL=babylon.instancedMesh.js.map
  61551. var BABYLON;
  61552. (function (BABYLON) {
  61553. var LinesMesh = /** @class */ (function (_super) {
  61554. __extends(LinesMesh, _super);
  61555. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor, useVertexAlpha) {
  61556. if (scene === void 0) { scene = null; }
  61557. if (parent === void 0) { parent = null; }
  61558. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  61559. _this.useVertexColor = useVertexColor;
  61560. _this.useVertexAlpha = useVertexAlpha;
  61561. _this.color = new BABYLON.Color3(1, 1, 1);
  61562. _this.alpha = 1;
  61563. if (source) {
  61564. _this.color = source.color.clone();
  61565. _this.alpha = source.alpha;
  61566. _this.useVertexColor = source.useVertexColor;
  61567. _this.useVertexAlpha = source.useVertexAlpha;
  61568. }
  61569. _this._intersectionThreshold = 0.1;
  61570. var defines = [];
  61571. var options = {
  61572. attributes: [BABYLON.VertexBuffer.PositionKind],
  61573. uniforms: ["world", "viewProjection"],
  61574. needAlphaBlending: true,
  61575. defines: defines
  61576. };
  61577. if (useVertexAlpha === false) {
  61578. options.needAlphaBlending = false;
  61579. }
  61580. if (!useVertexColor) {
  61581. options.uniforms.push("color");
  61582. }
  61583. else {
  61584. options.defines.push("#define VERTEXCOLOR");
  61585. options.attributes.push(BABYLON.VertexBuffer.ColorKind);
  61586. }
  61587. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", _this.getScene(), "color", options);
  61588. return _this;
  61589. }
  61590. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  61591. /**
  61592. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  61593. * This margin is expressed in world space coordinates, so its value may vary.
  61594. * Default value is 0.1
  61595. * @returns the intersection Threshold value.
  61596. */
  61597. get: function () {
  61598. return this._intersectionThreshold;
  61599. },
  61600. /**
  61601. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  61602. * This margin is expressed in world space coordinates, so its value may vary.
  61603. * @param value the new threshold to apply
  61604. */
  61605. set: function (value) {
  61606. if (this._intersectionThreshold === value) {
  61607. return;
  61608. }
  61609. this._intersectionThreshold = value;
  61610. if (this.geometry) {
  61611. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  61612. }
  61613. },
  61614. enumerable: true,
  61615. configurable: true
  61616. });
  61617. /**
  61618. * Returns the string "LineMesh"
  61619. */
  61620. LinesMesh.prototype.getClassName = function () {
  61621. return "LinesMesh";
  61622. };
  61623. Object.defineProperty(LinesMesh.prototype, "material", {
  61624. /**
  61625. * @hidden
  61626. */
  61627. get: function () {
  61628. return this._colorShader;
  61629. },
  61630. /**
  61631. * @hidden
  61632. */
  61633. set: function (value) {
  61634. // Do nothing
  61635. },
  61636. enumerable: true,
  61637. configurable: true
  61638. });
  61639. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  61640. /**
  61641. * @hidden
  61642. */
  61643. get: function () {
  61644. return false;
  61645. },
  61646. enumerable: true,
  61647. configurable: true
  61648. });
  61649. LinesMesh.prototype.createInstance = function (name) {
  61650. throw new Error("LinesMeshes do not support createInstance.");
  61651. };
  61652. /** @hidden */
  61653. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  61654. if (!this._geometry) {
  61655. return this;
  61656. }
  61657. // VBOs
  61658. this._geometry._bind(this._colorShader.getEffect());
  61659. // Color
  61660. if (!this.useVertexColor) {
  61661. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  61662. }
  61663. return this;
  61664. };
  61665. /** @hidden */
  61666. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  61667. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  61668. return this;
  61669. }
  61670. var engine = this.getScene().getEngine();
  61671. // Draw order
  61672. engine.drawElementsType(BABYLON.Material.LineListDrawMode, subMesh.indexStart, subMesh.indexCount);
  61673. return this;
  61674. };
  61675. LinesMesh.prototype.dispose = function (doNotRecurse) {
  61676. this._colorShader.dispose();
  61677. _super.prototype.dispose.call(this, doNotRecurse);
  61678. };
  61679. /**
  61680. * Returns a new LineMesh object cloned from the current one.
  61681. */
  61682. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  61683. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  61684. };
  61685. return LinesMesh;
  61686. }(BABYLON.Mesh));
  61687. BABYLON.LinesMesh = LinesMesh;
  61688. })(BABYLON || (BABYLON = {}));
  61689. //# sourceMappingURL=babylon.linesMesh.js.map
  61690. var BABYLON;
  61691. (function (BABYLON) {
  61692. /**
  61693. * This class implement a typical dictionary using a string as key and the generic type T as value.
  61694. * The underlying implementation relies on an associative array to ensure the best performances.
  61695. * The value can be anything including 'null' but except 'undefined'
  61696. */
  61697. var StringDictionary = /** @class */ (function () {
  61698. function StringDictionary() {
  61699. this._count = 0;
  61700. this._data = {};
  61701. }
  61702. /**
  61703. * This will clear this dictionary and copy the content from the 'source' one.
  61704. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  61705. * @param source the dictionary to take the content from and copy to this dictionary
  61706. */
  61707. StringDictionary.prototype.copyFrom = function (source) {
  61708. var _this = this;
  61709. this.clear();
  61710. source.forEach(function (t, v) { return _this.add(t, v); });
  61711. };
  61712. /**
  61713. * Get a value based from its key
  61714. * @param key the given key to get the matching value from
  61715. * @return the value if found, otherwise undefined is returned
  61716. */
  61717. StringDictionary.prototype.get = function (key) {
  61718. var val = this._data[key];
  61719. if (val !== undefined) {
  61720. return val;
  61721. }
  61722. return undefined;
  61723. };
  61724. /**
  61725. * Get a value from its key or add it if it doesn't exist.
  61726. * This method will ensure you that a given key/data will be present in the dictionary.
  61727. * @param key the given key to get the matching value from
  61728. * @param factory the factory that will create the value if the key is not present in the dictionary.
  61729. * The factory will only be invoked if there's no data for the given key.
  61730. * @return the value corresponding to the key.
  61731. */
  61732. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  61733. var val = this.get(key);
  61734. if (val !== undefined) {
  61735. return val;
  61736. }
  61737. val = factory(key);
  61738. if (val) {
  61739. this.add(key, val);
  61740. }
  61741. return val;
  61742. };
  61743. /**
  61744. * Get a value from its key if present in the dictionary otherwise add it
  61745. * @param key the key to get the value from
  61746. * @param val if there's no such key/value pair in the dictionary add it with this value
  61747. * @return the value corresponding to the key
  61748. */
  61749. StringDictionary.prototype.getOrAdd = function (key, val) {
  61750. var curVal = this.get(key);
  61751. if (curVal !== undefined) {
  61752. return curVal;
  61753. }
  61754. this.add(key, val);
  61755. return val;
  61756. };
  61757. /**
  61758. * Check if there's a given key in the dictionary
  61759. * @param key the key to check for
  61760. * @return true if the key is present, false otherwise
  61761. */
  61762. StringDictionary.prototype.contains = function (key) {
  61763. return this._data[key] !== undefined;
  61764. };
  61765. /**
  61766. * Add a new key and its corresponding value
  61767. * @param key the key to add
  61768. * @param value the value corresponding to the key
  61769. * @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
  61770. */
  61771. StringDictionary.prototype.add = function (key, value) {
  61772. if (this._data[key] !== undefined) {
  61773. return false;
  61774. }
  61775. this._data[key] = value;
  61776. ++this._count;
  61777. return true;
  61778. };
  61779. StringDictionary.prototype.set = function (key, value) {
  61780. if (this._data[key] === undefined) {
  61781. return false;
  61782. }
  61783. this._data[key] = value;
  61784. return true;
  61785. };
  61786. /**
  61787. * Get the element of the given key and remove it from the dictionary
  61788. * @param key
  61789. */
  61790. StringDictionary.prototype.getAndRemove = function (key) {
  61791. var val = this.get(key);
  61792. if (val !== undefined) {
  61793. delete this._data[key];
  61794. --this._count;
  61795. return val;
  61796. }
  61797. return null;
  61798. };
  61799. /**
  61800. * Remove a key/value from the dictionary.
  61801. * @param key the key to remove
  61802. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  61803. */
  61804. StringDictionary.prototype.remove = function (key) {
  61805. if (this.contains(key)) {
  61806. delete this._data[key];
  61807. --this._count;
  61808. return true;
  61809. }
  61810. return false;
  61811. };
  61812. /**
  61813. * Clear the whole content of the dictionary
  61814. */
  61815. StringDictionary.prototype.clear = function () {
  61816. this._data = {};
  61817. this._count = 0;
  61818. };
  61819. Object.defineProperty(StringDictionary.prototype, "count", {
  61820. get: function () {
  61821. return this._count;
  61822. },
  61823. enumerable: true,
  61824. configurable: true
  61825. });
  61826. /**
  61827. * Execute a callback on each key/val of the dictionary.
  61828. * Note that you can remove any element in this dictionary in the callback implementation
  61829. * @param callback the callback to execute on a given key/value pair
  61830. */
  61831. StringDictionary.prototype.forEach = function (callback) {
  61832. for (var cur in this._data) {
  61833. var val = this._data[cur];
  61834. callback(cur, val);
  61835. }
  61836. };
  61837. /**
  61838. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  61839. * If the callback returns null or undefined the method will iterate to the next key/value pair
  61840. * Note that you can remove any element in this dictionary in the callback implementation
  61841. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  61842. */
  61843. StringDictionary.prototype.first = function (callback) {
  61844. for (var cur in this._data) {
  61845. var val = this._data[cur];
  61846. var res = callback(cur, val);
  61847. if (res) {
  61848. return res;
  61849. }
  61850. }
  61851. return null;
  61852. };
  61853. return StringDictionary;
  61854. }());
  61855. BABYLON.StringDictionary = StringDictionary;
  61856. })(BABYLON || (BABYLON = {}));
  61857. //# sourceMappingURL=babylon.stringDictionary.js.map
  61858. var BABYLON;
  61859. (function (BABYLON) {
  61860. var Debug;
  61861. (function (Debug) {
  61862. /**
  61863. * Class used to render a debug view of a given skeleton
  61864. * @see http://www.babylonjs-playground.com/#1BZJVJ#8
  61865. */
  61866. var SkeletonViewer = /** @class */ (function () {
  61867. /**
  61868. * Creates a new SkeletonViewer
  61869. * @param skeleton defines the skeleton to render
  61870. * @param mesh defines the mesh attached to the skeleton
  61871. * @param scene defines the hosting scene
  61872. * @param autoUpdateBonesMatrices defines a boolean indicating if bones matrices must be forced to update before rendering (true by default)
  61873. * @param renderingGroupId defines the rendering group id to use with the viewer
  61874. */
  61875. function SkeletonViewer(
  61876. /** defines the skeleton to render */
  61877. skeleton,
  61878. /** defines the mesh attached to the skeleton */
  61879. mesh, scene,
  61880. /** defines a boolean indicating if bones matrices must be forced to update before rendering (true by default) */
  61881. autoUpdateBonesMatrices,
  61882. /** defines the rendering group id to use with the viewer */
  61883. renderingGroupId) {
  61884. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  61885. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  61886. this.skeleton = skeleton;
  61887. this.mesh = mesh;
  61888. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  61889. this.renderingGroupId = renderingGroupId;
  61890. /** Gets or sets the color used to render the skeleton */
  61891. this.color = BABYLON.Color3.White();
  61892. this._debugLines = new Array();
  61893. this._isEnabled = false;
  61894. this._scene = scene;
  61895. this.update();
  61896. this._renderFunction = this.update.bind(this);
  61897. }
  61898. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  61899. get: function () {
  61900. return this._isEnabled;
  61901. },
  61902. /** Gets or sets a boolean indicating if the viewer is enabled */
  61903. set: function (value) {
  61904. if (this._isEnabled === value) {
  61905. return;
  61906. }
  61907. this._isEnabled = value;
  61908. if (value) {
  61909. this._scene.registerBeforeRender(this._renderFunction);
  61910. }
  61911. else {
  61912. this._scene.unregisterBeforeRender(this._renderFunction);
  61913. }
  61914. },
  61915. enumerable: true,
  61916. configurable: true
  61917. });
  61918. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  61919. if (x === void 0) { x = 0; }
  61920. if (y === void 0) { y = 0; }
  61921. if (z === void 0) { z = 0; }
  61922. var tmat = BABYLON.Tmp.Matrix[0];
  61923. var parentBone = bone.getParent();
  61924. tmat.copyFrom(bone.getLocalMatrix());
  61925. if (x !== 0 || y !== 0 || z !== 0) {
  61926. var tmat2 = BABYLON.Tmp.Matrix[1];
  61927. BABYLON.Matrix.IdentityToRef(tmat2);
  61928. tmat2.m[12] = x;
  61929. tmat2.m[13] = y;
  61930. tmat2.m[14] = z;
  61931. tmat2.multiplyToRef(tmat, tmat);
  61932. }
  61933. if (parentBone) {
  61934. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  61935. }
  61936. tmat.multiplyToRef(meshMat, tmat);
  61937. position.x = tmat.m[12];
  61938. position.y = tmat.m[13];
  61939. position.z = tmat.m[14];
  61940. };
  61941. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  61942. var len = bones.length;
  61943. var meshPos = this.mesh.position;
  61944. for (var i = 0; i < len; i++) {
  61945. var bone = bones[i];
  61946. var points = this._debugLines[i];
  61947. if (!points) {
  61948. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  61949. this._debugLines[i] = points;
  61950. }
  61951. this._getBonePosition(points[0], bone, meshMat);
  61952. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  61953. points[0].subtractInPlace(meshPos);
  61954. points[1].subtractInPlace(meshPos);
  61955. }
  61956. };
  61957. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  61958. var len = bones.length;
  61959. var boneNum = 0;
  61960. var meshPos = this.mesh.position;
  61961. for (var i = len - 1; i >= 0; i--) {
  61962. var childBone = bones[i];
  61963. var parentBone = childBone.getParent();
  61964. if (!parentBone) {
  61965. continue;
  61966. }
  61967. var points = this._debugLines[boneNum];
  61968. if (!points) {
  61969. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  61970. this._debugLines[boneNum] = points;
  61971. }
  61972. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  61973. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  61974. points[0].subtractInPlace(meshPos);
  61975. points[1].subtractInPlace(meshPos);
  61976. boneNum++;
  61977. }
  61978. };
  61979. /** Update the viewer to sync with current skeleton state */
  61980. SkeletonViewer.prototype.update = function () {
  61981. if (this.autoUpdateBonesMatrices) {
  61982. this.skeleton.computeAbsoluteTransforms();
  61983. }
  61984. if (this.skeleton.bones[0].length === undefined) {
  61985. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  61986. }
  61987. else {
  61988. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  61989. }
  61990. if (!this._debugMesh) {
  61991. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, this._scene);
  61992. this._debugMesh.renderingGroupId = this.renderingGroupId;
  61993. }
  61994. else {
  61995. BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  61996. }
  61997. this._debugMesh.position.copyFrom(this.mesh.position);
  61998. this._debugMesh.color = this.color;
  61999. };
  62000. /** Release associated resources */
  62001. SkeletonViewer.prototype.dispose = function () {
  62002. if (this._debugMesh) {
  62003. this.isEnabled = false;
  62004. this._debugMesh.dispose();
  62005. this._debugMesh = null;
  62006. }
  62007. };
  62008. return SkeletonViewer;
  62009. }());
  62010. Debug.SkeletonViewer = SkeletonViewer;
  62011. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  62012. })(BABYLON || (BABYLON = {}));
  62013. //# sourceMappingURL=babylon.skeletonViewer.js.map
  62014. /**
  62015. * Module Debug contains the (visual) components to debug a scene correctly
  62016. */
  62017. var BABYLON;
  62018. (function (BABYLON) {
  62019. var Debug;
  62020. (function (Debug) {
  62021. /**
  62022. * The Axes viewer will show 3 axes in a specific point in space
  62023. */
  62024. var AxesViewer = /** @class */ (function () {
  62025. /**
  62026. * Creates a new AxesViewer
  62027. * @param scene defines the hosting scene
  62028. * @param scaleLines defines a number used to scale line length (1 by default)
  62029. */
  62030. function AxesViewer(scene, scaleLines) {
  62031. if (scaleLines === void 0) { scaleLines = 1; }
  62032. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  62033. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  62034. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  62035. /**
  62036. * Gets or sets a number used to scale line length
  62037. */
  62038. this.scaleLines = 1;
  62039. this.scaleLines = scaleLines;
  62040. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  62041. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  62042. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  62043. this._xmesh.renderingGroupId = 2;
  62044. this._ymesh.renderingGroupId = 2;
  62045. this._zmesh.renderingGroupId = 2;
  62046. this._xmesh.material.checkReadyOnlyOnce = true;
  62047. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  62048. this._ymesh.material.checkReadyOnlyOnce = true;
  62049. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  62050. this._zmesh.material.checkReadyOnlyOnce = true;
  62051. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  62052. this.scene = scene;
  62053. }
  62054. /**
  62055. * Force the viewer to update
  62056. * @param position defines the position of the viewer
  62057. * @param xaxis defines the x axis of the viewer
  62058. * @param yaxis defines the y axis of the viewer
  62059. * @param zaxis defines the z axis of the viewer
  62060. */
  62061. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  62062. var scaleLines = this.scaleLines;
  62063. if (this._xmesh) {
  62064. this._xmesh.position.copyFrom(position);
  62065. }
  62066. if (this._ymesh) {
  62067. this._ymesh.position.copyFrom(position);
  62068. }
  62069. if (this._zmesh) {
  62070. this._zmesh.position.copyFrom(position);
  62071. }
  62072. var point2 = this._xline[1];
  62073. point2.x = xaxis.x * scaleLines;
  62074. point2.y = xaxis.y * scaleLines;
  62075. point2.z = xaxis.z * scaleLines;
  62076. BABYLON.Mesh.CreateLines("", this._xline, null, false, this._xmesh);
  62077. point2 = this._yline[1];
  62078. point2.x = yaxis.x * scaleLines;
  62079. point2.y = yaxis.y * scaleLines;
  62080. point2.z = yaxis.z * scaleLines;
  62081. BABYLON.Mesh.CreateLines("", this._yline, null, false, this._ymesh);
  62082. point2 = this._zline[1];
  62083. point2.x = zaxis.x * scaleLines;
  62084. point2.y = zaxis.y * scaleLines;
  62085. point2.z = zaxis.z * scaleLines;
  62086. BABYLON.Mesh.CreateLines("", this._zline, null, false, this._zmesh);
  62087. };
  62088. /** Releases resources */
  62089. AxesViewer.prototype.dispose = function () {
  62090. if (this._xmesh) {
  62091. this._xmesh.dispose();
  62092. }
  62093. if (this._ymesh) {
  62094. this._ymesh.dispose();
  62095. }
  62096. if (this._zmesh) {
  62097. this._zmesh.dispose();
  62098. }
  62099. this._xmesh = null;
  62100. this._ymesh = null;
  62101. this._zmesh = null;
  62102. this.scene = null;
  62103. };
  62104. return AxesViewer;
  62105. }());
  62106. Debug.AxesViewer = AxesViewer;
  62107. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  62108. })(BABYLON || (BABYLON = {}));
  62109. //# sourceMappingURL=babylon.axesViewer.js.map
  62110. var BABYLON;
  62111. (function (BABYLON) {
  62112. var Debug;
  62113. (function (Debug) {
  62114. /**
  62115. * The BoneAxesViewer will attach 3 axes to a specific bone of a specific mesh
  62116. * @see demo here: https://www.babylonjs-playground.com/#0DE8F4#8
  62117. */
  62118. var BoneAxesViewer = /** @class */ (function (_super) {
  62119. __extends(BoneAxesViewer, _super);
  62120. /**
  62121. * Creates a new BoneAxesViewer
  62122. * @param scene defines the hosting scene
  62123. * @param bone defines the target bone
  62124. * @param mesh defines the target mesh
  62125. * @param scaleLines defines a scaling factor for line length (1 by default)
  62126. */
  62127. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  62128. if (scaleLines === void 0) { scaleLines = 1; }
  62129. var _this = _super.call(this, scene, scaleLines) || this;
  62130. /** Gets current position */
  62131. _this.pos = BABYLON.Vector3.Zero();
  62132. /** Gets direction of X axis */
  62133. _this.xaxis = BABYLON.Vector3.Zero();
  62134. /** Gets direction of Y axis */
  62135. _this.yaxis = BABYLON.Vector3.Zero();
  62136. /** Gets direction of Z axis */
  62137. _this.zaxis = BABYLON.Vector3.Zero();
  62138. _this.mesh = mesh;
  62139. _this.bone = bone;
  62140. return _this;
  62141. }
  62142. /**
  62143. * Force the viewer to update
  62144. */
  62145. BoneAxesViewer.prototype.update = function () {
  62146. if (!this.mesh || !this.bone) {
  62147. return;
  62148. }
  62149. var bone = this.bone;
  62150. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  62151. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  62152. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  62153. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  62154. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  62155. };
  62156. /** Releases resources */
  62157. BoneAxesViewer.prototype.dispose = function () {
  62158. if (this.mesh) {
  62159. this.mesh = null;
  62160. this.bone = null;
  62161. _super.prototype.dispose.call(this);
  62162. }
  62163. };
  62164. return BoneAxesViewer;
  62165. }(Debug.AxesViewer));
  62166. Debug.BoneAxesViewer = BoneAxesViewer;
  62167. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  62168. })(BABYLON || (BABYLON = {}));
  62169. //# sourceMappingURL=babylon.boneAxesViewer.js.map
  62170. var BABYLON;
  62171. (function (BABYLON) {
  62172. var RayHelper = /** @class */ (function () {
  62173. function RayHelper(ray) {
  62174. this.ray = ray;
  62175. }
  62176. RayHelper.CreateAndShow = function (ray, scene, color) {
  62177. var helper = new RayHelper(ray);
  62178. helper.show(scene, color);
  62179. return helper;
  62180. };
  62181. RayHelper.prototype.show = function (scene, color) {
  62182. if (!this._renderFunction && this.ray) {
  62183. var ray = this.ray;
  62184. this._renderFunction = this._render.bind(this);
  62185. this._scene = scene;
  62186. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  62187. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  62188. if (this._renderFunction) {
  62189. this._scene.registerBeforeRender(this._renderFunction);
  62190. }
  62191. }
  62192. if (color && this._renderLine) {
  62193. this._renderLine.color.copyFrom(color);
  62194. }
  62195. };
  62196. RayHelper.prototype.hide = function () {
  62197. if (this._renderFunction && this._scene) {
  62198. this._scene.unregisterBeforeRender(this._renderFunction);
  62199. this._scene = null;
  62200. this._renderFunction = null;
  62201. if (this._renderLine) {
  62202. this._renderLine.dispose();
  62203. this._renderLine = null;
  62204. }
  62205. this._renderPoints = [];
  62206. }
  62207. };
  62208. RayHelper.prototype._render = function () {
  62209. var ray = this.ray;
  62210. if (!ray) {
  62211. return;
  62212. }
  62213. var point = this._renderPoints[1];
  62214. var len = Math.min(ray.length, 1000000);
  62215. point.copyFrom(ray.direction);
  62216. point.scaleInPlace(len);
  62217. point.addInPlace(ray.origin);
  62218. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  62219. };
  62220. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  62221. this._attachedToMesh = mesh;
  62222. var ray = this.ray;
  62223. if (!ray) {
  62224. return;
  62225. }
  62226. if (!ray.direction) {
  62227. ray.direction = BABYLON.Vector3.Zero();
  62228. }
  62229. if (!ray.origin) {
  62230. ray.origin = BABYLON.Vector3.Zero();
  62231. }
  62232. if (length) {
  62233. ray.length = length;
  62234. }
  62235. if (!meshSpaceOrigin) {
  62236. meshSpaceOrigin = BABYLON.Vector3.Zero();
  62237. }
  62238. if (!meshSpaceDirection) {
  62239. // -1 so that this will work with Mesh.lookAt
  62240. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  62241. }
  62242. if (!this._meshSpaceDirection) {
  62243. this._meshSpaceDirection = meshSpaceDirection.clone();
  62244. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  62245. }
  62246. else {
  62247. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  62248. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  62249. }
  62250. if (!this._updateToMeshFunction) {
  62251. this._updateToMeshFunction = this._updateToMesh.bind(this);
  62252. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  62253. }
  62254. this._updateToMesh();
  62255. };
  62256. RayHelper.prototype.detachFromMesh = function () {
  62257. if (this._attachedToMesh) {
  62258. if (this._updateToMeshFunction) {
  62259. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  62260. }
  62261. this._attachedToMesh = null;
  62262. this._updateToMeshFunction = null;
  62263. }
  62264. };
  62265. RayHelper.prototype._updateToMesh = function () {
  62266. var ray = this.ray;
  62267. if (!this._attachedToMesh || !ray) {
  62268. return;
  62269. }
  62270. if (this._attachedToMesh._isDisposed) {
  62271. this.detachFromMesh();
  62272. return;
  62273. }
  62274. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  62275. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  62276. };
  62277. RayHelper.prototype.dispose = function () {
  62278. this.hide();
  62279. this.detachFromMesh();
  62280. this.ray = null;
  62281. };
  62282. return RayHelper;
  62283. }());
  62284. BABYLON.RayHelper = RayHelper;
  62285. })(BABYLON || (BABYLON = {}));
  62286. //# sourceMappingURL=babylon.rayHelper.js.map
  62287. var BABYLON;
  62288. (function (BABYLON) {
  62289. Object.defineProperty(BABYLON.Scene.prototype, "debugLayer", {
  62290. get: function () {
  62291. if (!this._debugLayer) {
  62292. this._debugLayer = new DebugLayer(this);
  62293. }
  62294. return this._debugLayer;
  62295. },
  62296. enumerable: true,
  62297. configurable: true
  62298. });
  62299. var DebugLayer = /** @class */ (function () {
  62300. function DebugLayer(scene) {
  62301. var _this = this;
  62302. this.BJSINSPECTOR = typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  62303. this.onPropertyChangedObservable = new BABYLON.Observable();
  62304. this._scene = scene;
  62305. this._scene.onDisposeObservable.add(function () {
  62306. // Debug layer
  62307. if (_this._scene._debugLayer) {
  62308. _this._scene._debugLayer.hide();
  62309. }
  62310. });
  62311. }
  62312. /** Creates the inspector window. */
  62313. DebugLayer.prototype._createInspector = function (config) {
  62314. if (config === void 0) { config = {}; }
  62315. var popup = config.popup || false;
  62316. var initialTab = config.initialTab || 0;
  62317. var parentElement = config.parentElement || null;
  62318. if (!this._inspector) {
  62319. this.BJSINSPECTOR = this.BJSINSPECTOR || typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  62320. this._inspector = new this.BJSINSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  62321. } // else nothing to do as instance is already created
  62322. };
  62323. DebugLayer.prototype.isVisible = function () {
  62324. if (!this._inspector) {
  62325. return false;
  62326. }
  62327. return true;
  62328. };
  62329. DebugLayer.prototype.hide = function () {
  62330. if (this._inspector) {
  62331. try {
  62332. this._inspector.dispose();
  62333. }
  62334. catch (e) {
  62335. // If the inspector has been removed directly from the inspector tool
  62336. }
  62337. this.onPropertyChangedObservable.clear();
  62338. this._inspector = null;
  62339. }
  62340. };
  62341. /**
  62342. *
  62343. * Launch the debugLayer.
  62344. *
  62345. * initialTab:
  62346. * | Value | Tab Name |
  62347. * | --- | --- |
  62348. * | 0 | Scene |
  62349. * | 1 | Console |
  62350. * | 2 | Stats |
  62351. * | 3 | Textures |
  62352. * | 4 | Mesh |
  62353. * | 5 | Light |
  62354. * | 6 | Material |
  62355. * | 7 | GLTF |
  62356. * | 8 | GUI |
  62357. * | 9 | Physics |
  62358. * | 10 | Camera |
  62359. * | 11 | Audio |
  62360. *
  62361. */
  62362. DebugLayer.prototype.show = function (config) {
  62363. if (config === void 0) { config = {}; }
  62364. if (typeof this.BJSINSPECTOR == 'undefined') {
  62365. // Load inspector and add it to the DOM
  62366. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  62367. }
  62368. else {
  62369. // Otherwise creates the inspector
  62370. this._createInspector(config);
  62371. }
  62372. };
  62373. /**
  62374. * Gets the active tab
  62375. * @return the index of the active tab or -1 if the inspector is hidden
  62376. */
  62377. DebugLayer.prototype.getActiveTab = function () {
  62378. return this._inspector ? this._inspector.getActiveTabIndex() : -1;
  62379. };
  62380. DebugLayer.InspectorURL = 'https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  62381. return DebugLayer;
  62382. }());
  62383. BABYLON.DebugLayer = DebugLayer;
  62384. })(BABYLON || (BABYLON = {}));
  62385. //# sourceMappingURL=babylon.debugLayer.js.map
  62386. var BABYLON;
  62387. (function (BABYLON) {
  62388. var Debug;
  62389. (function (Debug) {
  62390. /**
  62391. * Used to show the physics impostor around the specific mesh
  62392. */
  62393. var PhysicsViewer = /** @class */ (function () {
  62394. /**
  62395. * Creates a new PhysicsViewer
  62396. * @param scene defines the hosting scene
  62397. */
  62398. function PhysicsViewer(scene) {
  62399. /** @hidden */
  62400. this._impostors = [];
  62401. /** @hidden */
  62402. this._meshes = [];
  62403. /** @hidden */
  62404. this._numMeshes = 0;
  62405. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  62406. var physicEngine = this._scene.getPhysicsEngine();
  62407. if (physicEngine) {
  62408. this._physicsEnginePlugin = physicEngine.getPhysicsPlugin();
  62409. }
  62410. }
  62411. /** @hidden */
  62412. PhysicsViewer.prototype._updateDebugMeshes = function () {
  62413. var plugin = this._physicsEnginePlugin;
  62414. for (var i = 0; i < this._numMeshes; i++) {
  62415. var impostor = this._impostors[i];
  62416. if (!impostor) {
  62417. continue;
  62418. }
  62419. if (impostor.isDisposed) {
  62420. this.hideImpostor(this._impostors[i--]);
  62421. }
  62422. else {
  62423. var mesh = this._meshes[i];
  62424. if (mesh && plugin) {
  62425. plugin.syncMeshWithImpostor(mesh, impostor);
  62426. }
  62427. }
  62428. }
  62429. };
  62430. /**
  62431. * Renders a specified physic impostor
  62432. * @param impostor defines the impostor to render
  62433. */
  62434. PhysicsViewer.prototype.showImpostor = function (impostor) {
  62435. if (!this._scene) {
  62436. return;
  62437. }
  62438. for (var i = 0; i < this._numMeshes; i++) {
  62439. if (this._impostors[i] == impostor) {
  62440. return;
  62441. }
  62442. }
  62443. var debugMesh = this._getDebugMesh(impostor, this._scene);
  62444. if (debugMesh) {
  62445. this._impostors[this._numMeshes] = impostor;
  62446. this._meshes[this._numMeshes] = debugMesh;
  62447. if (this._numMeshes === 0) {
  62448. this._renderFunction = this._updateDebugMeshes.bind(this);
  62449. this._scene.registerBeforeRender(this._renderFunction);
  62450. }
  62451. this._numMeshes++;
  62452. }
  62453. };
  62454. /**
  62455. * Hides a specified physic impostor
  62456. * @param impostor defines the impostor to hide
  62457. */
  62458. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  62459. if (!impostor || !this._scene) {
  62460. return;
  62461. }
  62462. var removed = false;
  62463. for (var i = 0; i < this._numMeshes; i++) {
  62464. if (this._impostors[i] == impostor) {
  62465. var mesh = this._meshes[i];
  62466. if (!mesh) {
  62467. continue;
  62468. }
  62469. this._scene.removeMesh(mesh);
  62470. mesh.dispose();
  62471. this._numMeshes--;
  62472. if (this._numMeshes > 0) {
  62473. this._meshes[i] = this._meshes[this._numMeshes];
  62474. this._impostors[i] = this._impostors[this._numMeshes];
  62475. this._meshes[this._numMeshes] = null;
  62476. this._impostors[this._numMeshes] = null;
  62477. }
  62478. else {
  62479. this._meshes[0] = null;
  62480. this._impostors[0] = null;
  62481. }
  62482. removed = true;
  62483. break;
  62484. }
  62485. }
  62486. if (removed && this._numMeshes === 0) {
  62487. this._scene.unregisterBeforeRender(this._renderFunction);
  62488. }
  62489. };
  62490. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  62491. if (!this._debugMaterial) {
  62492. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  62493. this._debugMaterial.wireframe = true;
  62494. }
  62495. return this._debugMaterial;
  62496. };
  62497. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  62498. if (!this._debugBoxMesh) {
  62499. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  62500. this._debugBoxMesh.renderingGroupId = 1;
  62501. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  62502. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  62503. scene.removeMesh(this._debugBoxMesh);
  62504. }
  62505. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  62506. };
  62507. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  62508. if (!this._debugSphereMesh) {
  62509. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  62510. this._debugSphereMesh.renderingGroupId = 1;
  62511. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  62512. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  62513. scene.removeMesh(this._debugSphereMesh);
  62514. }
  62515. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  62516. };
  62517. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  62518. var mesh = null;
  62519. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  62520. mesh = this._getDebugBoxMesh(scene);
  62521. impostor.getBoxSizeToRef(mesh.scaling);
  62522. }
  62523. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  62524. mesh = this._getDebugSphereMesh(scene);
  62525. var radius = impostor.getRadius();
  62526. mesh.scaling.x = radius * 2;
  62527. mesh.scaling.y = radius * 2;
  62528. mesh.scaling.z = radius * 2;
  62529. }
  62530. return mesh;
  62531. };
  62532. /** Releases all resources */
  62533. PhysicsViewer.prototype.dispose = function () {
  62534. for (var i = 0; i < this._numMeshes; i++) {
  62535. this.hideImpostor(this._impostors[i]);
  62536. }
  62537. if (this._debugBoxMesh) {
  62538. this._debugBoxMesh.dispose();
  62539. }
  62540. if (this._debugSphereMesh) {
  62541. this._debugSphereMesh.dispose();
  62542. }
  62543. if (this._debugMaterial) {
  62544. this._debugMaterial.dispose();
  62545. }
  62546. this._impostors.length = 0;
  62547. this._scene = null;
  62548. this._physicsEnginePlugin = null;
  62549. };
  62550. return PhysicsViewer;
  62551. }());
  62552. Debug.PhysicsViewer = PhysicsViewer;
  62553. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  62554. })(BABYLON || (BABYLON = {}));
  62555. //# sourceMappingURL=babylon.physicsViewer.js.map
  62556. var BABYLON;
  62557. (function (BABYLON) {
  62558. Object.defineProperty(BABYLON.Scene.prototype, "forceShowBoundingBoxes", {
  62559. get: function () {
  62560. return this._forceShowBoundingBoxes || false;
  62561. },
  62562. set: function (value) {
  62563. this._forceShowBoundingBoxes = value;
  62564. // Lazyly creates a BB renderer if needed.
  62565. if (value) {
  62566. this.getBoundingBoxRenderer();
  62567. }
  62568. },
  62569. enumerable: true,
  62570. configurable: true
  62571. });
  62572. BABYLON.Scene.prototype.getBoundingBoxRenderer = function () {
  62573. if (!this._boundingBoxRenderer) {
  62574. this._boundingBoxRenderer = new BoundingBoxRenderer(this);
  62575. }
  62576. return this._boundingBoxRenderer;
  62577. };
  62578. Object.defineProperty(BABYLON.AbstractMesh.prototype, "showBoundingBox", {
  62579. get: function () {
  62580. return this._showBoundingBox || false;
  62581. },
  62582. set: function (value) {
  62583. this._showBoundingBox = value;
  62584. // Lazyly creates a BB renderer if needed.
  62585. if (value) {
  62586. this.getScene().getBoundingBoxRenderer();
  62587. }
  62588. },
  62589. enumerable: true,
  62590. configurable: true
  62591. });
  62592. /**
  62593. * Component responsible of rendering the bounding box of the meshes in a scene.
  62594. * This is usually used through the mesh.showBoundingBox or the scene.forceShowBoundingBoxes properties
  62595. *
  62596. */
  62597. var BoundingBoxRenderer = /** @class */ (function () {
  62598. /**
  62599. * Instantiates a new bounding box renderer in a scene.
  62600. * @param scene the scene the renderer renders in
  62601. */
  62602. function BoundingBoxRenderer(scene) {
  62603. /**
  62604. * The component name helpfull to identify the component in the list of scene components.
  62605. */
  62606. this.name = BABYLON.SceneComponentConstants.NAME_BOUNDINGBOXRENDERER;
  62607. /**
  62608. * Color of the bounding box lines placed in front of an object
  62609. */
  62610. this.frontColor = new BABYLON.Color3(1, 1, 1);
  62611. /**
  62612. * Color of the bounding box lines placed behind an object
  62613. */
  62614. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  62615. /**
  62616. * Defines if the renderer should show the back lines or not
  62617. */
  62618. this.showBackLines = true;
  62619. /**
  62620. * @hidden
  62621. */
  62622. this.renderList = new BABYLON.SmartArray(32);
  62623. this._vertexBuffers = {};
  62624. this.scene = scene;
  62625. scene._addComponent(this);
  62626. }
  62627. /**
  62628. * Registers the component in a given scene
  62629. */
  62630. BoundingBoxRenderer.prototype.register = function () {
  62631. this.scene._beforeEvaluateActiveMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFOREEVALUATEACTIVEMESH_BOUNDINGBOXRENDERER, this, this.reset);
  62632. this.scene._activeMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_ACTIVEMESH_BOUNDINGBOXRENDERER, this, this._activeMesh);
  62633. this.scene._evaluateSubMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_EVALUATESUBMESH_BOUNDINGBOXRENDERER, this, this._evaluateSubMesh);
  62634. this.scene._afterRenderingGroupDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERRENDERINGGROUPDRAW_BOUNDINGBOXRENDERER, this, this.render);
  62635. };
  62636. BoundingBoxRenderer.prototype._evaluateSubMesh = function (mesh, subMesh) {
  62637. if (mesh.showSubMeshesBoundingBox) {
  62638. var boundingInfo = subMesh.getBoundingInfo();
  62639. if (boundingInfo !== null && boundingInfo !== undefined) {
  62640. boundingInfo.boundingBox._tag = mesh.renderingGroupId;
  62641. this.renderList.push(boundingInfo.boundingBox);
  62642. }
  62643. }
  62644. };
  62645. BoundingBoxRenderer.prototype._activeMesh = function (sourceMesh, mesh) {
  62646. if (sourceMesh.showBoundingBox || this.scene.forceShowBoundingBoxes) {
  62647. var boundingInfo = sourceMesh.getBoundingInfo();
  62648. boundingInfo.boundingBox._tag = mesh.renderingGroupId;
  62649. this.renderList.push(boundingInfo.boundingBox);
  62650. }
  62651. };
  62652. BoundingBoxRenderer.prototype._prepareRessources = function () {
  62653. if (this._colorShader) {
  62654. return;
  62655. }
  62656. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this.scene, "color", {
  62657. attributes: [BABYLON.VertexBuffer.PositionKind],
  62658. uniforms: ["world", "viewProjection", "color"]
  62659. });
  62660. var engine = this.scene.getEngine();
  62661. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  62662. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  62663. this._createIndexBuffer();
  62664. };
  62665. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  62666. var engine = this.scene.getEngine();
  62667. 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]);
  62668. };
  62669. /**
  62670. * Rebuilds the elements related to this component in case of
  62671. * context lost for instance.
  62672. */
  62673. BoundingBoxRenderer.prototype.rebuild = function () {
  62674. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  62675. if (vb) {
  62676. vb._rebuild();
  62677. }
  62678. this._createIndexBuffer();
  62679. };
  62680. /**
  62681. * @hidden
  62682. */
  62683. BoundingBoxRenderer.prototype.reset = function () {
  62684. this.renderList.reset();
  62685. };
  62686. /**
  62687. * Render the bounding boxes of a specific rendering group
  62688. * @param renderingGroupId defines the rendering group to render
  62689. */
  62690. BoundingBoxRenderer.prototype.render = function (renderingGroupId) {
  62691. if (this.renderList.length === 0) {
  62692. return;
  62693. }
  62694. this._prepareRessources();
  62695. if (!this._colorShader.isReady()) {
  62696. return;
  62697. }
  62698. var engine = this.scene.getEngine();
  62699. engine.setDepthWrite(false);
  62700. this._colorShader._preBind();
  62701. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  62702. var boundingBox = this.renderList.data[boundingBoxIndex];
  62703. if (boundingBox._tag !== renderingGroupId) {
  62704. continue;
  62705. }
  62706. var min = boundingBox.minimum;
  62707. var max = boundingBox.maximum;
  62708. var diff = max.subtract(min);
  62709. var median = min.add(diff.scale(0.5));
  62710. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  62711. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  62712. .multiply(boundingBox.getWorldMatrix());
  62713. // VBOs
  62714. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  62715. if (this.showBackLines) {
  62716. // Back
  62717. engine.setDepthFunctionToGreaterOrEqual();
  62718. this.scene.resetCachedMaterial();
  62719. this._colorShader.setColor4("color", this.backColor.toColor4());
  62720. this._colorShader.bind(worldMatrix);
  62721. // Draw order
  62722. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  62723. }
  62724. // Front
  62725. engine.setDepthFunctionToLess();
  62726. this.scene.resetCachedMaterial();
  62727. this._colorShader.setColor4("color", this.frontColor.toColor4());
  62728. this._colorShader.bind(worldMatrix);
  62729. // Draw order
  62730. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  62731. }
  62732. this._colorShader.unbind();
  62733. engine.setDepthFunctionToLessOrEqual();
  62734. engine.setDepthWrite(true);
  62735. };
  62736. /**
  62737. * In case of occlusion queries, we can render the occlusion bounding box through this method
  62738. * @param mesh Define the mesh to render the occlusion bounding box for
  62739. */
  62740. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  62741. this._prepareRessources();
  62742. if (!this._colorShader.isReady() || !mesh._boundingInfo) {
  62743. return;
  62744. }
  62745. var engine = this.scene.getEngine();
  62746. engine.setDepthWrite(false);
  62747. engine.setColorWrite(false);
  62748. this._colorShader._preBind();
  62749. var boundingBox = mesh._boundingInfo.boundingBox;
  62750. var min = boundingBox.minimum;
  62751. var max = boundingBox.maximum;
  62752. var diff = max.subtract(min);
  62753. var median = min.add(diff.scale(0.5));
  62754. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  62755. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  62756. .multiply(boundingBox.getWorldMatrix());
  62757. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  62758. engine.setDepthFunctionToLess();
  62759. this.scene.resetCachedMaterial();
  62760. this._colorShader.bind(worldMatrix);
  62761. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  62762. this._colorShader.unbind();
  62763. engine.setDepthFunctionToLessOrEqual();
  62764. engine.setDepthWrite(true);
  62765. engine.setColorWrite(true);
  62766. };
  62767. /**
  62768. * Dispose and release the resources attached to this renderer.
  62769. */
  62770. BoundingBoxRenderer.prototype.dispose = function () {
  62771. if (!this._colorShader) {
  62772. return;
  62773. }
  62774. this.renderList.dispose();
  62775. this._colorShader.dispose();
  62776. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  62777. if (buffer) {
  62778. buffer.dispose();
  62779. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  62780. }
  62781. this.scene.getEngine()._releaseBuffer(this._indexBuffer);
  62782. };
  62783. return BoundingBoxRenderer;
  62784. }());
  62785. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  62786. })(BABYLON || (BABYLON = {}));
  62787. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  62788. var BABYLON;
  62789. (function (BABYLON) {
  62790. BABYLON.Engine.prototype.createTransformFeedback = function () {
  62791. return this._gl.createTransformFeedback();
  62792. };
  62793. BABYLON.Engine.prototype.deleteTransformFeedback = function (value) {
  62794. this._gl.deleteTransformFeedback(value);
  62795. };
  62796. BABYLON.Engine.prototype.bindTransformFeedback = function (value) {
  62797. this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value);
  62798. };
  62799. BABYLON.Engine.prototype.beginTransformFeedback = function (usePoints) {
  62800. if (usePoints === void 0) { usePoints = true; }
  62801. this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES);
  62802. };
  62803. BABYLON.Engine.prototype.endTransformFeedback = function () {
  62804. this._gl.endTransformFeedback();
  62805. };
  62806. BABYLON.Engine.prototype.setTranformFeedbackVaryings = function (program, value) {
  62807. this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS);
  62808. };
  62809. BABYLON.Engine.prototype.bindTransformFeedbackBuffer = function (value) {
  62810. this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value);
  62811. };
  62812. })(BABYLON || (BABYLON = {}));
  62813. //# sourceMappingURL=babylon.engine.transformFeedback.js.map
  62814. var BABYLON;
  62815. (function (BABYLON) {
  62816. /**
  62817. * This represents a GPU particle system in Babylon
  62818. * This is the fastest particle system in Babylon as it uses the GPU to update the individual particle data
  62819. * @see https://www.babylonjs-playground.com/#PU4WYI#4
  62820. */
  62821. var GPUParticleSystem = /** @class */ (function (_super) {
  62822. __extends(GPUParticleSystem, _super);
  62823. /**
  62824. * Instantiates a GPU particle system.
  62825. * 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.
  62826. * @param name The name of the particle system
  62827. * @param options The options used to create the system
  62828. * @param scene The scene the particle system belongs to
  62829. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  62830. */
  62831. function GPUParticleSystem(name, options, scene, isAnimationSheetEnabled) {
  62832. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  62833. var _this = _super.call(this, name) || this;
  62834. /**
  62835. * The layer mask we are rendering the particles through.
  62836. */
  62837. _this.layerMask = 0x0FFFFFFF;
  62838. _this._accumulatedCount = 0;
  62839. _this._targetIndex = 0;
  62840. _this._currentRenderId = -1;
  62841. _this._started = false;
  62842. _this._stopped = false;
  62843. _this._timeDelta = 0;
  62844. _this._attributesStrideSize = 21;
  62845. _this._actualFrame = 0;
  62846. _this._rawTextureWidth = 256;
  62847. /**
  62848. * An event triggered when the system is disposed.
  62849. */
  62850. _this.onDisposeObservable = new BABYLON.Observable();
  62851. /**
  62852. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  62853. * to override the particles.
  62854. */
  62855. _this.forceDepthWrite = false;
  62856. _this._preWarmDone = false;
  62857. _this._scene = scene || BABYLON.Engine.LastCreatedScene;
  62858. // Setup the default processing configuration to the scene.
  62859. _this._attachImageProcessingConfiguration(null);
  62860. _this._engine = _this._scene.getEngine();
  62861. if (!options.randomTextureSize) {
  62862. delete options.randomTextureSize;
  62863. }
  62864. var fullOptions = __assign({ capacity: 50000, randomTextureSize: _this._engine.getCaps().maxTextureSize }, options);
  62865. var optionsAsNumber = options;
  62866. if (isFinite(optionsAsNumber)) {
  62867. fullOptions.capacity = optionsAsNumber;
  62868. }
  62869. _this._capacity = fullOptions.capacity;
  62870. _this._activeCount = fullOptions.capacity;
  62871. _this._currentActiveCount = 0;
  62872. _this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  62873. _this._scene.particleSystems.push(_this);
  62874. _this._updateEffectOptions = {
  62875. attributes: ["position", "age", "life", "seed", "size", "color", "direction", "initialDirection", "angle", "cellIndex", "cellStartOffset", "noiseCoordinates1", "noiseCoordinates2"],
  62876. uniformsNames: ["currentCount", "timeDelta", "emitterWM", "lifeTime", "color1", "color2", "sizeRange", "scaleRange", "gravity", "emitPower",
  62877. "direction1", "direction2", "minEmitBox", "maxEmitBox", "radius", "directionRandomizer", "height", "coneAngle", "stopFactor",
  62878. "angleRange", "radiusRange", "cellInfos", "noiseStrength", "limitVelocityDamping"],
  62879. uniformBuffersNames: [],
  62880. samplers: ["randomSampler", "randomSampler2", "sizeGradientSampler", "angularSpeedGradientSampler", "velocityGradientSampler", "limitVelocityGradientSampler", "noiseSampler", "dragGradientSampler"],
  62881. defines: "",
  62882. fallbacks: null,
  62883. onCompiled: null,
  62884. onError: null,
  62885. indexParameters: null,
  62886. maxSimultaneousLights: 0,
  62887. transformFeedbackVaryings: []
  62888. };
  62889. _this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  62890. // Random data
  62891. var maxTextureSize = Math.min(_this._engine.getCaps().maxTextureSize, fullOptions.randomTextureSize);
  62892. var d = [];
  62893. for (var i = 0; i < maxTextureSize; ++i) {
  62894. d.push(Math.random());
  62895. d.push(Math.random());
  62896. d.push(Math.random());
  62897. d.push(Math.random());
  62898. }
  62899. _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);
  62900. _this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  62901. _this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  62902. d = [];
  62903. for (var i = 0; i < maxTextureSize; ++i) {
  62904. d.push(Math.random());
  62905. d.push(Math.random());
  62906. d.push(Math.random());
  62907. d.push(Math.random());
  62908. }
  62909. _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);
  62910. _this._randomTexture2.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  62911. _this._randomTexture2.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  62912. _this._randomTextureSize = maxTextureSize;
  62913. return _this;
  62914. }
  62915. Object.defineProperty(GPUParticleSystem, "IsSupported", {
  62916. /**
  62917. * Gets a boolean indicating if the GPU particles can be rendered on current browser
  62918. */
  62919. get: function () {
  62920. if (!BABYLON.Engine.LastCreatedEngine) {
  62921. return false;
  62922. }
  62923. return BABYLON.Engine.LastCreatedEngine.webGLVersion > 1;
  62924. },
  62925. enumerable: true,
  62926. configurable: true
  62927. });
  62928. /**
  62929. * Gets the maximum number of particles active at the same time.
  62930. * @returns The max number of active particles.
  62931. */
  62932. GPUParticleSystem.prototype.getCapacity = function () {
  62933. return this._capacity;
  62934. };
  62935. Object.defineProperty(GPUParticleSystem.prototype, "activeParticleCount", {
  62936. /**
  62937. * Gets or set the number of active particles
  62938. */
  62939. get: function () {
  62940. return this._activeCount;
  62941. },
  62942. set: function (value) {
  62943. this._activeCount = Math.min(value, this._capacity);
  62944. },
  62945. enumerable: true,
  62946. configurable: true
  62947. });
  62948. /**
  62949. * Is this system ready to be used/rendered
  62950. * @return true if the system is ready
  62951. */
  62952. GPUParticleSystem.prototype.isReady = function () {
  62953. if (!this._updateEffect) {
  62954. this._recreateUpdateEffect();
  62955. this._recreateRenderEffect();
  62956. return false;
  62957. }
  62958. if (!this.emitter || !this._updateEffect.isReady() || !this._imageProcessingConfiguration.isReady() || !this._renderEffect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  62959. return false;
  62960. }
  62961. return true;
  62962. };
  62963. /**
  62964. * Gets if the system has been started. (Note: this will still be true after stop is called)
  62965. * @returns True if it has been started, otherwise false.
  62966. */
  62967. GPUParticleSystem.prototype.isStarted = function () {
  62968. return this._started;
  62969. };
  62970. /**
  62971. * Starts the particle system and begins to emit
  62972. * @param delay defines the delay in milliseconds before starting the system (this.startDelay by default)
  62973. */
  62974. GPUParticleSystem.prototype.start = function (delay) {
  62975. var _this = this;
  62976. if (delay === void 0) { delay = this.startDelay; }
  62977. if (!this.targetStopDuration && this._hasTargetStopDurationDependantGradient()) {
  62978. throw "Particle system started with a targetStopDuration dependant gradient (eg. startSizeGradients) but no targetStopDuration set";
  62979. }
  62980. if (delay) {
  62981. setTimeout(function () {
  62982. _this.start(0);
  62983. }, delay);
  62984. return;
  62985. }
  62986. this._started = true;
  62987. this._stopped = false;
  62988. this._preWarmDone = false;
  62989. };
  62990. /**
  62991. * Stops the particle system.
  62992. */
  62993. GPUParticleSystem.prototype.stop = function () {
  62994. this._stopped = true;
  62995. };
  62996. /**
  62997. * Remove all active particles
  62998. */
  62999. GPUParticleSystem.prototype.reset = function () {
  63000. this._releaseBuffers();
  63001. this._releaseVAOs();
  63002. this._currentActiveCount = 0;
  63003. this._targetIndex = 0;
  63004. };
  63005. /**
  63006. * Returns the string "GPUParticleSystem"
  63007. * @returns a string containing the class name
  63008. */
  63009. GPUParticleSystem.prototype.getClassName = function () {
  63010. return "GPUParticleSystem";
  63011. };
  63012. GPUParticleSystem.prototype._removeGradientAndTexture = function (gradient, gradients, texture) {
  63013. _super.prototype._removeGradientAndTexture.call(this, gradient, gradients, texture);
  63014. this._releaseBuffers();
  63015. return this;
  63016. };
  63017. /**
  63018. * Adds a new color gradient
  63019. * @param gradient defines the gradient to use (between 0 and 1)
  63020. * @param color1 defines the color to affect to the specified gradient
  63021. * @param color2 defines an additional color used to define a range ([color, color2]) with main color to pick the final color from
  63022. * @returns the current particle system
  63023. */
  63024. GPUParticleSystem.prototype.addColorGradient = function (gradient, color1, color2) {
  63025. if (!this._colorGradients) {
  63026. this._colorGradients = [];
  63027. }
  63028. var colorGradient = new BABYLON.ColorGradient();
  63029. colorGradient.gradient = gradient;
  63030. colorGradient.color1 = color1;
  63031. this._colorGradients.push(colorGradient);
  63032. this._colorGradients.sort(function (a, b) {
  63033. if (a.gradient < b.gradient) {
  63034. return -1;
  63035. }
  63036. else if (a.gradient > b.gradient) {
  63037. return 1;
  63038. }
  63039. return 0;
  63040. });
  63041. if (this._colorGradientsTexture) {
  63042. this._colorGradientsTexture.dispose();
  63043. this._colorGradientsTexture = null;
  63044. }
  63045. this._releaseBuffers();
  63046. return this;
  63047. };
  63048. /**
  63049. * Remove a specific color gradient
  63050. * @param gradient defines the gradient to remove
  63051. * @returns the current particle system
  63052. */
  63053. GPUParticleSystem.prototype.removeColorGradient = function (gradient) {
  63054. this._removeGradientAndTexture(gradient, this._colorGradients, this._colorGradientsTexture);
  63055. this._colorGradientsTexture = null;
  63056. return this;
  63057. };
  63058. GPUParticleSystem.prototype._addFactorGradient = function (factorGradients, gradient, factor) {
  63059. var valueGradient = new BABYLON.FactorGradient();
  63060. valueGradient.gradient = gradient;
  63061. valueGradient.factor1 = factor;
  63062. factorGradients.push(valueGradient);
  63063. factorGradients.sort(function (a, b) {
  63064. if (a.gradient < b.gradient) {
  63065. return -1;
  63066. }
  63067. else if (a.gradient > b.gradient) {
  63068. return 1;
  63069. }
  63070. return 0;
  63071. });
  63072. this._releaseBuffers();
  63073. };
  63074. /**
  63075. * Adds a new size gradient
  63076. * @param gradient defines the gradient to use (between 0 and 1)
  63077. * @param factor defines the size factor to affect to the specified gradient
  63078. * @returns the current particle system
  63079. */
  63080. GPUParticleSystem.prototype.addSizeGradient = function (gradient, factor) {
  63081. if (!this._sizeGradients) {
  63082. this._sizeGradients = [];
  63083. }
  63084. this._addFactorGradient(this._sizeGradients, gradient, factor);
  63085. if (this._sizeGradientsTexture) {
  63086. this._sizeGradientsTexture.dispose();
  63087. this._sizeGradientsTexture = null;
  63088. }
  63089. this._releaseBuffers();
  63090. return this;
  63091. };
  63092. /**
  63093. * Remove a specific size gradient
  63094. * @param gradient defines the gradient to remove
  63095. * @returns the current particle system
  63096. */
  63097. GPUParticleSystem.prototype.removeSizeGradient = function (gradient) {
  63098. this._removeGradientAndTexture(gradient, this._sizeGradients, this._sizeGradientsTexture);
  63099. this._sizeGradientsTexture = null;
  63100. return this;
  63101. };
  63102. /**
  63103. * Adds a new angular speed gradient
  63104. * @param gradient defines the gradient to use (between 0 and 1)
  63105. * @param factor defines the angular speed to affect to the specified gradient
  63106. * @returns the current particle system
  63107. */
  63108. GPUParticleSystem.prototype.addAngularSpeedGradient = function (gradient, factor) {
  63109. if (!this._angularSpeedGradients) {
  63110. this._angularSpeedGradients = [];
  63111. }
  63112. this._addFactorGradient(this._angularSpeedGradients, gradient, factor);
  63113. if (this._angularSpeedGradientsTexture) {
  63114. this._angularSpeedGradientsTexture.dispose();
  63115. this._angularSpeedGradientsTexture = null;
  63116. }
  63117. this._releaseBuffers();
  63118. return this;
  63119. };
  63120. /**
  63121. * Remove a specific angular speed gradient
  63122. * @param gradient defines the gradient to remove
  63123. * @returns the current particle system
  63124. */
  63125. GPUParticleSystem.prototype.removeAngularSpeedGradient = function (gradient) {
  63126. this._removeGradientAndTexture(gradient, this._angularSpeedGradients, this._angularSpeedGradientsTexture);
  63127. this._angularSpeedGradientsTexture = null;
  63128. return this;
  63129. };
  63130. /**
  63131. * Adds a new velocity gradient
  63132. * @param gradient defines the gradient to use (between 0 and 1)
  63133. * @param factor defines the velocity to affect to the specified gradient
  63134. * @returns the current particle system
  63135. */
  63136. GPUParticleSystem.prototype.addVelocityGradient = function (gradient, factor) {
  63137. if (!this._velocityGradients) {
  63138. this._velocityGradients = [];
  63139. }
  63140. this._addFactorGradient(this._velocityGradients, gradient, factor);
  63141. if (this._velocityGradientsTexture) {
  63142. this._velocityGradientsTexture.dispose();
  63143. this._velocityGradientsTexture = null;
  63144. }
  63145. this._releaseBuffers();
  63146. return this;
  63147. };
  63148. /**
  63149. * Remove a specific velocity gradient
  63150. * @param gradient defines the gradient to remove
  63151. * @returns the current particle system
  63152. */
  63153. GPUParticleSystem.prototype.removeVelocityGradient = function (gradient) {
  63154. this._removeGradientAndTexture(gradient, this._velocityGradients, this._velocityGradientsTexture);
  63155. this._velocityGradientsTexture = null;
  63156. return this;
  63157. };
  63158. /**
  63159. * Adds a new limit velocity gradient
  63160. * @param gradient defines the gradient to use (between 0 and 1)
  63161. * @param factor defines the limit velocity value to affect to the specified gradient
  63162. * @returns the current particle system
  63163. */
  63164. GPUParticleSystem.prototype.addLimitVelocityGradient = function (gradient, factor) {
  63165. if (!this._limitVelocityGradients) {
  63166. this._limitVelocityGradients = [];
  63167. }
  63168. this._addFactorGradient(this._limitVelocityGradients, gradient, factor);
  63169. if (this._limitVelocityGradientsTexture) {
  63170. this._limitVelocityGradientsTexture.dispose();
  63171. this._limitVelocityGradientsTexture = null;
  63172. }
  63173. this._releaseBuffers();
  63174. return this;
  63175. };
  63176. /**
  63177. * Remove a specific limit velocity gradient
  63178. * @param gradient defines the gradient to remove
  63179. * @returns the current particle system
  63180. */
  63181. GPUParticleSystem.prototype.removeLimitVelocityGradient = function (gradient) {
  63182. this._removeGradientAndTexture(gradient, this._limitVelocityGradients, this._limitVelocityGradientsTexture);
  63183. this._limitVelocityGradientsTexture = null;
  63184. return this;
  63185. };
  63186. /**
  63187. * Adds a new drag gradient
  63188. * @param gradient defines the gradient to use (between 0 and 1)
  63189. * @param factor defines the drag value to affect to the specified gradient
  63190. * @returns the current particle system
  63191. */
  63192. GPUParticleSystem.prototype.addDragGradient = function (gradient, factor) {
  63193. if (!this._dragGradients) {
  63194. this._dragGradients = [];
  63195. }
  63196. this._addFactorGradient(this._dragGradients, gradient, factor);
  63197. if (this._dragGradientsTexture) {
  63198. this._dragGradientsTexture.dispose();
  63199. this._dragGradientsTexture = null;
  63200. }
  63201. this._releaseBuffers();
  63202. return this;
  63203. };
  63204. /**
  63205. * Remove a specific drag gradient
  63206. * @param gradient defines the gradient to remove
  63207. * @returns the current particle system
  63208. */
  63209. GPUParticleSystem.prototype.removeDragGradient = function (gradient) {
  63210. this._removeGradientAndTexture(gradient, this._dragGradients, this._dragGradientsTexture);
  63211. this._dragGradientsTexture = null;
  63212. return this;
  63213. };
  63214. /**
  63215. * Not supported by GPUParticleSystem
  63216. * @param gradient defines the gradient to use (between 0 and 1)
  63217. * @param factor defines the emit rate value to affect to the specified gradient
  63218. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  63219. * @returns the current particle system
  63220. */
  63221. GPUParticleSystem.prototype.addEmitRateGradient = function (gradient, factor, factor2) {
  63222. // Do nothing as emit rate is not supported by GPUParticleSystem
  63223. return this;
  63224. };
  63225. /**
  63226. * Not supported by GPUParticleSystem
  63227. * @param gradient defines the gradient to remove
  63228. * @returns the current particle system
  63229. */
  63230. GPUParticleSystem.prototype.removeEmitRateGradient = function (gradient) {
  63231. // Do nothing as emit rate is not supported by GPUParticleSystem
  63232. return this;
  63233. };
  63234. /**
  63235. * Not supported by GPUParticleSystem
  63236. * @param gradient defines the gradient to use (between 0 and 1)
  63237. * @param factor defines the start size value to affect to the specified gradient
  63238. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  63239. * @returns the current particle system
  63240. */
  63241. GPUParticleSystem.prototype.addStartSizeGradient = function (gradient, factor, factor2) {
  63242. // Do nothing as start size is not supported by GPUParticleSystem
  63243. return this;
  63244. };
  63245. /**
  63246. * Not supported by GPUParticleSystem
  63247. * @param gradient defines the gradient to remove
  63248. * @returns the current particle system
  63249. */
  63250. GPUParticleSystem.prototype.removeStartSizeGradient = function (gradient) {
  63251. // Do nothing as start size is not supported by GPUParticleSystem
  63252. return this;
  63253. };
  63254. /**
  63255. * Not supported by GPUParticleSystem
  63256. * @param gradient defines the gradient to use (between 0 and 1)
  63257. * @param min defines the color remap minimal range
  63258. * @param max defines the color remap maximal range
  63259. * @returns the current particle system
  63260. */
  63261. GPUParticleSystem.prototype.addColorRemapGradient = function (gradient, min, max) {
  63262. // Do nothing as start size is not supported by GPUParticleSystem
  63263. return this;
  63264. };
  63265. /**
  63266. * Not supported by GPUParticleSystem
  63267. * @param gradient defines the gradient to remove
  63268. * @returns the current particle system
  63269. */
  63270. GPUParticleSystem.prototype.removeColorRemapGradient = function (gradient) {
  63271. // Do nothing as start size is not supported by GPUParticleSystem
  63272. return this;
  63273. };
  63274. /**
  63275. * Not supported by GPUParticleSystem
  63276. * @param gradient defines the gradient to use (between 0 and 1)
  63277. * @param min defines the alpha remap minimal range
  63278. * @param max defines the alpha remap maximal range
  63279. * @returns the current particle system
  63280. */
  63281. GPUParticleSystem.prototype.addAlphaRemapGradient = function (gradient, min, max) {
  63282. // Do nothing as start size is not supported by GPUParticleSystem
  63283. return this;
  63284. };
  63285. /**
  63286. * Not supported by GPUParticleSystem
  63287. * @param gradient defines the gradient to remove
  63288. * @returns the current particle system
  63289. */
  63290. GPUParticleSystem.prototype.removeAlphaRemapGradient = function (gradient) {
  63291. // Do nothing as start size is not supported by GPUParticleSystem
  63292. return this;
  63293. };
  63294. /**
  63295. * Not supported by GPUParticleSystem
  63296. * @param gradient defines the gradient to use (between 0 and 1)
  63297. * @param color defines the color to affect to the specified gradient
  63298. * @returns the current particle system
  63299. */
  63300. GPUParticleSystem.prototype.addRampGradient = function (gradient, color) {
  63301. //Not supported by GPUParticleSystem
  63302. return this;
  63303. };
  63304. /**
  63305. * Not supported by GPUParticleSystem
  63306. * @param gradient defines the gradient to remove
  63307. * @returns the current particle system
  63308. */
  63309. GPUParticleSystem.prototype.removeRampGradient = function (gradient) {
  63310. //Not supported by GPUParticleSystem
  63311. return this;
  63312. };
  63313. /**
  63314. * Not supported by GPUParticleSystem
  63315. * @returns the list of ramp gradients
  63316. */
  63317. GPUParticleSystem.prototype.getRampGradients = function () {
  63318. return null;
  63319. };
  63320. Object.defineProperty(GPUParticleSystem.prototype, "useRampGradients", {
  63321. /**
  63322. * Not supported by GPUParticleSystem
  63323. * Gets or sets a boolean indicating that ramp gradients must be used
  63324. * @see http://doc.babylonjs.com/babylon101/particles#ramp-gradients
  63325. */
  63326. get: function () {
  63327. //Not supported by GPUParticleSystem
  63328. return false;
  63329. },
  63330. set: function (value) {
  63331. //Not supported by GPUParticleSystem
  63332. },
  63333. enumerable: true,
  63334. configurable: true
  63335. });
  63336. GPUParticleSystem.prototype._reset = function () {
  63337. this._releaseBuffers();
  63338. };
  63339. GPUParticleSystem.prototype._createUpdateVAO = function (source) {
  63340. var updateVertexBuffers = {};
  63341. updateVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3);
  63342. updateVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1);
  63343. updateVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1);
  63344. updateVertexBuffers["seed"] = source.createVertexBuffer("seed", 5, 4);
  63345. updateVertexBuffers["size"] = source.createVertexBuffer("size", 9, 3);
  63346. var offset = 12;
  63347. if (!this._colorGradientsTexture) {
  63348. updateVertexBuffers["color"] = source.createVertexBuffer("color", offset, 4);
  63349. offset += 4;
  63350. }
  63351. updateVertexBuffers["direction"] = source.createVertexBuffer("direction", offset, 3);
  63352. offset += 3;
  63353. if (!this._isBillboardBased) {
  63354. updateVertexBuffers["initialDirection"] = source.createVertexBuffer("initialDirection", offset, 3);
  63355. offset += 3;
  63356. }
  63357. if (this._angularSpeedGradientsTexture) {
  63358. updateVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 1);
  63359. offset += 1;
  63360. }
  63361. else {
  63362. updateVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 2);
  63363. offset += 2;
  63364. }
  63365. if (this._isAnimationSheetEnabled) {
  63366. updateVertexBuffers["cellIndex"] = source.createVertexBuffer("cellIndex", offset, 1);
  63367. offset += 1;
  63368. if (this.spriteRandomStartCell) {
  63369. updateVertexBuffers["cellStartOffset"] = source.createVertexBuffer("cellStartOffset", offset, 1);
  63370. offset += 1;
  63371. }
  63372. }
  63373. if (this.noiseTexture) {
  63374. updateVertexBuffers["noiseCoordinates1"] = source.createVertexBuffer("noiseCoordinates1", offset, 3);
  63375. offset += 3;
  63376. updateVertexBuffers["noiseCoordinates2"] = source.createVertexBuffer("noiseCoordinates2", offset, 3);
  63377. offset += 3;
  63378. }
  63379. var vao = this._engine.recordVertexArrayObject(updateVertexBuffers, null, this._updateEffect);
  63380. this._engine.bindArrayBuffer(null);
  63381. return vao;
  63382. };
  63383. GPUParticleSystem.prototype._createRenderVAO = function (source, spriteSource) {
  63384. var renderVertexBuffers = {};
  63385. renderVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3, this._attributesStrideSize, true);
  63386. renderVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1, this._attributesStrideSize, true);
  63387. renderVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1, this._attributesStrideSize, true);
  63388. renderVertexBuffers["size"] = source.createVertexBuffer("size", 9, 3, this._attributesStrideSize, true);
  63389. var offset = 12;
  63390. if (!this._colorGradientsTexture) {
  63391. renderVertexBuffers["color"] = source.createVertexBuffer("color", offset, 4, this._attributesStrideSize, true);
  63392. offset += 4;
  63393. }
  63394. if (this.billboardMode === BABYLON.ParticleSystem.BILLBOARDMODE_STRETCHED) {
  63395. renderVertexBuffers["direction"] = source.createVertexBuffer("direction", offset, 3, this._attributesStrideSize, true);
  63396. }
  63397. offset += 3; // Direction
  63398. if (!this._isBillboardBased) {
  63399. renderVertexBuffers["initialDirection"] = source.createVertexBuffer("initialDirection", offset, 3, this._attributesStrideSize, true);
  63400. offset += 3;
  63401. }
  63402. renderVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 1, this._attributesStrideSize, true);
  63403. if (this._angularSpeedGradientsTexture) {
  63404. offset++;
  63405. }
  63406. else {
  63407. offset += 2;
  63408. }
  63409. if (this._isAnimationSheetEnabled) {
  63410. renderVertexBuffers["cellIndex"] = source.createVertexBuffer("cellIndex", offset, 1, this._attributesStrideSize, true);
  63411. offset += 1;
  63412. if (this.spriteRandomStartCell) {
  63413. renderVertexBuffers["cellStartOffset"] = source.createVertexBuffer("cellStartOffset", offset, 1, this._attributesStrideSize, true);
  63414. offset += 1;
  63415. }
  63416. }
  63417. if (this.noiseTexture) {
  63418. renderVertexBuffers["noiseCoordinates1"] = source.createVertexBuffer("noiseCoordinates1", offset, 3, this._attributesStrideSize, true);
  63419. offset += 3;
  63420. renderVertexBuffers["noiseCoordinates2"] = source.createVertexBuffer("noiseCoordinates2", offset, 3, this._attributesStrideSize, true);
  63421. offset += 3;
  63422. }
  63423. renderVertexBuffers["offset"] = spriteSource.createVertexBuffer("offset", 0, 2);
  63424. renderVertexBuffers["uv"] = spriteSource.createVertexBuffer("uv", 2, 2);
  63425. var vao = this._engine.recordVertexArrayObject(renderVertexBuffers, null, this._renderEffect);
  63426. this._engine.bindArrayBuffer(null);
  63427. return vao;
  63428. };
  63429. GPUParticleSystem.prototype._initialize = function (force) {
  63430. if (force === void 0) { force = false; }
  63431. if (this._buffer0 && !force) {
  63432. return;
  63433. }
  63434. var engine = this._scene.getEngine();
  63435. var data = new Array();
  63436. if (!this.isBillboardBased) {
  63437. this._attributesStrideSize += 3;
  63438. }
  63439. if (this._colorGradientsTexture) {
  63440. this._attributesStrideSize -= 4;
  63441. }
  63442. if (this._angularSpeedGradientsTexture) {
  63443. this._attributesStrideSize -= 1;
  63444. }
  63445. if (this._isAnimationSheetEnabled) {
  63446. this._attributesStrideSize += 1;
  63447. if (this.spriteRandomStartCell) {
  63448. this._attributesStrideSize += 1;
  63449. }
  63450. }
  63451. if (this.noiseTexture) {
  63452. this._attributesStrideSize += 6;
  63453. }
  63454. for (var particleIndex = 0; particleIndex < this._capacity; particleIndex++) {
  63455. // position
  63456. data.push(0.0);
  63457. data.push(0.0);
  63458. data.push(0.0);
  63459. // Age and life
  63460. data.push(0.0); // create the particle as a dead one to create a new one at start
  63461. data.push(0.0);
  63462. // Seed
  63463. data.push(Math.random());
  63464. data.push(Math.random());
  63465. data.push(Math.random());
  63466. data.push(Math.random());
  63467. // Size
  63468. data.push(0.0);
  63469. data.push(0.0);
  63470. data.push(0.0);
  63471. if (!this._colorGradientsTexture) {
  63472. // color
  63473. data.push(0.0);
  63474. data.push(0.0);
  63475. data.push(0.0);
  63476. data.push(0.0);
  63477. }
  63478. // direction
  63479. data.push(0.0);
  63480. data.push(0.0);
  63481. data.push(0.0);
  63482. if (!this.isBillboardBased) {
  63483. // initialDirection
  63484. data.push(0.0);
  63485. data.push(0.0);
  63486. data.push(0.0);
  63487. }
  63488. // angle
  63489. data.push(0.0);
  63490. if (!this._angularSpeedGradientsTexture) {
  63491. data.push(0.0);
  63492. }
  63493. if (this._isAnimationSheetEnabled) {
  63494. data.push(0.0);
  63495. if (this.spriteRandomStartCell) {
  63496. data.push(0.0);
  63497. }
  63498. }
  63499. if (this.noiseTexture) { // Random coordinates for reading into noise texture
  63500. data.push(Math.random());
  63501. data.push(Math.random());
  63502. data.push(Math.random());
  63503. data.push(Math.random());
  63504. data.push(Math.random());
  63505. data.push(Math.random());
  63506. }
  63507. }
  63508. // Sprite data
  63509. var spriteData = new Float32Array([0.5, 0.5, 1, 1,
  63510. -0.5, 0.5, 0, 1,
  63511. -0.5, -0.5, 0, 0,
  63512. 0.5, -0.5, 1, 0]);
  63513. // Buffers
  63514. this._buffer0 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  63515. this._buffer1 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  63516. this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 4);
  63517. // Update VAO
  63518. this._updateVAO = [];
  63519. this._updateVAO.push(this._createUpdateVAO(this._buffer0));
  63520. this._updateVAO.push(this._createUpdateVAO(this._buffer1));
  63521. // Render VAO
  63522. this._renderVAO = [];
  63523. this._renderVAO.push(this._createRenderVAO(this._buffer1, this._spriteBuffer));
  63524. this._renderVAO.push(this._createRenderVAO(this._buffer0, this._spriteBuffer));
  63525. // Links
  63526. this._sourceBuffer = this._buffer0;
  63527. this._targetBuffer = this._buffer1;
  63528. };
  63529. /** @hidden */
  63530. GPUParticleSystem.prototype._recreateUpdateEffect = function () {
  63531. var defines = this.particleEmitterType ? this.particleEmitterType.getEffectDefines() : "";
  63532. if (this._isBillboardBased) {
  63533. defines += "\n#define BILLBOARD";
  63534. }
  63535. if (this._colorGradientsTexture) {
  63536. defines += "\n#define COLORGRADIENTS";
  63537. }
  63538. if (this._sizeGradientsTexture) {
  63539. defines += "\n#define SIZEGRADIENTS";
  63540. }
  63541. if (this._angularSpeedGradientsTexture) {
  63542. defines += "\n#define ANGULARSPEEDGRADIENTS";
  63543. }
  63544. if (this._velocityGradientsTexture) {
  63545. defines += "\n#define VELOCITYGRADIENTS";
  63546. }
  63547. if (this._limitVelocityGradientsTexture) {
  63548. defines += "\n#define LIMITVELOCITYGRADIENTS";
  63549. }
  63550. if (this._dragGradientsTexture) {
  63551. defines += "\n#define DRAGGRADIENTS";
  63552. }
  63553. if (this.isAnimationSheetEnabled) {
  63554. defines += "\n#define ANIMATESHEET";
  63555. if (this.spriteRandomStartCell) {
  63556. defines += "\n#define ANIMATESHEETRANDOMSTART";
  63557. }
  63558. }
  63559. if (this.noiseTexture) {
  63560. defines += "\n#define NOISE";
  63561. }
  63562. if (this._updateEffect && this._updateEffectOptions.defines === defines) {
  63563. return;
  63564. }
  63565. this._updateEffectOptions.transformFeedbackVaryings = ["outPosition", "outAge", "outLife", "outSeed", "outSize"];
  63566. if (!this._colorGradientsTexture) {
  63567. this._updateEffectOptions.transformFeedbackVaryings.push("outColor");
  63568. }
  63569. this._updateEffectOptions.transformFeedbackVaryings.push("outDirection");
  63570. if (!this._isBillboardBased) {
  63571. this._updateEffectOptions.transformFeedbackVaryings.push("outInitialDirection");
  63572. }
  63573. this._updateEffectOptions.transformFeedbackVaryings.push("outAngle");
  63574. if (this.isAnimationSheetEnabled) {
  63575. this._updateEffectOptions.transformFeedbackVaryings.push("outCellIndex");
  63576. if (this.spriteRandomStartCell) {
  63577. this._updateEffectOptions.transformFeedbackVaryings.push("outCellStartOffset");
  63578. }
  63579. }
  63580. if (this.noiseTexture) {
  63581. this._updateEffectOptions.transformFeedbackVaryings.push("outNoiseCoordinates1");
  63582. this._updateEffectOptions.transformFeedbackVaryings.push("outNoiseCoordinates2");
  63583. }
  63584. this._updateEffectOptions.defines = defines;
  63585. this._updateEffect = new BABYLON.Effect("gpuUpdateParticles", this._updateEffectOptions, this._scene.getEngine());
  63586. };
  63587. /** @hidden */
  63588. GPUParticleSystem.prototype._recreateRenderEffect = function () {
  63589. var defines = "";
  63590. if (this._scene.clipPlane) {
  63591. defines = "\n#define CLIPPLANE";
  63592. }
  63593. if (this._scene.clipPlane2) {
  63594. defines = "\n#define CLIPPLANE2";
  63595. }
  63596. if (this._scene.clipPlane3) {
  63597. defines = "\n#define CLIPPLANE3";
  63598. }
  63599. if (this._scene.clipPlane4) {
  63600. defines = "\n#define CLIPPLANE4";
  63601. }
  63602. if (this.blendMode === BABYLON.ParticleSystem.BLENDMODE_MULTIPLY) {
  63603. defines = "\n#define BLENDMULTIPLYMODE";
  63604. }
  63605. if (this._isBillboardBased) {
  63606. defines += "\n#define BILLBOARD";
  63607. switch (this.billboardMode) {
  63608. case BABYLON.ParticleSystem.BILLBOARDMODE_Y:
  63609. defines += "\n#define BILLBOARDY";
  63610. break;
  63611. case BABYLON.ParticleSystem.BILLBOARDMODE_STRETCHED:
  63612. defines += "\n#define BILLBOARDSTRETCHED";
  63613. break;
  63614. case BABYLON.ParticleSystem.BILLBOARDMODE_ALL:
  63615. default:
  63616. break;
  63617. }
  63618. }
  63619. if (this._colorGradientsTexture) {
  63620. defines += "\n#define COLORGRADIENTS";
  63621. }
  63622. if (this.isAnimationSheetEnabled) {
  63623. defines += "\n#define ANIMATESHEET";
  63624. }
  63625. if (this._imageProcessingConfiguration) {
  63626. this._imageProcessingConfiguration.prepareDefines(this._imageProcessingConfigurationDefines);
  63627. defines += "\n" + this._imageProcessingConfigurationDefines.toString();
  63628. }
  63629. if (this._renderEffect && this._renderEffect.defines === defines) {
  63630. return;
  63631. }
  63632. var uniforms = ["view", "projection", "colorDead", "invView", "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "sheetInfos", "translationPivot", "eyePosition"];
  63633. var samplers = ["textureSampler", "colorGradientSampler"];
  63634. if (BABYLON.ImageProcessingConfiguration) {
  63635. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._imageProcessingConfigurationDefines);
  63636. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._imageProcessingConfigurationDefines);
  63637. }
  63638. this._renderEffect = new BABYLON.Effect("gpuRenderParticles", ["position", "age", "life", "size", "color", "offset", "uv", "direction", "initialDirection", "angle", "cellIndex"], uniforms, samplers, this._scene.getEngine(), defines);
  63639. };
  63640. /**
  63641. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  63642. * @param preWarm defines if we are in the pre-warmimg phase
  63643. */
  63644. GPUParticleSystem.prototype.animate = function (preWarm) {
  63645. if (preWarm === void 0) { preWarm = false; }
  63646. this._timeDelta = this.updateSpeed * (preWarm ? this.preWarmStepOffset : this._scene.getAnimationRatio());
  63647. this._actualFrame += this._timeDelta;
  63648. if (!this._stopped) {
  63649. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration) {
  63650. this.stop();
  63651. }
  63652. }
  63653. };
  63654. GPUParticleSystem.prototype._createFactorGradientTexture = function (factorGradients, textureName) {
  63655. var texture = this[textureName];
  63656. if (!factorGradients || !factorGradients.length || texture) {
  63657. return;
  63658. }
  63659. var data = new Float32Array(this._rawTextureWidth);
  63660. for (var x = 0; x < this._rawTextureWidth; x++) {
  63661. var ratio = x / this._rawTextureWidth;
  63662. BABYLON.Tools.GetCurrentGradient(ratio, factorGradients, function (currentGradient, nextGradient, scale) {
  63663. data[x] = BABYLON.Scalar.Lerp(currentGradient.factor1, nextGradient.factor1, scale);
  63664. });
  63665. }
  63666. this[textureName] = BABYLON.RawTexture.CreateRTexture(data, this._rawTextureWidth, 1, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  63667. };
  63668. GPUParticleSystem.prototype._createSizeGradientTexture = function () {
  63669. this._createFactorGradientTexture(this._sizeGradients, "_sizeGradientsTexture");
  63670. };
  63671. GPUParticleSystem.prototype._createAngularSpeedGradientTexture = function () {
  63672. this._createFactorGradientTexture(this._angularSpeedGradients, "_angularSpeedGradientsTexture");
  63673. };
  63674. GPUParticleSystem.prototype._createVelocityGradientTexture = function () {
  63675. this._createFactorGradientTexture(this._velocityGradients, "_velocityGradientsTexture");
  63676. };
  63677. GPUParticleSystem.prototype._createLimitVelocityGradientTexture = function () {
  63678. this._createFactorGradientTexture(this._limitVelocityGradients, "_limitVelocityGradientsTexture");
  63679. };
  63680. GPUParticleSystem.prototype._createDragGradientTexture = function () {
  63681. this._createFactorGradientTexture(this._dragGradients, "_dragGradientsTexture");
  63682. };
  63683. GPUParticleSystem.prototype._createColorGradientTexture = function () {
  63684. if (!this._colorGradients || !this._colorGradients.length || this._colorGradientsTexture) {
  63685. return;
  63686. }
  63687. var data = new Uint8Array(this._rawTextureWidth * 4);
  63688. var tmpColor = BABYLON.Tmp.Color4[0];
  63689. for (var x = 0; x < this._rawTextureWidth; x++) {
  63690. var ratio = x / this._rawTextureWidth;
  63691. BABYLON.Tools.GetCurrentGradient(ratio, this._colorGradients, function (currentGradient, nextGradient, scale) {
  63692. BABYLON.Color4.LerpToRef(currentGradient.color1, nextGradient.color1, scale, tmpColor);
  63693. data[x * 4] = tmpColor.r * 255;
  63694. data[x * 4 + 1] = tmpColor.g * 255;
  63695. data[x * 4 + 2] = tmpColor.b * 255;
  63696. data[x * 4 + 3] = tmpColor.a * 255;
  63697. });
  63698. }
  63699. this._colorGradientsTexture = BABYLON.RawTexture.CreateRGBATexture(data, this._rawTextureWidth, 1, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  63700. };
  63701. /**
  63702. * Renders the particle system in its current state
  63703. * @param preWarm defines if the system should only update the particles but not render them
  63704. * @returns the current number of particles
  63705. */
  63706. GPUParticleSystem.prototype.render = function (preWarm) {
  63707. if (preWarm === void 0) { preWarm = false; }
  63708. if (!this._started) {
  63709. return 0;
  63710. }
  63711. this._createColorGradientTexture();
  63712. this._createSizeGradientTexture();
  63713. this._createAngularSpeedGradientTexture();
  63714. this._createVelocityGradientTexture();
  63715. this._createLimitVelocityGradientTexture();
  63716. this._createDragGradientTexture();
  63717. this._recreateUpdateEffect();
  63718. this._recreateRenderEffect();
  63719. if (!this.isReady()) {
  63720. return 0;
  63721. }
  63722. if (!preWarm) {
  63723. if (!this._preWarmDone && this.preWarmCycles) {
  63724. for (var index = 0; index < this.preWarmCycles; index++) {
  63725. this.animate(true);
  63726. this.render(true);
  63727. }
  63728. this._preWarmDone = true;
  63729. }
  63730. if (this._currentRenderId === this._scene.getRenderId()) {
  63731. return 0;
  63732. }
  63733. this._currentRenderId = this._scene.getRenderId();
  63734. }
  63735. // Get everything ready to render
  63736. this._initialize();
  63737. this._accumulatedCount += this.emitRate * this._timeDelta;
  63738. if (this._accumulatedCount > 1) {
  63739. var intPart = this._accumulatedCount | 0;
  63740. this._accumulatedCount -= intPart;
  63741. this._currentActiveCount = Math.min(this._activeCount, this._currentActiveCount + intPart);
  63742. }
  63743. if (!this._currentActiveCount) {
  63744. return 0;
  63745. }
  63746. // Enable update effect
  63747. this._engine.enableEffect(this._updateEffect);
  63748. this._engine.setState(false);
  63749. this._updateEffect.setFloat("currentCount", this._currentActiveCount);
  63750. this._updateEffect.setFloat("timeDelta", this._timeDelta);
  63751. this._updateEffect.setFloat("stopFactor", this._stopped ? 0 : 1);
  63752. this._updateEffect.setTexture("randomSampler", this._randomTexture);
  63753. this._updateEffect.setTexture("randomSampler2", this._randomTexture2);
  63754. this._updateEffect.setFloat2("lifeTime", this.minLifeTime, this.maxLifeTime);
  63755. this._updateEffect.setFloat2("emitPower", this.minEmitPower, this.maxEmitPower);
  63756. if (!this._colorGradientsTexture) {
  63757. this._updateEffect.setDirectColor4("color1", this.color1);
  63758. this._updateEffect.setDirectColor4("color2", this.color2);
  63759. }
  63760. this._updateEffect.setFloat2("sizeRange", this.minSize, this.maxSize);
  63761. this._updateEffect.setFloat4("scaleRange", this.minScaleX, this.maxScaleX, this.minScaleY, this.maxScaleY);
  63762. this._updateEffect.setFloat4("angleRange", this.minAngularSpeed, this.maxAngularSpeed, this.minInitialRotation, this.maxInitialRotation);
  63763. this._updateEffect.setVector3("gravity", this.gravity);
  63764. if (this._sizeGradientsTexture) {
  63765. this._updateEffect.setTexture("sizeGradientSampler", this._sizeGradientsTexture);
  63766. }
  63767. if (this._angularSpeedGradientsTexture) {
  63768. this._updateEffect.setTexture("angularSpeedGradientSampler", this._angularSpeedGradientsTexture);
  63769. }
  63770. if (this._velocityGradientsTexture) {
  63771. this._updateEffect.setTexture("velocityGradientSampler", this._velocityGradientsTexture);
  63772. }
  63773. if (this._limitVelocityGradientsTexture) {
  63774. this._updateEffect.setTexture("limitVelocityGradientSampler", this._limitVelocityGradientsTexture);
  63775. this._updateEffect.setFloat("limitVelocityDamping", this.limitVelocityDamping);
  63776. }
  63777. if (this._dragGradientsTexture) {
  63778. this._updateEffect.setTexture("dragGradientSampler", this._dragGradientsTexture);
  63779. }
  63780. if (this.particleEmitterType) {
  63781. this.particleEmitterType.applyToShader(this._updateEffect);
  63782. }
  63783. if (this._isAnimationSheetEnabled) {
  63784. this._updateEffect.setFloat3("cellInfos", this.startSpriteCellID, this.endSpriteCellID, this.spriteCellChangeSpeed);
  63785. }
  63786. if (this.noiseTexture) {
  63787. this._updateEffect.setTexture("noiseSampler", this.noiseTexture);
  63788. this._updateEffect.setVector3("noiseStrength", this.noiseStrength);
  63789. }
  63790. var emitterWM;
  63791. if (this.emitter.position) {
  63792. var emitterMesh = this.emitter;
  63793. emitterWM = emitterMesh.getWorldMatrix();
  63794. }
  63795. else {
  63796. var emitterPosition = this.emitter;
  63797. emitterWM = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  63798. }
  63799. this._updateEffect.setMatrix("emitterWM", emitterWM);
  63800. // Bind source VAO
  63801. this._engine.bindVertexArrayObject(this._updateVAO[this._targetIndex], null);
  63802. // Update
  63803. this._engine.bindTransformFeedbackBuffer(this._targetBuffer.getBuffer());
  63804. this._engine.setRasterizerState(false);
  63805. this._engine.beginTransformFeedback(true);
  63806. this._engine.drawArraysType(BABYLON.Material.PointListDrawMode, 0, this._currentActiveCount);
  63807. this._engine.endTransformFeedback();
  63808. this._engine.setRasterizerState(true);
  63809. this._engine.bindTransformFeedbackBuffer(null);
  63810. if (!preWarm) {
  63811. // Enable render effect
  63812. this._engine.enableEffect(this._renderEffect);
  63813. var viewMatrix = this._scene.getViewMatrix();
  63814. this._renderEffect.setMatrix("view", viewMatrix);
  63815. this._renderEffect.setMatrix("projection", this._scene.getProjectionMatrix());
  63816. this._renderEffect.setTexture("textureSampler", this.particleTexture);
  63817. this._renderEffect.setVector2("translationPivot", this.translationPivot);
  63818. if (this._colorGradientsTexture) {
  63819. this._renderEffect.setTexture("colorGradientSampler", this._colorGradientsTexture);
  63820. }
  63821. else {
  63822. this._renderEffect.setDirectColor4("colorDead", this.colorDead);
  63823. }
  63824. if (this._isAnimationSheetEnabled && this.particleTexture) {
  63825. var baseSize = this.particleTexture.getBaseSize();
  63826. this._renderEffect.setFloat3("sheetInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  63827. }
  63828. if (this._isBillboardBased) {
  63829. var camera = this._scene.activeCamera;
  63830. this._renderEffect.setVector3("eyePosition", camera.globalPosition);
  63831. }
  63832. if (this._scene.clipPlane || this._scene.clipPlane2 || this._scene.clipPlane3 || this._scene.clipPlane4) {
  63833. var invView = viewMatrix.clone();
  63834. invView.invert();
  63835. this._renderEffect.setMatrix("invView", invView);
  63836. BABYLON.MaterialHelper.BindClipPlane(this._renderEffect, this._scene);
  63837. }
  63838. // image processing
  63839. if (this._imageProcessingConfiguration && !this._imageProcessingConfiguration.applyByPostProcess) {
  63840. this._imageProcessingConfiguration.bind(this._renderEffect);
  63841. }
  63842. // Draw order
  63843. switch (this.blendMode) {
  63844. case BABYLON.ParticleSystem.BLENDMODE_ADD:
  63845. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  63846. break;
  63847. case BABYLON.ParticleSystem.BLENDMODE_ONEONE:
  63848. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  63849. break;
  63850. case BABYLON.ParticleSystem.BLENDMODE_STANDARD:
  63851. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  63852. break;
  63853. case BABYLON.ParticleSystem.BLENDMODE_MULTIPLY:
  63854. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_MULTIPLY);
  63855. break;
  63856. }
  63857. if (this.forceDepthWrite) {
  63858. this._engine.setDepthWrite(true);
  63859. }
  63860. // Bind source VAO
  63861. this._engine.bindVertexArrayObject(this._renderVAO[this._targetIndex], null);
  63862. // Render
  63863. this._engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._currentActiveCount);
  63864. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  63865. }
  63866. // Switch VAOs
  63867. this._targetIndex++;
  63868. if (this._targetIndex === 2) {
  63869. this._targetIndex = 0;
  63870. }
  63871. // Switch buffers
  63872. var tmpBuffer = this._sourceBuffer;
  63873. this._sourceBuffer = this._targetBuffer;
  63874. this._targetBuffer = tmpBuffer;
  63875. return this._currentActiveCount;
  63876. };
  63877. /**
  63878. * Rebuilds the particle system
  63879. */
  63880. GPUParticleSystem.prototype.rebuild = function () {
  63881. this._initialize(true);
  63882. };
  63883. GPUParticleSystem.prototype._releaseBuffers = function () {
  63884. if (this._buffer0) {
  63885. this._buffer0.dispose();
  63886. this._buffer0 = null;
  63887. }
  63888. if (this._buffer1) {
  63889. this._buffer1.dispose();
  63890. this._buffer1 = null;
  63891. }
  63892. if (this._spriteBuffer) {
  63893. this._spriteBuffer.dispose();
  63894. this._spriteBuffer = null;
  63895. }
  63896. };
  63897. GPUParticleSystem.prototype._releaseVAOs = function () {
  63898. if (!this._updateVAO) {
  63899. return;
  63900. }
  63901. for (var index = 0; index < this._updateVAO.length; index++) {
  63902. this._engine.releaseVertexArrayObject(this._updateVAO[index]);
  63903. }
  63904. this._updateVAO = [];
  63905. for (var index = 0; index < this._renderVAO.length; index++) {
  63906. this._engine.releaseVertexArrayObject(this._renderVAO[index]);
  63907. }
  63908. this._renderVAO = [];
  63909. };
  63910. /**
  63911. * Disposes the particle system and free the associated resources
  63912. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  63913. */
  63914. GPUParticleSystem.prototype.dispose = function (disposeTexture) {
  63915. if (disposeTexture === void 0) { disposeTexture = true; }
  63916. var index = this._scene.particleSystems.indexOf(this);
  63917. if (index > -1) {
  63918. this._scene.particleSystems.splice(index, 1);
  63919. }
  63920. this._releaseBuffers();
  63921. this._releaseVAOs();
  63922. if (this._colorGradientsTexture) {
  63923. this._colorGradientsTexture.dispose();
  63924. this._colorGradientsTexture = null;
  63925. }
  63926. if (this._sizeGradientsTexture) {
  63927. this._sizeGradientsTexture.dispose();
  63928. this._sizeGradientsTexture = null;
  63929. }
  63930. if (this._angularSpeedGradientsTexture) {
  63931. this._angularSpeedGradientsTexture.dispose();
  63932. this._angularSpeedGradientsTexture = null;
  63933. }
  63934. if (this._velocityGradientsTexture) {
  63935. this._velocityGradientsTexture.dispose();
  63936. this._velocityGradientsTexture = null;
  63937. }
  63938. if (this._limitVelocityGradientsTexture) {
  63939. this._limitVelocityGradientsTexture.dispose();
  63940. this._limitVelocityGradientsTexture = null;
  63941. }
  63942. if (this._dragGradientsTexture) {
  63943. this._dragGradientsTexture.dispose();
  63944. this._dragGradientsTexture = null;
  63945. }
  63946. if (this._randomTexture) {
  63947. this._randomTexture.dispose();
  63948. this._randomTexture = null;
  63949. }
  63950. if (this._randomTexture2) {
  63951. this._randomTexture2.dispose();
  63952. this._randomTexture2 = null;
  63953. }
  63954. if (disposeTexture && this.particleTexture) {
  63955. this.particleTexture.dispose();
  63956. this.particleTexture = null;
  63957. }
  63958. if (disposeTexture && this.noiseTexture) {
  63959. this.noiseTexture.dispose();
  63960. this.noiseTexture = null;
  63961. }
  63962. // Callback
  63963. this.onDisposeObservable.notifyObservers(this);
  63964. this.onDisposeObservable.clear();
  63965. };
  63966. /**
  63967. * Clones the particle system.
  63968. * @param name The name of the cloned object
  63969. * @param newEmitter The new emitter to use
  63970. * @returns the cloned particle system
  63971. */
  63972. GPUParticleSystem.prototype.clone = function (name, newEmitter) {
  63973. var result = new GPUParticleSystem(name, { capacity: this._capacity, randomTextureSize: this._randomTextureSize }, this._scene);
  63974. BABYLON.Tools.DeepCopy(this, result);
  63975. if (newEmitter === undefined) {
  63976. newEmitter = this.emitter;
  63977. }
  63978. result.emitter = newEmitter;
  63979. if (this.particleTexture) {
  63980. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  63981. }
  63982. return result;
  63983. };
  63984. /**
  63985. * Serializes the particle system to a JSON object.
  63986. * @returns the JSON object
  63987. */
  63988. GPUParticleSystem.prototype.serialize = function () {
  63989. var serializationObject = {};
  63990. BABYLON.ParticleSystem._Serialize(serializationObject, this);
  63991. serializationObject.activeParticleCount = this.activeParticleCount;
  63992. return serializationObject;
  63993. };
  63994. /**
  63995. * Parses a JSON object to create a GPU particle system.
  63996. * @param parsedParticleSystem The JSON object to parse
  63997. * @param scene The scene to create the particle system in
  63998. * @param rootUrl The root url to use to load external dependencies like texture
  63999. * @returns the parsed GPU particle system
  64000. */
  64001. GPUParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  64002. var name = parsedParticleSystem.name;
  64003. var particleSystem = new GPUParticleSystem(name, { capacity: parsedParticleSystem.capacity, randomTextureSize: parsedParticleSystem.randomTextureSize }, scene);
  64004. if (parsedParticleSystem.activeParticleCount) {
  64005. particleSystem.activeParticleCount = parsedParticleSystem.activeParticleCount;
  64006. }
  64007. BABYLON.ParticleSystem._Parse(parsedParticleSystem, particleSystem, scene, rootUrl);
  64008. return particleSystem;
  64009. };
  64010. return GPUParticleSystem;
  64011. }(BABYLON.BaseParticleSystem));
  64012. BABYLON.GPUParticleSystem = GPUParticleSystem;
  64013. })(BABYLON || (BABYLON = {}));
  64014. //# sourceMappingURL=babylon.gpuParticleSystem.js.map
  64015. var BABYLON;
  64016. (function (BABYLON) {
  64017. /**
  64018. * Represents one particle of a solid particle system.
  64019. */
  64020. var SolidParticle = /** @class */ (function () {
  64021. /**
  64022. * Creates a Solid Particle object.
  64023. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  64024. * @param particleIndex (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  64025. * @param positionIndex (integer) is the starting index of the particle vertices in the SPS "positions" array.
  64026. * @param indiceIndex (integer) is the starting index of the particle indices in the SPS "indices" array.
  64027. * @param model (ModelShape) is a reference to the model shape on what the particle is designed.
  64028. * @param shapeId (integer) is the model shape identifier in the SPS.
  64029. * @param idxInShape (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  64030. * @param modelBoundingInfo is the reference to the model BoundingInfo used for intersection computations.
  64031. */
  64032. function SolidParticle(particleIndex, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  64033. if (modelBoundingInfo === void 0) { modelBoundingInfo = null; }
  64034. /**
  64035. * particle global index
  64036. */
  64037. this.idx = 0;
  64038. /**
  64039. * The color of the particle
  64040. */
  64041. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  64042. /**
  64043. * The world space position of the particle.
  64044. */
  64045. this.position = BABYLON.Vector3.Zero();
  64046. /**
  64047. * The world space rotation of the particle. (Not use if rotationQuaternion is set)
  64048. */
  64049. this.rotation = BABYLON.Vector3.Zero();
  64050. /**
  64051. * The scaling of the particle.
  64052. */
  64053. this.scaling = BABYLON.Vector3.One();
  64054. /**
  64055. * The uvs of the particle.
  64056. */
  64057. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  64058. /**
  64059. * The current speed of the particle.
  64060. */
  64061. this.velocity = BABYLON.Vector3.Zero();
  64062. /**
  64063. * The pivot point in the particle local space.
  64064. */
  64065. this.pivot = BABYLON.Vector3.Zero();
  64066. /**
  64067. * Must the particle be translated from its pivot point in its local space ?
  64068. * In this case, the pivot point is set at the origin of the particle local space and the particle is translated.
  64069. * Default : false
  64070. */
  64071. this.translateFromPivot = false;
  64072. /**
  64073. * Is the particle active or not ?
  64074. */
  64075. this.alive = true;
  64076. /**
  64077. * Is the particle visible or not ?
  64078. */
  64079. this.isVisible = true;
  64080. /**
  64081. * Index of this particle in the global "positions" array (Internal use)
  64082. * @hidden
  64083. */
  64084. this._pos = 0;
  64085. /**
  64086. * @hidden Index of this particle in the global "indices" array (Internal use)
  64087. */
  64088. this._ind = 0;
  64089. /**
  64090. * ModelShape id of this particle
  64091. */
  64092. this.shapeId = 0;
  64093. /**
  64094. * Index of the particle in its shape id (Internal use)
  64095. */
  64096. this.idxInShape = 0;
  64097. /**
  64098. * @hidden Still set as invisible in order to skip useless computations (Internal use)
  64099. */
  64100. this._stillInvisible = false;
  64101. /**
  64102. * @hidden Last computed particle rotation matrix
  64103. */
  64104. this._rotationMatrix = [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0];
  64105. /**
  64106. * Parent particle Id, if any.
  64107. * Default null.
  64108. */
  64109. this.parentId = null;
  64110. /**
  64111. * @hidden Internal global position in the SPS.
  64112. */
  64113. this._globalPosition = BABYLON.Vector3.Zero();
  64114. this.idx = particleIndex;
  64115. this._pos = positionIndex;
  64116. this._ind = indiceIndex;
  64117. this._model = model;
  64118. this.shapeId = shapeId;
  64119. this.idxInShape = idxInShape;
  64120. this._sps = sps;
  64121. if (modelBoundingInfo) {
  64122. this._modelBoundingInfo = modelBoundingInfo;
  64123. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  64124. }
  64125. }
  64126. Object.defineProperty(SolidParticle.prototype, "scale", {
  64127. /**
  64128. * Legacy support, changed scale to scaling
  64129. */
  64130. get: function () {
  64131. return this.scaling;
  64132. },
  64133. /**
  64134. * Legacy support, changed scale to scaling
  64135. */
  64136. set: function (scale) {
  64137. this.scaling = scale;
  64138. },
  64139. enumerable: true,
  64140. configurable: true
  64141. });
  64142. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  64143. /**
  64144. * Legacy support, changed quaternion to rotationQuaternion
  64145. */
  64146. get: function () {
  64147. return this.rotationQuaternion;
  64148. },
  64149. /**
  64150. * Legacy support, changed quaternion to rotationQuaternion
  64151. */
  64152. set: function (q) {
  64153. this.rotationQuaternion = q;
  64154. },
  64155. enumerable: true,
  64156. configurable: true
  64157. });
  64158. /**
  64159. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  64160. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  64161. * @param target is the object (solid particle or mesh) what the intersection is computed against.
  64162. * @returns true if it intersects
  64163. */
  64164. SolidParticle.prototype.intersectsMesh = function (target) {
  64165. if (!this._boundingInfo || !target._boundingInfo) {
  64166. return false;
  64167. }
  64168. if (this._sps._bSphereOnly) {
  64169. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  64170. }
  64171. return this._boundingInfo.intersects(target._boundingInfo, false);
  64172. };
  64173. return SolidParticle;
  64174. }());
  64175. BABYLON.SolidParticle = SolidParticle;
  64176. /**
  64177. * Represents the shape of the model used by one particle of a solid particle system.
  64178. * SPS internal tool, don't use it manually.
  64179. */
  64180. var ModelShape = /** @class */ (function () {
  64181. /**
  64182. * 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.
  64183. * SPS internal tool, don't use it manually.
  64184. * @hidden
  64185. */
  64186. function ModelShape(id, shape, indicesLength, shapeUV, posFunction, vtxFunction) {
  64187. /**
  64188. * length of the shape in the model indices array (internal use)
  64189. * @hidden
  64190. */
  64191. this._indicesLength = 0;
  64192. this.shapeID = id;
  64193. this._shape = shape;
  64194. this._indicesLength = indicesLength;
  64195. this._shapeUV = shapeUV;
  64196. this._positionFunction = posFunction;
  64197. this._vertexFunction = vtxFunction;
  64198. }
  64199. return ModelShape;
  64200. }());
  64201. BABYLON.ModelShape = ModelShape;
  64202. /**
  64203. * Represents a Depth Sorted Particle in the solid particle system.
  64204. */
  64205. var DepthSortedParticle = /** @class */ (function () {
  64206. function DepthSortedParticle() {
  64207. /**
  64208. * Index of the particle in the "indices" array
  64209. */
  64210. this.ind = 0;
  64211. /**
  64212. * Length of the particle shape in the "indices" array
  64213. */
  64214. this.indicesLength = 0;
  64215. /**
  64216. * Squared distance from the particle to the camera
  64217. */
  64218. this.sqDistance = 0.0;
  64219. }
  64220. return DepthSortedParticle;
  64221. }());
  64222. BABYLON.DepthSortedParticle = DepthSortedParticle;
  64223. })(BABYLON || (BABYLON = {}));
  64224. //# sourceMappingURL=babylon.solidParticle.js.map
  64225. var BABYLON;
  64226. (function (BABYLON) {
  64227. /**
  64228. * The SPS is a single updatable mesh. The solid particles are simply separate parts or faces fo this big mesh.
  64229. *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.
  64230. * The SPS is also a particle system. It provides some methods to manage the particles.
  64231. * However it is behavior agnostic. This means it has no emitter, no particle physics, no particle recycler. You have to implement your own behavior.
  64232. *
  64233. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  64234. */
  64235. var SolidParticleSystem = /** @class */ (function () {
  64236. /**
  64237. * Creates a SPS (Solid Particle System) object.
  64238. * @param name (String) is the SPS name, this will be the underlying mesh name.
  64239. * @param scene (Scene) is the scene in which the SPS is added.
  64240. * @param updatable (optional boolean, default true) : if the SPS must be updatable or immutable.
  64241. * @param isPickable (optional boolean, default false) : if the solid particles must be pickable.
  64242. * @param enableDepthSort (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.
  64243. * @param particleIntersection (optional boolean, default false) : if the solid particle intersections must be computed.
  64244. * @param boundingSphereOnly (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  64245. * @param bSphereRadiusFactor (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  64246. * @example bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  64247. */
  64248. function SolidParticleSystem(name, scene, options) {
  64249. /**
  64250. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  64251. * Example : var p = SPS.particles[i];
  64252. */
  64253. this.particles = new Array();
  64254. /**
  64255. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  64256. */
  64257. this.nbParticles = 0;
  64258. /**
  64259. * If the particles must ever face the camera (default false). Useful for planar particles.
  64260. */
  64261. this.billboard = false;
  64262. /**
  64263. * Recompute normals when adding a shape
  64264. */
  64265. this.recomputeNormals = true;
  64266. /**
  64267. * This a counter ofr your own usage. It's not set by any SPS functions.
  64268. */
  64269. this.counter = 0;
  64270. /**
  64271. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  64272. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  64273. */
  64274. this.vars = {};
  64275. /**
  64276. * If the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster). (Internal use only)
  64277. * @hidden
  64278. */
  64279. this._bSphereOnly = false;
  64280. /**
  64281. * A number to multiply the boundind sphere radius by in order to reduce it for instance. (Internal use only)
  64282. * @hidden
  64283. */
  64284. this._bSphereRadiusFactor = 1.0;
  64285. this._positions = new Array();
  64286. this._indices = new Array();
  64287. this._normals = new Array();
  64288. this._colors = new Array();
  64289. this._uvs = new Array();
  64290. this._index = 0; // indices index
  64291. this._updatable = true;
  64292. this._pickable = false;
  64293. this._isVisibilityBoxLocked = false;
  64294. this._alwaysVisible = false;
  64295. this._depthSort = false;
  64296. this._shapeCounter = 0;
  64297. this._copy = new BABYLON.SolidParticle(0, 0, 0, null, 0, 0, this);
  64298. this._color = new BABYLON.Color4(0, 0, 0, 0);
  64299. this._computeParticleColor = true;
  64300. this._computeParticleTexture = true;
  64301. this._computeParticleRotation = true;
  64302. this._computeParticleVertex = false;
  64303. this._computeBoundingBox = false;
  64304. this._depthSortParticles = true;
  64305. this._cam_axisZ = BABYLON.Vector3.Zero();
  64306. this._cam_axisY = BABYLON.Vector3.Zero();
  64307. this._cam_axisX = BABYLON.Vector3.Zero();
  64308. this._axisZ = BABYLON.Axis.Z;
  64309. this._camDir = BABYLON.Vector3.Zero();
  64310. this._camInvertedPosition = BABYLON.Vector3.Zero();
  64311. this._rotMatrix = new BABYLON.Matrix();
  64312. this._invertMatrix = new BABYLON.Matrix();
  64313. this._rotated = BABYLON.Vector3.Zero();
  64314. this._quaternion = new BABYLON.Quaternion();
  64315. this._vertex = BABYLON.Vector3.Zero();
  64316. this._normal = BABYLON.Vector3.Zero();
  64317. this._yaw = 0.0;
  64318. this._pitch = 0.0;
  64319. this._roll = 0.0;
  64320. this._halfroll = 0.0;
  64321. this._halfpitch = 0.0;
  64322. this._halfyaw = 0.0;
  64323. this._sinRoll = 0.0;
  64324. this._cosRoll = 0.0;
  64325. this._sinPitch = 0.0;
  64326. this._cosPitch = 0.0;
  64327. this._sinYaw = 0.0;
  64328. this._cosYaw = 0.0;
  64329. this._mustUnrotateFixedNormals = false;
  64330. this._minimum = BABYLON.Vector3.Zero();
  64331. this._maximum = BABYLON.Vector3.Zero();
  64332. this._minBbox = BABYLON.Vector3.Zero();
  64333. this._maxBbox = BABYLON.Vector3.Zero();
  64334. this._particlesIntersect = false;
  64335. this._depthSortFunction = function (p1, p2) {
  64336. return (p2.sqDistance - p1.sqDistance);
  64337. };
  64338. this._needs32Bits = false;
  64339. this._pivotBackTranslation = BABYLON.Vector3.Zero();
  64340. this._scaledPivot = BABYLON.Vector3.Zero();
  64341. this._particleHasParent = false;
  64342. this.name = name;
  64343. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  64344. this._camera = scene.activeCamera;
  64345. this._pickable = options ? options.isPickable : false;
  64346. this._depthSort = options ? options.enableDepthSort : false;
  64347. this._particlesIntersect = options ? options.particleIntersection : false;
  64348. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  64349. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  64350. if (options && options.updatable !== undefined) {
  64351. this._updatable = options.updatable;
  64352. }
  64353. else {
  64354. this._updatable = true;
  64355. }
  64356. if (this._pickable) {
  64357. this.pickedParticles = [];
  64358. }
  64359. if (this._depthSort) {
  64360. this.depthSortedParticles = [];
  64361. }
  64362. }
  64363. /**
  64364. * Builds the SPS underlying mesh. Returns a standard Mesh.
  64365. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  64366. * @returns the created mesh
  64367. */
  64368. SolidParticleSystem.prototype.buildMesh = function () {
  64369. if (this.nbParticles === 0) {
  64370. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  64371. this.addShape(triangle, 1);
  64372. triangle.dispose();
  64373. }
  64374. this._indices32 = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices);
  64375. this._positions32 = new Float32Array(this._positions);
  64376. this._uvs32 = new Float32Array(this._uvs);
  64377. this._colors32 = new Float32Array(this._colors);
  64378. if (this.recomputeNormals) {
  64379. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals);
  64380. }
  64381. this._normals32 = new Float32Array(this._normals);
  64382. this._fixedNormal32 = new Float32Array(this._normals);
  64383. if (this._mustUnrotateFixedNormals) { // the particles could be created already rotated in the mesh with a positionFunction
  64384. this._unrotateFixedNormals();
  64385. }
  64386. var vertexData = new BABYLON.VertexData();
  64387. vertexData.indices = (this._depthSort) ? this._indices : this._indices32;
  64388. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  64389. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  64390. if (this._uvs32.length > 0) {
  64391. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  64392. }
  64393. if (this._colors32.length > 0) {
  64394. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  64395. }
  64396. var mesh = new BABYLON.Mesh(this.name, this._scene);
  64397. vertexData.applyToMesh(mesh, this._updatable);
  64398. this.mesh = mesh;
  64399. this.mesh.isPickable = this._pickable;
  64400. // free memory
  64401. if (!this._depthSort) {
  64402. this._indices = null;
  64403. }
  64404. this._positions = null;
  64405. this._normals = null;
  64406. this._uvs = null;
  64407. this._colors = null;
  64408. if (!this._updatable) {
  64409. this.particles.length = 0;
  64410. }
  64411. return mesh;
  64412. };
  64413. /**
  64414. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  64415. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  64416. * Thus the particles generated from `digest()` have their property `position` set yet.
  64417. * @param mesh ( Mesh ) is the mesh to be digested
  64418. * @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
  64419. * {delta} (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  64420. * {number} (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  64421. * @returns the current SPS
  64422. */
  64423. SolidParticleSystem.prototype.digest = function (mesh, options) {
  64424. var size = (options && options.facetNb) || 1;
  64425. var number = (options && options.number) || 0;
  64426. var delta = (options && options.delta) || 0;
  64427. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  64428. var meshInd = mesh.getIndices();
  64429. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  64430. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  64431. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  64432. var f = 0; // facet counter
  64433. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  64434. // compute size from number
  64435. if (number) {
  64436. number = (number > totalFacets) ? totalFacets : number;
  64437. size = Math.round(totalFacets / number);
  64438. delta = 0;
  64439. }
  64440. else {
  64441. size = (size > totalFacets) ? totalFacets : size;
  64442. }
  64443. var facetPos = []; // submesh positions
  64444. var facetInd = []; // submesh indices
  64445. var facetUV = []; // submesh UV
  64446. var facetCol = []; // submesh colors
  64447. var barycenter = BABYLON.Vector3.Zero();
  64448. var sizeO = size;
  64449. while (f < totalFacets) {
  64450. size = sizeO + Math.floor((1 + delta) * Math.random());
  64451. if (f > totalFacets - size) {
  64452. size = totalFacets - f;
  64453. }
  64454. // reset temp arrays
  64455. facetPos.length = 0;
  64456. facetInd.length = 0;
  64457. facetUV.length = 0;
  64458. facetCol.length = 0;
  64459. // iterate over "size" facets
  64460. var fi = 0;
  64461. for (var j = f * 3; j < (f + size) * 3; j++) {
  64462. facetInd.push(fi);
  64463. var i = meshInd[j];
  64464. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  64465. if (meshUV) {
  64466. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  64467. }
  64468. if (meshCol) {
  64469. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  64470. }
  64471. fi++;
  64472. }
  64473. // create a model shape for each single particle
  64474. var idx = this.nbParticles;
  64475. var shape = this._posToShape(facetPos);
  64476. var shapeUV = this._uvsToShapeUV(facetUV);
  64477. // compute the barycenter of the shape
  64478. var v;
  64479. for (v = 0; v < shape.length; v++) {
  64480. barycenter.addInPlace(shape[v]);
  64481. }
  64482. barycenter.scaleInPlace(1 / shape.length);
  64483. // shift the shape from its barycenter to the origin
  64484. for (v = 0; v < shape.length; v++) {
  64485. shape[v].subtractInPlace(barycenter);
  64486. }
  64487. var bInfo;
  64488. if (this._particlesIntersect) {
  64489. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  64490. }
  64491. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, size * 3, shapeUV, null, null);
  64492. // add the particle in the SPS
  64493. var currentPos = this._positions.length;
  64494. var currentInd = this._indices.length;
  64495. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  64496. this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo);
  64497. // initialize the particle position
  64498. this.particles[this.nbParticles].position.addInPlace(barycenter);
  64499. this._index += shape.length;
  64500. idx++;
  64501. this.nbParticles++;
  64502. this._shapeCounter++;
  64503. f += size;
  64504. }
  64505. return this;
  64506. };
  64507. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  64508. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  64509. var index = 0;
  64510. var idx = 0;
  64511. for (var p = 0; p < this.particles.length; p++) {
  64512. this._particle = this.particles[p];
  64513. this._shape = this._particle._model._shape;
  64514. if (this._particle.rotationQuaternion) {
  64515. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  64516. }
  64517. else {
  64518. this._yaw = this._particle.rotation.y;
  64519. this._pitch = this._particle.rotation.x;
  64520. this._roll = this._particle.rotation.z;
  64521. this._quaternionRotationYPR();
  64522. }
  64523. this._quaternionToRotationMatrix();
  64524. this._rotMatrix.invertToRef(this._invertMatrix);
  64525. for (var pt = 0; pt < this._shape.length; pt++) {
  64526. idx = index + pt * 3;
  64527. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  64528. this._fixedNormal32[idx] = this._normal.x;
  64529. this._fixedNormal32[idx + 1] = this._normal.y;
  64530. this._fixedNormal32[idx + 2] = this._normal.z;
  64531. }
  64532. index = idx + 3;
  64533. }
  64534. };
  64535. //reset copy
  64536. SolidParticleSystem.prototype._resetCopy = function () {
  64537. this._copy.position.x = 0;
  64538. this._copy.position.y = 0;
  64539. this._copy.position.z = 0;
  64540. this._copy.rotation.x = 0;
  64541. this._copy.rotation.y = 0;
  64542. this._copy.rotation.z = 0;
  64543. this._copy.rotationQuaternion = null;
  64544. this._copy.scaling.x = 1.0;
  64545. this._copy.scaling.y = 1.0;
  64546. this._copy.scaling.z = 1.0;
  64547. this._copy.uvs.x = 0;
  64548. this._copy.uvs.y = 0;
  64549. this._copy.uvs.z = 1.0;
  64550. this._copy.uvs.w = 1.0;
  64551. this._copy.color = null;
  64552. this._copy.translateFromPivot = false;
  64553. };
  64554. // _meshBuilder : inserts the shape model in the global SPS mesh
  64555. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  64556. var i;
  64557. var u = 0;
  64558. var c = 0;
  64559. var n = 0;
  64560. this._resetCopy();
  64561. if (options && options.positionFunction) { // call to custom positionFunction
  64562. options.positionFunction(this._copy, idx, idxInShape);
  64563. this._mustUnrotateFixedNormals = true;
  64564. }
  64565. if (this._copy.rotationQuaternion) {
  64566. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  64567. }
  64568. else {
  64569. this._yaw = this._copy.rotation.y;
  64570. this._pitch = this._copy.rotation.x;
  64571. this._roll = this._copy.rotation.z;
  64572. this._quaternionRotationYPR();
  64573. }
  64574. this._quaternionToRotationMatrix();
  64575. this._scaledPivot.x = this._copy.pivot.x * this._copy.scaling.x;
  64576. this._scaledPivot.y = this._copy.pivot.y * this._copy.scaling.y;
  64577. this._scaledPivot.z = this._copy.pivot.z * this._copy.scaling.z;
  64578. if (this._copy.translateFromPivot) {
  64579. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  64580. }
  64581. else {
  64582. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  64583. }
  64584. for (i = 0; i < shape.length; i++) {
  64585. this._vertex.x = shape[i].x;
  64586. this._vertex.y = shape[i].y;
  64587. this._vertex.z = shape[i].z;
  64588. if (options && options.vertexFunction) {
  64589. options.vertexFunction(this._copy, this._vertex, i);
  64590. }
  64591. this._vertex.x *= this._copy.scaling.x;
  64592. this._vertex.y *= this._copy.scaling.y;
  64593. this._vertex.z *= this._copy.scaling.z;
  64594. this._vertex.x -= this._scaledPivot.x;
  64595. this._vertex.y -= this._scaledPivot.y;
  64596. this._vertex.z -= this._scaledPivot.z;
  64597. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  64598. this._rotated.addInPlace(this._pivotBackTranslation);
  64599. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  64600. if (meshUV) {
  64601. 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);
  64602. u += 2;
  64603. }
  64604. if (this._copy.color) {
  64605. this._color = this._copy.color;
  64606. }
  64607. else if (meshCol && meshCol[c] !== undefined) {
  64608. this._color.r = meshCol[c];
  64609. this._color.g = meshCol[c + 1];
  64610. this._color.b = meshCol[c + 2];
  64611. this._color.a = meshCol[c + 3];
  64612. }
  64613. else {
  64614. this._color.r = 1.0;
  64615. this._color.g = 1.0;
  64616. this._color.b = 1.0;
  64617. this._color.a = 1.0;
  64618. }
  64619. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  64620. c += 4;
  64621. if (!this.recomputeNormals && meshNor) {
  64622. this._normal.x = meshNor[n];
  64623. this._normal.y = meshNor[n + 1];
  64624. this._normal.z = meshNor[n + 2];
  64625. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  64626. normals.push(this._normal.x, this._normal.y, this._normal.z);
  64627. n += 3;
  64628. }
  64629. }
  64630. for (i = 0; i < meshInd.length; i++) {
  64631. var current_ind = p + meshInd[i];
  64632. indices.push(current_ind);
  64633. if (current_ind > 65535) {
  64634. this._needs32Bits = true;
  64635. }
  64636. }
  64637. if (this._pickable) {
  64638. var nbfaces = meshInd.length / 3;
  64639. for (i = 0; i < nbfaces; i++) {
  64640. this.pickedParticles.push({ idx: idx, faceId: i });
  64641. }
  64642. }
  64643. if (this._depthSort) {
  64644. this.depthSortedParticles.push(new BABYLON.DepthSortedParticle());
  64645. }
  64646. return this._copy;
  64647. };
  64648. // returns a shape array from positions array
  64649. SolidParticleSystem.prototype._posToShape = function (positions) {
  64650. var shape = [];
  64651. for (var i = 0; i < positions.length; i += 3) {
  64652. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  64653. }
  64654. return shape;
  64655. };
  64656. // returns a shapeUV array from a Vector4 uvs
  64657. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  64658. var shapeUV = [];
  64659. if (uvs) {
  64660. for (var i = 0; i < uvs.length; i++)
  64661. shapeUV.push(uvs[i]);
  64662. }
  64663. return shapeUV;
  64664. };
  64665. // adds a new particle object in the particles array
  64666. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, idxind, model, shapeId, idxInShape, bInfo) {
  64667. if (bInfo === void 0) { bInfo = null; }
  64668. var sp = new BABYLON.SolidParticle(idx, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);
  64669. this.particles.push(sp);
  64670. return sp;
  64671. };
  64672. /**
  64673. * Adds some particles to the SPS from the model shape. Returns the shape id.
  64674. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  64675. * @param mesh is any Mesh object that will be used as a model for the solid particles.
  64676. * @param nb (positive integer) the number of particles to be created from this model
  64677. * @param options {positionFunction} is an optional javascript function to called for each particle on SPS creation.
  64678. * {vertexFunction} is an optional javascript function to called for each vertex of each particle on SPS creation
  64679. * @returns the number of shapes in the system
  64680. */
  64681. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  64682. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  64683. var meshInd = mesh.getIndices();
  64684. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  64685. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  64686. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  64687. var bbInfo;
  64688. if (this._particlesIntersect) {
  64689. bbInfo = mesh.getBoundingInfo();
  64690. }
  64691. var shape = this._posToShape(meshPos);
  64692. var shapeUV = this._uvsToShapeUV(meshUV);
  64693. var posfunc = options ? options.positionFunction : null;
  64694. var vtxfunc = options ? options.vertexFunction : null;
  64695. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, meshInd.length, shapeUV, posfunc, vtxfunc);
  64696. // particles
  64697. var sp;
  64698. var currentCopy;
  64699. var idx = this.nbParticles;
  64700. for (var i = 0; i < nb; i++) {
  64701. var currentPos = this._positions.length;
  64702. var currentInd = this._indices.length;
  64703. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  64704. if (this._updatable) {
  64705. sp = this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo);
  64706. sp.position.copyFrom(currentCopy.position);
  64707. sp.rotation.copyFrom(currentCopy.rotation);
  64708. if (currentCopy.rotationQuaternion && sp.rotationQuaternion) {
  64709. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  64710. }
  64711. if (currentCopy.color && sp.color) {
  64712. sp.color.copyFrom(currentCopy.color);
  64713. }
  64714. sp.scaling.copyFrom(currentCopy.scaling);
  64715. sp.uvs.copyFrom(currentCopy.uvs);
  64716. }
  64717. this._index += shape.length;
  64718. idx++;
  64719. }
  64720. this.nbParticles += nb;
  64721. this._shapeCounter++;
  64722. return this._shapeCounter - 1;
  64723. };
  64724. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  64725. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  64726. this._resetCopy();
  64727. if (particle._model._positionFunction) { // recall to stored custom positionFunction
  64728. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  64729. }
  64730. if (this._copy.rotationQuaternion) {
  64731. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  64732. }
  64733. else {
  64734. this._yaw = this._copy.rotation.y;
  64735. this._pitch = this._copy.rotation.x;
  64736. this._roll = this._copy.rotation.z;
  64737. this._quaternionRotationYPR();
  64738. }
  64739. this._quaternionToRotationMatrix();
  64740. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  64741. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  64742. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  64743. if (this._copy.translateFromPivot) {
  64744. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  64745. }
  64746. else {
  64747. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  64748. }
  64749. this._shape = particle._model._shape;
  64750. for (var pt = 0; pt < this._shape.length; pt++) {
  64751. this._vertex.x = this._shape[pt].x;
  64752. this._vertex.y = this._shape[pt].y;
  64753. this._vertex.z = this._shape[pt].z;
  64754. if (particle._model._vertexFunction) {
  64755. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  64756. }
  64757. this._vertex.x *= this._copy.scaling.x;
  64758. this._vertex.y *= this._copy.scaling.y;
  64759. this._vertex.z *= this._copy.scaling.z;
  64760. this._vertex.x -= this._scaledPivot.x;
  64761. this._vertex.y -= this._scaledPivot.y;
  64762. this._vertex.z -= this._scaledPivot.z;
  64763. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  64764. this._rotated.addInPlace(this._pivotBackTranslation);
  64765. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  64766. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  64767. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  64768. }
  64769. particle.position.x = 0.0;
  64770. particle.position.y = 0.0;
  64771. particle.position.z = 0.0;
  64772. particle.rotation.x = 0.0;
  64773. particle.rotation.y = 0.0;
  64774. particle.rotation.z = 0.0;
  64775. particle.rotationQuaternion = null;
  64776. particle.scaling.x = 1.0;
  64777. particle.scaling.y = 1.0;
  64778. particle.scaling.z = 1.0;
  64779. particle.uvs.x = 0.0;
  64780. particle.uvs.y = 0.0;
  64781. particle.uvs.z = 1.0;
  64782. particle.uvs.w = 1.0;
  64783. particle.pivot.x = 0.0;
  64784. particle.pivot.y = 0.0;
  64785. particle.pivot.z = 0.0;
  64786. particle.translateFromPivot = false;
  64787. particle.parentId = null;
  64788. };
  64789. /**
  64790. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  64791. * @returns the SPS.
  64792. */
  64793. SolidParticleSystem.prototype.rebuildMesh = function () {
  64794. for (var p = 0; p < this.particles.length; p++) {
  64795. this._rebuildParticle(this.particles[p]);
  64796. }
  64797. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  64798. return this;
  64799. };
  64800. /**
  64801. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  64802. * This method calls `updateParticle()` for each particle of the SPS.
  64803. * For an animated SPS, it is usually called within the render loop.
  64804. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  64805. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  64806. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  64807. * @returns the SPS.
  64808. */
  64809. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  64810. if (start === void 0) { start = 0; }
  64811. if (end === void 0) { end = this.nbParticles - 1; }
  64812. if (update === void 0) { update = true; }
  64813. if (!this._updatable) {
  64814. return this;
  64815. }
  64816. // custom beforeUpdate
  64817. this.beforeUpdateParticles(start, end, update);
  64818. this._cam_axisX.x = 1.0;
  64819. this._cam_axisX.y = 0.0;
  64820. this._cam_axisX.z = 0.0;
  64821. this._cam_axisY.x = 0.0;
  64822. this._cam_axisY.y = 1.0;
  64823. this._cam_axisY.z = 0.0;
  64824. this._cam_axisZ.x = 0.0;
  64825. this._cam_axisZ.y = 0.0;
  64826. this._cam_axisZ.z = 1.0;
  64827. // cases when the World Matrix is to be computed first
  64828. if (this.billboard || this._depthSort) {
  64829. this.mesh.computeWorldMatrix(true);
  64830. this.mesh._worldMatrix.invertToRef(this._invertMatrix);
  64831. }
  64832. // if the particles will always face the camera
  64833. if (this.billboard) {
  64834. // compute the camera position and un-rotate it by the current mesh rotation
  64835. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  64836. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  64837. this._cam_axisZ.normalize();
  64838. // same for camera up vector extracted from the cam view matrix
  64839. var view = this._camera.getViewMatrix(true);
  64840. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  64841. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  64842. this._cam_axisY.normalize();
  64843. this._cam_axisX.normalize();
  64844. }
  64845. // if depthSort, compute the camera global position in the mesh local system
  64846. if (this._depthSort) {
  64847. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._camInvertedPosition); // then un-rotate the camera
  64848. }
  64849. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  64850. var idx = 0; // current position index in the global array positions32
  64851. var index = 0; // position start index in the global array positions32 of the current particle
  64852. var colidx = 0; // current color index in the global array colors32
  64853. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  64854. var uvidx = 0; // current uv index in the global array uvs32
  64855. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  64856. var pt = 0; // current index in the particle model shape
  64857. if (this.mesh.isFacetDataEnabled) {
  64858. this._computeBoundingBox = true;
  64859. }
  64860. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  64861. if (this._computeBoundingBox) {
  64862. if (start == 0 && end == this.nbParticles - 1) { // all the particles are updated, then recompute the BBox from scratch
  64863. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  64864. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  64865. }
  64866. else { // only some particles are updated, then use the current existing BBox basis. Note : it can only increase.
  64867. if (this.mesh._boundingInfo) {
  64868. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  64869. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  64870. }
  64871. }
  64872. }
  64873. // particle loop
  64874. index = this.particles[start]._pos;
  64875. var vpos = (index / 3) | 0;
  64876. colorIndex = vpos * 4;
  64877. uvIndex = vpos * 2;
  64878. for (var p = start; p <= end; p++) {
  64879. this._particle = this.particles[p];
  64880. this._shape = this._particle._model._shape;
  64881. this._shapeUV = this._particle._model._shapeUV;
  64882. // call to custom user function to update the particle properties
  64883. this.updateParticle(this._particle);
  64884. // camera-particle distance for depth sorting
  64885. if (this._depthSort && this._depthSortParticles) {
  64886. var dsp = this.depthSortedParticles[p];
  64887. dsp.ind = this._particle._ind;
  64888. dsp.indicesLength = this._particle._model._indicesLength;
  64889. dsp.sqDistance = BABYLON.Vector3.DistanceSquared(this._particle.position, this._camInvertedPosition);
  64890. }
  64891. // skip the computations for inactive or already invisible particles
  64892. if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {
  64893. // increment indexes for the next particle
  64894. pt = this._shape.length;
  64895. index += pt * 3;
  64896. colorIndex += pt * 4;
  64897. uvIndex += pt * 2;
  64898. continue;
  64899. }
  64900. if (this._particle.isVisible) {
  64901. this._particle._stillInvisible = false; // un-mark permanent invisibility
  64902. this._particleHasParent = (this._particle.parentId !== null);
  64903. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  64904. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  64905. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  64906. // particle rotation matrix
  64907. if (this.billboard) {
  64908. this._particle.rotation.x = 0.0;
  64909. this._particle.rotation.y = 0.0;
  64910. }
  64911. if (this._computeParticleRotation || this.billboard) {
  64912. if (this._particle.rotationQuaternion) {
  64913. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  64914. }
  64915. else {
  64916. this._yaw = this._particle.rotation.y;
  64917. this._pitch = this._particle.rotation.x;
  64918. this._roll = this._particle.rotation.z;
  64919. this._quaternionRotationYPR();
  64920. }
  64921. this._quaternionToRotationMatrix();
  64922. }
  64923. if (this._particleHasParent) {
  64924. this._parent = this.particles[this._particle.parentId];
  64925. 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];
  64926. 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];
  64927. 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];
  64928. this._particle._globalPosition.x = this._parent._globalPosition.x + this._rotated.x;
  64929. this._particle._globalPosition.y = this._parent._globalPosition.y + this._rotated.y;
  64930. this._particle._globalPosition.z = this._parent._globalPosition.z + this._rotated.z;
  64931. if (this._computeParticleRotation || this.billboard) {
  64932. 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];
  64933. 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];
  64934. 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];
  64935. 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];
  64936. 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];
  64937. 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];
  64938. 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];
  64939. 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];
  64940. 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];
  64941. }
  64942. }
  64943. else {
  64944. this._particle._globalPosition.x = this._particle.position.x;
  64945. this._particle._globalPosition.y = this._particle.position.y;
  64946. this._particle._globalPosition.z = this._particle.position.z;
  64947. if (this._computeParticleRotation || this.billboard) {
  64948. this._particle._rotationMatrix[0] = this._rotMatrix.m[0];
  64949. this._particle._rotationMatrix[1] = this._rotMatrix.m[1];
  64950. this._particle._rotationMatrix[2] = this._rotMatrix.m[2];
  64951. this._particle._rotationMatrix[3] = this._rotMatrix.m[4];
  64952. this._particle._rotationMatrix[4] = this._rotMatrix.m[5];
  64953. this._particle._rotationMatrix[5] = this._rotMatrix.m[6];
  64954. this._particle._rotationMatrix[6] = this._rotMatrix.m[8];
  64955. this._particle._rotationMatrix[7] = this._rotMatrix.m[9];
  64956. this._particle._rotationMatrix[8] = this._rotMatrix.m[10];
  64957. }
  64958. }
  64959. if (this._particle.translateFromPivot) {
  64960. this._pivotBackTranslation.x = 0.0;
  64961. this._pivotBackTranslation.y = 0.0;
  64962. this._pivotBackTranslation.z = 0.0;
  64963. }
  64964. else {
  64965. this._pivotBackTranslation.x = this._scaledPivot.x;
  64966. this._pivotBackTranslation.y = this._scaledPivot.y;
  64967. this._pivotBackTranslation.z = this._scaledPivot.z;
  64968. }
  64969. // particle vertex loop
  64970. for (pt = 0; pt < this._shape.length; pt++) {
  64971. idx = index + pt * 3;
  64972. colidx = colorIndex + pt * 4;
  64973. uvidx = uvIndex + pt * 2;
  64974. this._vertex.x = this._shape[pt].x;
  64975. this._vertex.y = this._shape[pt].y;
  64976. this._vertex.z = this._shape[pt].z;
  64977. if (this._computeParticleVertex) {
  64978. this.updateParticleVertex(this._particle, this._vertex, pt);
  64979. }
  64980. // positions
  64981. this._vertex.x *= this._particle.scaling.x;
  64982. this._vertex.y *= this._particle.scaling.y;
  64983. this._vertex.z *= this._particle.scaling.z;
  64984. this._vertex.x -= this._scaledPivot.x;
  64985. this._vertex.y -= this._scaledPivot.y;
  64986. this._vertex.z -= this._scaledPivot.z;
  64987. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  64988. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  64989. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  64990. this._rotated.x += this._pivotBackTranslation.x;
  64991. this._rotated.y += this._pivotBackTranslation.y;
  64992. this._rotated.z += this._pivotBackTranslation.z;
  64993. 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;
  64994. 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;
  64995. 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;
  64996. if (this._computeBoundingBox) {
  64997. if (this._positions32[idx] < this._minimum.x) {
  64998. this._minimum.x = this._positions32[idx];
  64999. }
  65000. if (this._positions32[idx] > this._maximum.x) {
  65001. this._maximum.x = this._positions32[idx];
  65002. }
  65003. if (this._positions32[idx + 1] < this._minimum.y) {
  65004. this._minimum.y = this._positions32[idx + 1];
  65005. }
  65006. if (this._positions32[idx + 1] > this._maximum.y) {
  65007. this._maximum.y = this._positions32[idx + 1];
  65008. }
  65009. if (this._positions32[idx + 2] < this._minimum.z) {
  65010. this._minimum.z = this._positions32[idx + 2];
  65011. }
  65012. if (this._positions32[idx + 2] > this._maximum.z) {
  65013. this._maximum.z = this._positions32[idx + 2];
  65014. }
  65015. }
  65016. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  65017. if (!this._computeParticleVertex) {
  65018. this._normal.x = this._fixedNormal32[idx];
  65019. this._normal.y = this._fixedNormal32[idx + 1];
  65020. this._normal.z = this._fixedNormal32[idx + 2];
  65021. this._rotated.x = this._normal.x * this._particle._rotationMatrix[0] + this._normal.y * this._particle._rotationMatrix[3] + this._normal.z * this._particle._rotationMatrix[6];
  65022. this._rotated.y = this._normal.x * this._particle._rotationMatrix[1] + this._normal.y * this._particle._rotationMatrix[4] + this._normal.z * this._particle._rotationMatrix[7];
  65023. this._rotated.z = this._normal.x * this._particle._rotationMatrix[2] + this._normal.y * this._particle._rotationMatrix[5] + this._normal.z * this._particle._rotationMatrix[8];
  65024. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  65025. 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;
  65026. 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;
  65027. }
  65028. if (this._computeParticleColor && this._particle.color) {
  65029. this._colors32[colidx] = this._particle.color.r;
  65030. this._colors32[colidx + 1] = this._particle.color.g;
  65031. this._colors32[colidx + 2] = this._particle.color.b;
  65032. this._colors32[colidx + 3] = this._particle.color.a;
  65033. }
  65034. if (this._computeParticleTexture) {
  65035. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  65036. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  65037. }
  65038. }
  65039. }
  65040. // particle just set invisible : scaled to zero and positioned at the origin
  65041. else {
  65042. this._particle._stillInvisible = true; // mark the particle as invisible
  65043. for (pt = 0; pt < this._shape.length; pt++) {
  65044. idx = index + pt * 3;
  65045. colidx = colorIndex + pt * 4;
  65046. uvidx = uvIndex + pt * 2;
  65047. this._positions32[idx] = 0.0;
  65048. this._positions32[idx + 1] = 0.0;
  65049. this._positions32[idx + 2] = 0.0;
  65050. this._normals32[idx] = 0.0;
  65051. this._normals32[idx + 1] = 0.0;
  65052. this._normals32[idx + 2] = 0.0;
  65053. if (this._computeParticleColor && this._particle.color) {
  65054. this._colors32[colidx] = this._particle.color.r;
  65055. this._colors32[colidx + 1] = this._particle.color.g;
  65056. this._colors32[colidx + 2] = this._particle.color.b;
  65057. this._colors32[colidx + 3] = this._particle.color.a;
  65058. }
  65059. if (this._computeParticleTexture) {
  65060. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  65061. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  65062. }
  65063. }
  65064. }
  65065. // if the particle intersections must be computed : update the bbInfo
  65066. if (this._particlesIntersect) {
  65067. var bInfo = this._particle._boundingInfo;
  65068. var bBox = bInfo.boundingBox;
  65069. var bSphere = bInfo.boundingSphere;
  65070. if (!this._bSphereOnly) {
  65071. // place, scale and rotate the particle bbox within the SPS local system, then update it
  65072. for (var b = 0; b < bBox.vectors.length; b++) {
  65073. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  65074. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  65075. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  65076. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  65077. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  65078. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  65079. 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;
  65080. 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;
  65081. 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;
  65082. }
  65083. bBox._update(this.mesh._worldMatrix);
  65084. }
  65085. // place and scale the particle bouding sphere in the SPS local system, then update it
  65086. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  65087. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  65088. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  65089. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  65090. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  65091. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  65092. bSphere.center.x = this._particle._globalPosition.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  65093. bSphere.center.y = this._particle._globalPosition.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  65094. bSphere.center.z = this._particle._globalPosition.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  65095. 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));
  65096. bSphere._update(this.mesh._worldMatrix);
  65097. }
  65098. // increment indexes for the next particle
  65099. index = idx + 3;
  65100. colorIndex = colidx + 4;
  65101. uvIndex = uvidx + 2;
  65102. }
  65103. // if the VBO must be updated
  65104. if (update) {
  65105. if (this._computeParticleColor) {
  65106. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  65107. }
  65108. if (this._computeParticleTexture) {
  65109. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  65110. }
  65111. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  65112. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  65113. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  65114. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  65115. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  65116. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals32, params);
  65117. for (var i = 0; i < this._normals32.length; i++) {
  65118. this._fixedNormal32[i] = this._normals32[i];
  65119. }
  65120. }
  65121. if (!this.mesh.areNormalsFrozen) {
  65122. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  65123. }
  65124. }
  65125. if (this._depthSort && this._depthSortParticles) {
  65126. this.depthSortedParticles.sort(this._depthSortFunction);
  65127. var dspl = this.depthSortedParticles.length;
  65128. var sorted = 0;
  65129. var lind = 0;
  65130. var sind = 0;
  65131. var sid = 0;
  65132. for (sorted = 0; sorted < dspl; sorted++) {
  65133. lind = this.depthSortedParticles[sorted].indicesLength;
  65134. sind = this.depthSortedParticles[sorted].ind;
  65135. for (var i = 0; i < lind; i++) {
  65136. this._indices32[sid] = this._indices[sind + i];
  65137. sid++;
  65138. }
  65139. }
  65140. this.mesh.updateIndices(this._indices32);
  65141. }
  65142. }
  65143. if (this._computeBoundingBox) {
  65144. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  65145. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  65146. }
  65147. this.afterUpdateParticles(start, end, update);
  65148. return this;
  65149. };
  65150. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  65151. this._halfroll = this._roll * 0.5;
  65152. this._halfpitch = this._pitch * 0.5;
  65153. this._halfyaw = this._yaw * 0.5;
  65154. this._sinRoll = Math.sin(this._halfroll);
  65155. this._cosRoll = Math.cos(this._halfroll);
  65156. this._sinPitch = Math.sin(this._halfpitch);
  65157. this._cosPitch = Math.cos(this._halfpitch);
  65158. this._sinYaw = Math.sin(this._halfyaw);
  65159. this._cosYaw = Math.cos(this._halfyaw);
  65160. this._quaternion.x = this._cosYaw * this._sinPitch * this._cosRoll + this._sinYaw * this._cosPitch * this._sinRoll;
  65161. this._quaternion.y = this._sinYaw * this._cosPitch * this._cosRoll - this._cosYaw * this._sinPitch * this._sinRoll;
  65162. this._quaternion.z = this._cosYaw * this._cosPitch * this._sinRoll - this._sinYaw * this._sinPitch * this._cosRoll;
  65163. this._quaternion.w = this._cosYaw * this._cosPitch * this._cosRoll + this._sinYaw * this._sinPitch * this._sinRoll;
  65164. };
  65165. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  65166. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  65167. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  65168. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  65169. this._rotMatrix.m[3] = 0;
  65170. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  65171. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  65172. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  65173. this._rotMatrix.m[7] = 0;
  65174. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  65175. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  65176. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  65177. this._rotMatrix.m[11] = 0;
  65178. this._rotMatrix.m[12] = 0;
  65179. this._rotMatrix.m[13] = 0;
  65180. this._rotMatrix.m[14] = 0;
  65181. this._rotMatrix.m[15] = 1.0;
  65182. };
  65183. /**
  65184. * Disposes the SPS.
  65185. */
  65186. SolidParticleSystem.prototype.dispose = function () {
  65187. this.mesh.dispose();
  65188. this.vars = null;
  65189. // drop references to internal big arrays for the GC
  65190. this._positions = null;
  65191. this._indices = null;
  65192. this._normals = null;
  65193. this._uvs = null;
  65194. this._colors = null;
  65195. this._indices32 = null;
  65196. this._positions32 = null;
  65197. this._normals32 = null;
  65198. this._fixedNormal32 = null;
  65199. this._uvs32 = null;
  65200. this._colors32 = null;
  65201. this.pickedParticles = null;
  65202. };
  65203. /**
  65204. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  65205. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  65206. * @returns the SPS.
  65207. */
  65208. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  65209. if (!this._isVisibilityBoxLocked) {
  65210. this.mesh.refreshBoundingInfo();
  65211. }
  65212. return this;
  65213. };
  65214. /**
  65215. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  65216. * @param size the size (float) of the visibility box
  65217. * note : this doesn't lock the SPS mesh bounding box.
  65218. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  65219. */
  65220. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  65221. var vis = size / 2;
  65222. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  65223. };
  65224. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  65225. /**
  65226. * Gets whether the SPS as always visible or not
  65227. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  65228. */
  65229. get: function () {
  65230. return this._alwaysVisible;
  65231. },
  65232. /**
  65233. * Sets the SPS as always visible or not
  65234. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  65235. */
  65236. set: function (val) {
  65237. this._alwaysVisible = val;
  65238. this.mesh.alwaysSelectAsActiveMesh = val;
  65239. },
  65240. enumerable: true,
  65241. configurable: true
  65242. });
  65243. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  65244. /**
  65245. * Gets if the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  65246. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  65247. */
  65248. get: function () {
  65249. return this._isVisibilityBoxLocked;
  65250. },
  65251. /**
  65252. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  65253. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  65254. */
  65255. set: function (val) {
  65256. this._isVisibilityBoxLocked = val;
  65257. var boundingInfo = this.mesh.getBoundingInfo();
  65258. boundingInfo.isLocked = val;
  65259. },
  65260. enumerable: true,
  65261. configurable: true
  65262. });
  65263. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  65264. /**
  65265. * Gets if `setParticles()` computes the particle rotations or not.
  65266. * Default value : true. The SPS is faster when it's set to false.
  65267. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  65268. */
  65269. get: function () {
  65270. return this._computeParticleRotation;
  65271. },
  65272. /**
  65273. * Tells to `setParticles()` to compute the particle rotations or not.
  65274. * Default value : true. The SPS is faster when it's set to false.
  65275. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  65276. */
  65277. set: function (val) {
  65278. this._computeParticleRotation = val;
  65279. },
  65280. enumerable: true,
  65281. configurable: true
  65282. });
  65283. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  65284. /**
  65285. * Gets if `setParticles()` computes the particle colors or not.
  65286. * Default value : true. The SPS is faster when it's set to false.
  65287. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  65288. */
  65289. get: function () {
  65290. return this._computeParticleColor;
  65291. },
  65292. /**
  65293. * Tells to `setParticles()` to compute the particle colors or not.
  65294. * Default value : true. The SPS is faster when it's set to false.
  65295. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  65296. */
  65297. set: function (val) {
  65298. this._computeParticleColor = val;
  65299. },
  65300. enumerable: true,
  65301. configurable: true
  65302. });
  65303. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  65304. /**
  65305. * Gets if `setParticles()` computes the particle textures or not.
  65306. * Default value : true. The SPS is faster when it's set to false.
  65307. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  65308. */
  65309. get: function () {
  65310. return this._computeParticleTexture;
  65311. },
  65312. set: function (val) {
  65313. this._computeParticleTexture = val;
  65314. },
  65315. enumerable: true,
  65316. configurable: true
  65317. });
  65318. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  65319. /**
  65320. * Gets if `setParticles()` calls the vertex function for each vertex of each particle, or not.
  65321. * Default value : false. The SPS is faster when it's set to false.
  65322. * Note : the particle custom vertex positions aren't stored values.
  65323. */
  65324. get: function () {
  65325. return this._computeParticleVertex;
  65326. },
  65327. /**
  65328. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  65329. * Default value : false. The SPS is faster when it's set to false.
  65330. * Note : the particle custom vertex positions aren't stored values.
  65331. */
  65332. set: function (val) {
  65333. this._computeParticleVertex = val;
  65334. },
  65335. enumerable: true,
  65336. configurable: true
  65337. });
  65338. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  65339. /**
  65340. * Gets if `setParticles()` computes or not the mesh bounding box when computing the particle positions.
  65341. */
  65342. get: function () {
  65343. return this._computeBoundingBox;
  65344. },
  65345. /**
  65346. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  65347. */
  65348. set: function (val) {
  65349. this._computeBoundingBox = val;
  65350. },
  65351. enumerable: true,
  65352. configurable: true
  65353. });
  65354. Object.defineProperty(SolidParticleSystem.prototype, "depthSortParticles", {
  65355. /**
  65356. * Gets if `setParticles()` sorts or not the distance between each particle and the camera.
  65357. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  65358. * Default : `true`
  65359. */
  65360. get: function () {
  65361. return this._depthSortParticles;
  65362. },
  65363. /**
  65364. * Tells to `setParticles()` to sort or not the distance between each particle and the camera.
  65365. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  65366. * Default : `true`
  65367. */
  65368. set: function (val) {
  65369. this._depthSortParticles = val;
  65370. },
  65371. enumerable: true,
  65372. configurable: true
  65373. });
  65374. // =======================================================================
  65375. // Particle behavior logic
  65376. // these following methods may be overwritten by the user to fit his needs
  65377. /**
  65378. * This function does nothing. It may be overwritten to set all the particle first values.
  65379. * The SPS doesn't call this function, you may have to call it by your own.
  65380. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  65381. */
  65382. SolidParticleSystem.prototype.initParticles = function () {
  65383. };
  65384. /**
  65385. * This function does nothing. It may be overwritten to recycle a particle.
  65386. * The SPS doesn't call this function, you may have to call it by your own.
  65387. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  65388. * @param particle The particle to recycle
  65389. * @returns the recycled particle
  65390. */
  65391. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  65392. return particle;
  65393. };
  65394. /**
  65395. * Updates a particle : this function should be overwritten by the user.
  65396. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  65397. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  65398. * @example : just set a particle position or velocity and recycle conditions
  65399. * @param particle The particle to update
  65400. * @returns the updated particle
  65401. */
  65402. SolidParticleSystem.prototype.updateParticle = function (particle) {
  65403. return particle;
  65404. };
  65405. /**
  65406. * Updates a vertex of a particle : it can be overwritten by the user.
  65407. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  65408. * @param particle the current particle
  65409. * @param vertex the current index of the current particle
  65410. * @param pt the index of the current vertex in the particle shape
  65411. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  65412. * @example : just set a vertex particle position
  65413. * @returns the updated vertex
  65414. */
  65415. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  65416. return vertex;
  65417. };
  65418. /**
  65419. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  65420. * This does nothing and may be overwritten by the user.
  65421. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  65422. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  65423. * @param update the boolean update value actually passed to setParticles()
  65424. */
  65425. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  65426. };
  65427. /**
  65428. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  65429. * This will be passed three parameters.
  65430. * This does nothing and may be overwritten by the user.
  65431. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  65432. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  65433. * @param update the boolean update value actually passed to setParticles()
  65434. */
  65435. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  65436. };
  65437. return SolidParticleSystem;
  65438. }());
  65439. BABYLON.SolidParticleSystem = SolidParticleSystem;
  65440. })(BABYLON || (BABYLON = {}));
  65441. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  65442. var BABYLON;
  65443. (function (BABYLON) {
  65444. /**
  65445. * Class containing static functions to help procedurally build meshes
  65446. */
  65447. var MeshBuilder = /** @class */ (function () {
  65448. function MeshBuilder() {
  65449. }
  65450. MeshBuilder.updateSideOrientation = function (orientation) {
  65451. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  65452. return BABYLON.Mesh.DOUBLESIDE;
  65453. }
  65454. if (orientation === undefined || orientation === null) {
  65455. return BABYLON.Mesh.FRONTSIDE;
  65456. }
  65457. return orientation;
  65458. };
  65459. /**
  65460. * Creates a box mesh
  65461. * * The parameter `size` sets the size (float) of each box side (default 1)
  65462. * * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value of `size`)
  65463. * * 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)
  65464. * * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  65465. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  65466. * * 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
  65467. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  65468. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  65469. * @param name defines the name of the mesh
  65470. * @param options defines the options used to create the mesh
  65471. * @param scene defines the hosting scene
  65472. * @returns the box mesh
  65473. */
  65474. MeshBuilder.CreateBox = function (name, options, scene) {
  65475. if (scene === void 0) { scene = null; }
  65476. var box = new BABYLON.Mesh(name, scene);
  65477. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  65478. box._originalBuilderSideOrientation = options.sideOrientation;
  65479. var vertexData = BABYLON.VertexData.CreateBox(options);
  65480. vertexData.applyToMesh(box, options.updatable);
  65481. return box;
  65482. };
  65483. /**
  65484. * Creates a sphere mesh
  65485. * * The parameter `diameter` sets the diameter size (float) of the sphere (default 1)
  65486. * * 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 of `diameter`)
  65487. * * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32)
  65488. * * 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
  65489. * * 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)
  65490. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  65491. * * 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
  65492. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  65493. * @param name defines the name of the mesh
  65494. * @param options defines the options used to create the mesh
  65495. * @param scene defines the hosting scene
  65496. * @returns the sphere mesh
  65497. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  65498. */
  65499. MeshBuilder.CreateSphere = function (name, options, scene) {
  65500. var sphere = new BABYLON.Mesh(name, scene);
  65501. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  65502. sphere._originalBuilderSideOrientation = options.sideOrientation;
  65503. var vertexData = BABYLON.VertexData.CreateSphere(options);
  65504. vertexData.applyToMesh(sphere, options.updatable);
  65505. return sphere;
  65506. };
  65507. /**
  65508. * Creates a plane polygonal mesh. By default, this is a disc
  65509. * * The parameter `radius` sets the radius size (float) of the polygon (default 0.5)
  65510. * * 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
  65511. * * 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
  65512. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  65513. * * 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
  65514. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  65515. * @param name defines the name of the mesh
  65516. * @param options defines the options used to create the mesh
  65517. * @param scene defines the hosting scene
  65518. * @returns the plane polygonal mesh
  65519. * @see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  65520. */
  65521. MeshBuilder.CreateDisc = function (name, options, scene) {
  65522. if (scene === void 0) { scene = null; }
  65523. var disc = new BABYLON.Mesh(name, scene);
  65524. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  65525. disc._originalBuilderSideOrientation = options.sideOrientation;
  65526. var vertexData = BABYLON.VertexData.CreateDisc(options);
  65527. vertexData.applyToMesh(disc, options.updatable);
  65528. return disc;
  65529. };
  65530. /**
  65531. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided
  65532. * * The parameter `radius` sets the radius size (float) of the icosphere (default 1)
  65533. * * 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 of `radius`)
  65534. * * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size
  65535. * * 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
  65536. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  65537. * * 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
  65538. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  65539. * @param name defines the name of the mesh
  65540. * @param options defines the options used to create the mesh
  65541. * @param scene defines the hosting scene
  65542. * @returns the icosahedron mesh
  65543. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes#icosphere
  65544. */
  65545. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  65546. var sphere = new BABYLON.Mesh(name, scene);
  65547. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  65548. sphere._originalBuilderSideOrientation = options.sideOrientation;
  65549. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  65550. vertexData.applyToMesh(sphere, options.updatable);
  65551. return sphere;
  65552. };
  65553. ;
  65554. /**
  65555. * Creates a ribbon mesh. The ribbon is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  65556. * * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry
  65557. * * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array
  65558. * * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array
  65559. * * 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
  65560. * * 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
  65561. * * 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
  65562. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  65563. * * 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
  65564. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  65565. * * 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
  65566. * * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values
  65567. * * 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
  65568. * * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time
  65569. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  65570. * @param name defines the name of the mesh
  65571. * @param options defines the options used to create the mesh
  65572. * @param scene defines the hosting scene
  65573. * @returns the ribbon mesh
  65574. * @see http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  65575. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  65576. */
  65577. MeshBuilder.CreateRibbon = function (name, options, scene) {
  65578. if (scene === void 0) { scene = null; }
  65579. var pathArray = options.pathArray;
  65580. var closeArray = options.closeArray;
  65581. var closePath = options.closePath;
  65582. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  65583. var instance = options.instance;
  65584. var updatable = options.updatable;
  65585. if (instance) { // existing ribbon instance update
  65586. // positionFunction : ribbon case
  65587. // only pathArray and sideOrientation parameters are taken into account for positions update
  65588. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  65589. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  65590. var positionFunction = function (positions) {
  65591. var minlg = pathArray[0].length;
  65592. var i = 0;
  65593. var ns = (instance._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  65594. for (var si = 1; si <= ns; si++) {
  65595. for (var p = 0; p < pathArray.length; p++) {
  65596. var path = pathArray[p];
  65597. var l = path.length;
  65598. minlg = (minlg < l) ? minlg : l;
  65599. var j = 0;
  65600. while (j < minlg) {
  65601. positions[i] = path[j].x;
  65602. positions[i + 1] = path[j].y;
  65603. positions[i + 2] = path[j].z;
  65604. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  65605. BABYLON.Tmp.Vector3[0].x = path[j].x;
  65606. }
  65607. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  65608. BABYLON.Tmp.Vector3[1].x = path[j].x;
  65609. }
  65610. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  65611. BABYLON.Tmp.Vector3[0].y = path[j].y;
  65612. }
  65613. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  65614. BABYLON.Tmp.Vector3[1].y = path[j].y;
  65615. }
  65616. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  65617. BABYLON.Tmp.Vector3[0].z = path[j].z;
  65618. }
  65619. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  65620. BABYLON.Tmp.Vector3[1].z = path[j].z;
  65621. }
  65622. j++;
  65623. i += 3;
  65624. }
  65625. if (instance._closePath) {
  65626. positions[i] = path[0].x;
  65627. positions[i + 1] = path[0].y;
  65628. positions[i + 2] = path[0].z;
  65629. i += 3;
  65630. }
  65631. }
  65632. }
  65633. };
  65634. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  65635. positionFunction(positions);
  65636. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  65637. instance._boundingInfo.update(instance._worldMatrix);
  65638. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  65639. if (options.colors) {
  65640. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  65641. for (var c = 0; c < options.colors.length; c++) {
  65642. colors[c * 4] = options.colors[c].r;
  65643. colors[c * 4 + 1] = options.colors[c].g;
  65644. colors[c * 4 + 2] = options.colors[c].b;
  65645. colors[c * 4 + 3] = options.colors[c].a;
  65646. }
  65647. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  65648. }
  65649. if (options.uvs) {
  65650. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  65651. for (var i = 0; i < options.uvs.length; i++) {
  65652. uvs[i * 2] = options.uvs[i].x;
  65653. uvs[i * 2 + 1] = options.uvs[i].y;
  65654. }
  65655. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  65656. }
  65657. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  65658. var indices = instance.getIndices();
  65659. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  65660. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  65661. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  65662. if (instance._closePath) {
  65663. var indexFirst = 0;
  65664. var indexLast = 0;
  65665. for (var p = 0; p < pathArray.length; p++) {
  65666. indexFirst = instance._idx[p] * 3;
  65667. if (p + 1 < pathArray.length) {
  65668. indexLast = (instance._idx[p + 1] - 1) * 3;
  65669. }
  65670. else {
  65671. indexLast = normals.length - 3;
  65672. }
  65673. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  65674. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  65675. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  65676. normals[indexLast] = normals[indexFirst];
  65677. normals[indexLast + 1] = normals[indexFirst + 1];
  65678. normals[indexLast + 2] = normals[indexFirst + 2];
  65679. }
  65680. }
  65681. if (!(instance.areNormalsFrozen)) {
  65682. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  65683. }
  65684. }
  65685. return instance;
  65686. }
  65687. else { // new ribbon creation
  65688. var ribbon = new BABYLON.Mesh(name, scene);
  65689. ribbon._originalBuilderSideOrientation = sideOrientation;
  65690. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  65691. if (closePath) {
  65692. ribbon._idx = vertexData._idx;
  65693. }
  65694. ribbon._closePath = closePath;
  65695. ribbon._closeArray = closeArray;
  65696. vertexData.applyToMesh(ribbon, updatable);
  65697. return ribbon;
  65698. }
  65699. };
  65700. /**
  65701. * Creates a cylinder or a cone mesh
  65702. * * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  65703. * * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  65704. * * 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.
  65705. * * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  65706. * * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  65707. * * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  65708. * * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  65709. * * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  65710. * * 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).
  65711. * * 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
  65712. * * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  65713. * * 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
  65714. * * 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.
  65715. * * If `enclose` is false, a ring surface is one element.
  65716. * * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  65717. * * 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
  65718. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  65719. * * 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
  65720. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  65721. * @param name defines the name of the mesh
  65722. * @param options defines the options used to create the mesh
  65723. * @param scene defines the hosting scene
  65724. * @returns the cylinder mesh
  65725. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  65726. */
  65727. MeshBuilder.CreateCylinder = function (name, options, scene) {
  65728. var cylinder = new BABYLON.Mesh(name, scene);
  65729. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  65730. cylinder._originalBuilderSideOrientation = options.sideOrientation;
  65731. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  65732. vertexData.applyToMesh(cylinder, options.updatable);
  65733. return cylinder;
  65734. };
  65735. /**
  65736. * Creates a torus mesh
  65737. * * The parameter `diameter` sets the diameter size (float) of the torus (default 1)
  65738. * * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5)
  65739. * * The parameter `tessellation` sets the number of torus sides (postive integer, default 16)
  65740. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  65741. * * 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
  65742. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  65743. * @param name defines the name of the mesh
  65744. * @param options defines the options used to create the mesh
  65745. * @param scene defines the hosting scene
  65746. * @returns the torus mesh
  65747. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  65748. */
  65749. MeshBuilder.CreateTorus = function (name, options, scene) {
  65750. var torus = new BABYLON.Mesh(name, scene);
  65751. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  65752. torus._originalBuilderSideOrientation = options.sideOrientation;
  65753. var vertexData = BABYLON.VertexData.CreateTorus(options);
  65754. vertexData.applyToMesh(torus, options.updatable);
  65755. return torus;
  65756. };
  65757. /**
  65758. * Creates a torus knot mesh
  65759. * * The parameter `radius` sets the global radius size (float) of the torus knot (default 2)
  65760. * * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32)
  65761. * * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32)
  65762. * * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3)
  65763. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  65764. * * 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
  65765. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  65766. * @param name defines the name of the mesh
  65767. * @param options defines the options used to create the mesh
  65768. * @param scene defines the hosting scene
  65769. * @returns the torus knot mesh
  65770. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  65771. */
  65772. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  65773. var torusKnot = new BABYLON.Mesh(name, scene);
  65774. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  65775. torusKnot._originalBuilderSideOrientation = options.sideOrientation;
  65776. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  65777. vertexData.applyToMesh(torusKnot, options.updatable);
  65778. return torusKnot;
  65779. };
  65780. /**
  65781. * Creates a line system mesh. A line system is a pool of many lines gathered in a single mesh
  65782. * * 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
  65783. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function
  65784. * * The parameter `lines` is an array of lines, each line being an array of successive Vector3
  65785. * * The optional parameter `instance` is an instance of an existing LineSystem object to be updated with the passed `lines` parameter
  65786. * * The optional parameter `colors` is an array of line colors, each line colors being an array of successive Color4, one per line point
  65787. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need the alpha blending (faster)
  65788. * * 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
  65789. * * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines
  65790. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  65791. * @see http://doc.babylonjs.com/how_to/parametric_shapes#line-system
  65792. * @param name defines the name of the new line system
  65793. * @param options defines the options used to create the line system
  65794. * @param scene defines the hosting scene
  65795. * @returns a new line system mesh
  65796. */
  65797. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  65798. var instance = options.instance;
  65799. var lines = options.lines;
  65800. var colors = options.colors;
  65801. if (instance) { // lines update
  65802. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  65803. var vertexColor;
  65804. var lineColors;
  65805. if (colors) {
  65806. vertexColor = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  65807. }
  65808. var i = 0;
  65809. var c = 0;
  65810. for (var l = 0; l < lines.length; l++) {
  65811. var points = lines[l];
  65812. for (var p = 0; p < points.length; p++) {
  65813. positions[i] = points[p].x;
  65814. positions[i + 1] = points[p].y;
  65815. positions[i + 2] = points[p].z;
  65816. if (colors && vertexColor) {
  65817. lineColors = colors[l];
  65818. vertexColor[c] = lineColors[p].r;
  65819. vertexColor[c + 1] = lineColors[p].g;
  65820. vertexColor[c + 2] = lineColors[p].b;
  65821. vertexColor[c + 3] = lineColors[p].a;
  65822. c += 4;
  65823. }
  65824. i += 3;
  65825. }
  65826. }
  65827. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  65828. if (colors && vertexColor) {
  65829. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, vertexColor, false, false);
  65830. }
  65831. return instance;
  65832. }
  65833. // line system creation
  65834. var useVertexColor = (colors) ? true : false;
  65835. var lineSystem = new BABYLON.LinesMesh(name, scene, null, undefined, undefined, useVertexColor, options.useVertexAlpha);
  65836. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  65837. vertexData.applyToMesh(lineSystem, options.updatable);
  65838. return lineSystem;
  65839. };
  65840. /**
  65841. * Creates a line mesh
  65842. * 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
  65843. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  65844. * * The parameter `points` is an array successive Vector3
  65845. * * 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
  65846. * * The optional parameter `colors` is an array of successive Color4, one per line point
  65847. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need alpha blending (faster)
  65848. * * When updating an instance, remember that only point positions can change, not the number of points
  65849. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  65850. * @see http://doc.babylonjs.com/how_to/parametric_shapes#lines
  65851. * @param name defines the name of the new line system
  65852. * @param options defines the options used to create the line system
  65853. * @param scene defines the hosting scene
  65854. * @returns a new line mesh
  65855. */
  65856. MeshBuilder.CreateLines = function (name, options, scene) {
  65857. if (scene === void 0) { scene = null; }
  65858. var colors = (options.colors) ? [options.colors] : null;
  65859. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance, colors: colors, useVertexAlpha: options.useVertexAlpha }, scene);
  65860. return lines;
  65861. };
  65862. /**
  65863. * Creates a dashed line mesh
  65864. * * 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
  65865. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  65866. * * The parameter `points` is an array successive Vector3
  65867. * * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200)
  65868. * * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3)
  65869. * * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1)
  65870. * * 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
  65871. * * When updating an instance, remember that only point positions can change, not the number of points
  65872. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  65873. * @param name defines the name of the mesh
  65874. * @param options defines the options used to create the mesh
  65875. * @param scene defines the hosting scene
  65876. * @returns the dashed line mesh
  65877. * @see http://doc.babylonjs.com/how_to/parametric_shapes#dashed-lines
  65878. */
  65879. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  65880. if (scene === void 0) { scene = null; }
  65881. var points = options.points;
  65882. var instance = options.instance;
  65883. var gapSize = options.gapSize || 1;
  65884. var dashSize = options.dashSize || 3;
  65885. if (instance) { // dashed lines update
  65886. var positionFunction = function (positions) {
  65887. var curvect = BABYLON.Vector3.Zero();
  65888. var nbSeg = positions.length / 6;
  65889. var lg = 0;
  65890. var nb = 0;
  65891. var shft = 0;
  65892. var dashshft = 0;
  65893. var curshft = 0;
  65894. var p = 0;
  65895. var i = 0;
  65896. var j = 0;
  65897. for (i = 0; i < points.length - 1; i++) {
  65898. points[i + 1].subtractToRef(points[i], curvect);
  65899. lg += curvect.length();
  65900. }
  65901. shft = lg / nbSeg;
  65902. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  65903. for (i = 0; i < points.length - 1; i++) {
  65904. points[i + 1].subtractToRef(points[i], curvect);
  65905. nb = Math.floor(curvect.length() / shft);
  65906. curvect.normalize();
  65907. j = 0;
  65908. while (j < nb && p < positions.length) {
  65909. curshft = shft * j;
  65910. positions[p] = points[i].x + curshft * curvect.x;
  65911. positions[p + 1] = points[i].y + curshft * curvect.y;
  65912. positions[p + 2] = points[i].z + curshft * curvect.z;
  65913. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  65914. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  65915. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  65916. p += 6;
  65917. j++;
  65918. }
  65919. }
  65920. while (p < positions.length) {
  65921. positions[p] = points[i].x;
  65922. positions[p + 1] = points[i].y;
  65923. positions[p + 2] = points[i].z;
  65924. p += 3;
  65925. }
  65926. };
  65927. instance.updateMeshPositions(positionFunction, false);
  65928. return instance;
  65929. }
  65930. // dashed lines creation
  65931. var dashedLines = new BABYLON.LinesMesh(name, scene);
  65932. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  65933. vertexData.applyToMesh(dashedLines, options.updatable);
  65934. dashedLines.dashSize = dashSize;
  65935. dashedLines.gapSize = gapSize;
  65936. return dashedLines;
  65937. };
  65938. /**
  65939. * 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.
  65940. * * 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.
  65941. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  65942. * * 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.
  65943. * * The parameter `scale` (float, default 1) is the value to scale the shape.
  65944. * * 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
  65945. * * 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
  65946. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  65947. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  65948. * * 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
  65949. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  65950. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  65951. * @param name defines the name of the mesh
  65952. * @param options defines the options used to create the mesh
  65953. * @param scene defines the hosting scene
  65954. * @returns the extruded shape mesh
  65955. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  65956. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  65957. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  65958. */
  65959. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  65960. if (scene === void 0) { scene = null; }
  65961. var path = options.path;
  65962. var shape = options.shape;
  65963. var scale = options.scale || 1;
  65964. var rotation = options.rotation || 0;
  65965. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  65966. var updatable = options.updatable;
  65967. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  65968. var instance = options.instance || null;
  65969. var invertUV = options.invertUV || false;
  65970. 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);
  65971. };
  65972. /**
  65973. * Creates an custom extruded shape mesh.
  65974. * The custom extrusion is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters.
  65975. * * 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.
  65976. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  65977. * * 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
  65978. * * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  65979. * * 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
  65980. * * It must returns a float value that will be the scale value applied to the shape on each path point
  65981. * * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`
  65982. * * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`
  65983. * * 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
  65984. * * 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
  65985. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape
  65986. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  65987. * * 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
  65988. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  65989. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  65990. * @param name defines the name of the mesh
  65991. * @param options defines the options used to create the mesh
  65992. * @param scene defines the hosting scene
  65993. * @returns the custom extruded shape mesh
  65994. * @see http://doc.babylonjs.com/how_to/parametric_shapes#custom-extruded-shapes
  65995. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  65996. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  65997. */
  65998. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  65999. var path = options.path;
  66000. var shape = options.shape;
  66001. var scaleFunction = options.scaleFunction || (function () { return 1; });
  66002. var rotationFunction = options.rotationFunction || (function () { return 0; });
  66003. var ribbonCloseArray = options.ribbonCloseArray || false;
  66004. var ribbonClosePath = options.ribbonClosePath || false;
  66005. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  66006. var updatable = options.updatable;
  66007. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  66008. var instance = options.instance;
  66009. var invertUV = options.invertUV || false;
  66010. 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);
  66011. };
  66012. /**
  66013. * Creates lathe mesh.
  66014. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe
  66015. * * 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
  66016. * * The parameter `radius` (positive float, default 1) is the radius value of the lathe
  66017. * * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe
  66018. * * The parameter `clip` (positive integer, default 0) is the number of sides to not create without effecting the general shape of the sides
  66019. * * 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
  66020. * * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc"
  66021. * * 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
  66022. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  66023. * * 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
  66024. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  66025. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  66026. * @param name defines the name of the mesh
  66027. * @param options defines the options used to create the mesh
  66028. * @param scene defines the hosting scene
  66029. * @returns the lathe mesh
  66030. * @see http://doc.babylonjs.com/how_to/parametric_shapes#lathe
  66031. */
  66032. MeshBuilder.CreateLathe = function (name, options, scene) {
  66033. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  66034. var closed = (options.closed === undefined) ? true : options.closed;
  66035. var shape = options.shape;
  66036. var radius = options.radius || 1;
  66037. var tessellation = options.tessellation || 64;
  66038. var clip = options.clip || 0;
  66039. var updatable = options.updatable;
  66040. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  66041. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  66042. var pi2 = Math.PI * 2;
  66043. var paths = new Array();
  66044. var invertUV = options.invertUV || false;
  66045. var i = 0;
  66046. var p = 0;
  66047. var step = pi2 / tessellation * arc;
  66048. var rotated;
  66049. var path = new Array();
  66050. for (i = 0; i <= tessellation - clip; i++) {
  66051. var path = [];
  66052. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  66053. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  66054. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  66055. }
  66056. for (p = 0; p < shape.length; p++) {
  66057. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  66058. path.push(rotated);
  66059. }
  66060. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  66061. 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));
  66062. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  66063. }
  66064. paths.push(path);
  66065. }
  66066. // lathe ribbon
  66067. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  66068. return lathe;
  66069. };
  66070. /**
  66071. * Creates a plane mesh
  66072. * * The parameter `size` sets the size (float) of both sides of the plane at once (default 1)
  66073. * * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value of `size`)
  66074. * * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane
  66075. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  66076. * * 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
  66077. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  66078. * @param name defines the name of the mesh
  66079. * @param options defines the options used to create the mesh
  66080. * @param scene defines the hosting scene
  66081. * @returns the plane mesh
  66082. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  66083. */
  66084. MeshBuilder.CreatePlane = function (name, options, scene) {
  66085. var plane = new BABYLON.Mesh(name, scene);
  66086. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  66087. plane._originalBuilderSideOrientation = options.sideOrientation;
  66088. var vertexData = BABYLON.VertexData.CreatePlane(options);
  66089. vertexData.applyToMesh(plane, options.updatable);
  66090. if (options.sourcePlane) {
  66091. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  66092. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  66093. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  66094. if (vectorProduct.lengthSquared() > BABYLON.Epsilon) {
  66095. plane.rotate(vectorProduct, product);
  66096. }
  66097. }
  66098. return plane;
  66099. };
  66100. /**
  66101. * Creates a ground mesh
  66102. * * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground
  66103. * * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side
  66104. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  66105. * @param name defines the name of the mesh
  66106. * @param options defines the options used to create the mesh
  66107. * @param scene defines the hosting scene
  66108. * @returns the ground mesh
  66109. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  66110. */
  66111. MeshBuilder.CreateGround = function (name, options, scene) {
  66112. var ground = new BABYLON.GroundMesh(name, scene);
  66113. ground._setReady(false);
  66114. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  66115. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  66116. ground._width = options.width || 1;
  66117. ground._height = options.height || 1;
  66118. ground._maxX = ground._width / 2;
  66119. ground._maxZ = ground._height / 2;
  66120. ground._minX = -ground._maxX;
  66121. ground._minZ = -ground._maxZ;
  66122. var vertexData = BABYLON.VertexData.CreateGround(options);
  66123. vertexData.applyToMesh(ground, options.updatable);
  66124. ground._setReady(true);
  66125. return ground;
  66126. };
  66127. /**
  66128. * Creates a tiled ground mesh
  66129. * * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates
  66130. * * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates
  66131. * * 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
  66132. * * 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
  66133. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  66134. * @param name defines the name of the mesh
  66135. * @param options defines the options used to create the mesh
  66136. * @param scene defines the hosting scene
  66137. * @returns the tiled ground mesh
  66138. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  66139. */
  66140. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  66141. var tiledGround = new BABYLON.Mesh(name, scene);
  66142. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  66143. vertexData.applyToMesh(tiledGround, options.updatable);
  66144. return tiledGround;
  66145. };
  66146. /**
  66147. * Creates a ground mesh from a height map
  66148. * * The parameter `url` sets the URL of the height map image resource.
  66149. * * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  66150. * * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  66151. * * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  66152. * * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  66153. * * 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.
  66154. * * 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).
  66155. * * The parameter `alphaFilter` will filter any data where the alpha channel is below this value, defaults 0 (all data visible)
  66156. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  66157. * @param name defines the name of the mesh
  66158. * @param url defines the url to the height map
  66159. * @param options defines the options used to create the mesh
  66160. * @param scene defines the hosting scene
  66161. * @returns the ground mesh
  66162. * @see http://doc.babylonjs.com/babylon101/height_map
  66163. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  66164. */
  66165. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  66166. var width = options.width || 10.0;
  66167. var height = options.height || 10.0;
  66168. var subdivisions = options.subdivisions || 1 | 0;
  66169. var minHeight = options.minHeight || 0.0;
  66170. var maxHeight = options.maxHeight || 1.0;
  66171. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  66172. var alphaFilter = options.alphaFilter || 0.0;
  66173. var updatable = options.updatable;
  66174. var onReady = options.onReady;
  66175. var ground = new BABYLON.GroundMesh(name, scene);
  66176. ground._subdivisionsX = subdivisions;
  66177. ground._subdivisionsY = subdivisions;
  66178. ground._width = width;
  66179. ground._height = height;
  66180. ground._maxX = ground._width / 2.0;
  66181. ground._maxZ = ground._height / 2.0;
  66182. ground._minX = -ground._maxX;
  66183. ground._minZ = -ground._maxZ;
  66184. ground._setReady(false);
  66185. var onload = function (img) {
  66186. // Getting height map data
  66187. var canvas = document.createElement("canvas");
  66188. var context = canvas.getContext("2d");
  66189. if (!context) {
  66190. throw new Error("Unable to get 2d context for CreateGroundFromHeightMap");
  66191. }
  66192. if (scene.isDisposed) {
  66193. return;
  66194. }
  66195. var bufferWidth = img.width;
  66196. var bufferHeight = img.height;
  66197. canvas.width = bufferWidth;
  66198. canvas.height = bufferHeight;
  66199. context.drawImage(img, 0, 0);
  66200. // Create VertexData from map data
  66201. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  66202. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  66203. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  66204. width: width, height: height,
  66205. subdivisions: subdivisions,
  66206. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  66207. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight,
  66208. alphaFilter: alphaFilter
  66209. });
  66210. vertexData.applyToMesh(ground, updatable);
  66211. //execute ready callback, if set
  66212. if (onReady) {
  66213. onReady(ground);
  66214. }
  66215. ground._setReady(true);
  66216. };
  66217. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  66218. return ground;
  66219. };
  66220. /**
  66221. * Creates a polygon mesh
  66222. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh
  66223. * * 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
  66224. * * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  66225. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  66226. * * 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)
  66227. * * Remember you can only change the shape positions, not their number when updating a polygon
  66228. * @param name defines the name of the mesh
  66229. * @param options defines the options used to create the mesh
  66230. * @param scene defines the hosting scene
  66231. * @returns the polygon mesh
  66232. */
  66233. MeshBuilder.CreatePolygon = function (name, options, scene) {
  66234. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  66235. var shape = options.shape;
  66236. var holes = options.holes || [];
  66237. var depth = options.depth || 0;
  66238. var contours = [];
  66239. var hole = [];
  66240. for (var i = 0; i < shape.length; i++) {
  66241. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  66242. }
  66243. var epsilon = 0.00000001;
  66244. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  66245. contours.pop();
  66246. }
  66247. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  66248. for (var hNb = 0; hNb < holes.length; hNb++) {
  66249. hole = [];
  66250. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  66251. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  66252. }
  66253. polygonTriangulation.addHole(hole);
  66254. }
  66255. var polygon = polygonTriangulation.build(options.updatable, depth);
  66256. polygon._originalBuilderSideOrientation = options.sideOrientation;
  66257. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  66258. vertexData.applyToMesh(polygon, options.updatable);
  66259. return polygon;
  66260. };
  66261. ;
  66262. /**
  66263. * Creates an extruded polygon mesh, with depth in the Y direction.
  66264. * * 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)
  66265. * @see http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  66266. * @param name defines the name of the mesh
  66267. * @param options defines the options used to create the mesh
  66268. * @param scene defines the hosting scene
  66269. * @returns the polygon mesh
  66270. */
  66271. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  66272. return MeshBuilder.CreatePolygon(name, options, scene);
  66273. };
  66274. ;
  66275. /**
  66276. * Creates a tube mesh.
  66277. * The tube is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  66278. * * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube
  66279. * * The parameter `radius` (positive float, default 1) sets the tube radius size
  66280. * * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface
  66281. * * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`
  66282. * * 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)
  66283. * * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc
  66284. * * 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
  66285. * * 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
  66286. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  66287. * * 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
  66288. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  66289. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  66290. * @param name defines the name of the mesh
  66291. * @param options defines the options used to create the mesh
  66292. * @param scene defines the hosting scene
  66293. * @returns the tube mesh
  66294. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  66295. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  66296. */
  66297. MeshBuilder.CreateTube = function (name, options, scene) {
  66298. var path = options.path;
  66299. var instance = options.instance;
  66300. var radius = 1.0;
  66301. if (instance) {
  66302. radius = instance.radius;
  66303. }
  66304. if (options.radius !== undefined) {
  66305. radius = options.radius;
  66306. }
  66307. ;
  66308. var tessellation = options.tessellation || 64 | 0;
  66309. var radiusFunction = options.radiusFunction || null;
  66310. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  66311. var invertUV = options.invertUV || false;
  66312. var updatable = options.updatable;
  66313. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  66314. options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  66315. // tube geometry
  66316. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  66317. var tangents = path3D.getTangents();
  66318. var normals = path3D.getNormals();
  66319. var distances = path3D.getDistances();
  66320. var pi2 = Math.PI * 2;
  66321. var step = pi2 / tessellation * arc;
  66322. var returnRadius = function () { return radius; };
  66323. var radiusFunctionFinal = radiusFunction || returnRadius;
  66324. var circlePath;
  66325. var rad;
  66326. var normal;
  66327. var rotated;
  66328. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  66329. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  66330. for (var i = 0; i < path.length; i++) {
  66331. rad = radiusFunctionFinal(i, distances[i]); // current radius
  66332. circlePath = Array(); // current circle array
  66333. normal = normals[i]; // current normal
  66334. for (var t = 0; t < tessellation; t++) {
  66335. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  66336. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  66337. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  66338. rotated.scaleInPlace(rad).addInPlace(path[i]);
  66339. circlePath[t] = rotated;
  66340. }
  66341. circlePaths[index] = circlePath;
  66342. index++;
  66343. }
  66344. // cap
  66345. var capPath = function (nbPoints, pathIndex) {
  66346. var pointCap = Array();
  66347. for (var i = 0; i < nbPoints; i++) {
  66348. pointCap.push(path[pathIndex]);
  66349. }
  66350. return pointCap;
  66351. };
  66352. switch (cap) {
  66353. case BABYLON.Mesh.NO_CAP:
  66354. break;
  66355. case BABYLON.Mesh.CAP_START:
  66356. circlePaths[0] = capPath(tessellation, 0);
  66357. circlePaths[1] = circlePaths[2].slice(0);
  66358. break;
  66359. case BABYLON.Mesh.CAP_END:
  66360. circlePaths[index] = circlePaths[index - 1].slice(0);
  66361. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  66362. break;
  66363. case BABYLON.Mesh.CAP_ALL:
  66364. circlePaths[0] = capPath(tessellation, 0);
  66365. circlePaths[1] = circlePaths[2].slice(0);
  66366. circlePaths[index] = circlePaths[index - 1].slice(0);
  66367. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  66368. break;
  66369. default:
  66370. break;
  66371. }
  66372. return circlePaths;
  66373. };
  66374. var path3D;
  66375. var pathArray;
  66376. if (instance) { // tube update
  66377. var arc = options.arc || instance.arc;
  66378. path3D = (instance.path3D).update(path);
  66379. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  66380. instance = MeshBuilder.CreateRibbon("", { pathArray: pathArray, instance: instance });
  66381. instance.path3D = path3D;
  66382. instance.pathArray = pathArray;
  66383. instance.arc = arc;
  66384. instance.radius = radius;
  66385. return instance;
  66386. }
  66387. // tube creation
  66388. path3D = new BABYLON.Path3D(path);
  66389. var newPathArray = new Array();
  66390. cap = (cap < 0 || cap > 3) ? 0 : cap;
  66391. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  66392. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  66393. tube.pathArray = pathArray;
  66394. tube.path3D = path3D;
  66395. tube.tessellation = tessellation;
  66396. tube.cap = cap;
  66397. tube.arc = options.arc;
  66398. tube.radius = radius;
  66399. return tube;
  66400. };
  66401. /**
  66402. * Creates a polyhedron mesh
  66403. * * 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
  66404. * * The parameter `size` (positive float, default 1) sets the polygon size
  66405. * * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value)
  66406. * * 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`
  66407. * * 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
  66408. * * 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)`)
  66409. * * 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
  66410. * * 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
  66411. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  66412. * * 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
  66413. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  66414. * @param name defines the name of the mesh
  66415. * @param options defines the options used to create the mesh
  66416. * @param scene defines the hosting scene
  66417. * @returns the polyhedron mesh
  66418. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes
  66419. */
  66420. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  66421. var polyhedron = new BABYLON.Mesh(name, scene);
  66422. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  66423. polyhedron._originalBuilderSideOrientation = options.sideOrientation;
  66424. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  66425. vertexData.applyToMesh(polyhedron, options.updatable);
  66426. return polyhedron;
  66427. };
  66428. /**
  66429. * Creates a decal mesh.
  66430. * 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
  66431. * * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates
  66432. * * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates
  66433. * * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling
  66434. * * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal
  66435. * @param name defines the name of the mesh
  66436. * @param sourceMesh defines the mesh where the decal must be applied
  66437. * @param options defines the options used to create the mesh
  66438. * @param scene defines the hosting scene
  66439. * @returns the decal mesh
  66440. * @see http://doc.babylonjs.com/how_to/decals
  66441. */
  66442. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  66443. var indices = sourceMesh.getIndices();
  66444. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  66445. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  66446. var position = options.position || BABYLON.Vector3.Zero();
  66447. var normal = options.normal || BABYLON.Vector3.Up();
  66448. var size = options.size || BABYLON.Vector3.One();
  66449. var angle = options.angle || 0;
  66450. // Getting correct rotation
  66451. if (!normal) {
  66452. var target = new BABYLON.Vector3(0, 0, 1);
  66453. var camera = sourceMesh.getScene().activeCamera;
  66454. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  66455. normal = camera.globalPosition.subtract(cameraWorldTarget);
  66456. }
  66457. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  66458. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  66459. var pitch = Math.atan2(normal.y, len);
  66460. // Matrix
  66461. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  66462. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  66463. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  66464. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  66465. var vertexData = new BABYLON.VertexData();
  66466. vertexData.indices = [];
  66467. vertexData.positions = [];
  66468. vertexData.normals = [];
  66469. vertexData.uvs = [];
  66470. var currentVertexDataIndex = 0;
  66471. var extractDecalVector3 = function (indexId) {
  66472. var result = new BABYLON.PositionNormalVertex();
  66473. if (!indices || !positions || !normals) {
  66474. return result;
  66475. }
  66476. var vertexId = indices[indexId];
  66477. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  66478. // Send vector to decal local world
  66479. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  66480. // Get normal
  66481. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  66482. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  66483. return result;
  66484. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  66485. var clip = function (vertices, axis) {
  66486. if (vertices.length === 0) {
  66487. return vertices;
  66488. }
  66489. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  66490. var clipVertices = function (v0, v1) {
  66491. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  66492. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  66493. };
  66494. var result = new Array();
  66495. for (var index = 0; index < vertices.length; index += 3) {
  66496. var v1Out;
  66497. var v2Out;
  66498. var v3Out;
  66499. var total = 0;
  66500. var nV1 = null;
  66501. var nV2 = null;
  66502. var nV3 = null;
  66503. var nV4 = null;
  66504. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  66505. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  66506. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  66507. v1Out = d1 > 0;
  66508. v2Out = d2 > 0;
  66509. v3Out = d3 > 0;
  66510. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  66511. switch (total) {
  66512. case 0:
  66513. result.push(vertices[index]);
  66514. result.push(vertices[index + 1]);
  66515. result.push(vertices[index + 2]);
  66516. break;
  66517. case 1:
  66518. if (v1Out) {
  66519. nV1 = vertices[index + 1];
  66520. nV2 = vertices[index + 2];
  66521. nV3 = clipVertices(vertices[index], nV1);
  66522. nV4 = clipVertices(vertices[index], nV2);
  66523. }
  66524. if (v2Out) {
  66525. nV1 = vertices[index];
  66526. nV2 = vertices[index + 2];
  66527. nV3 = clipVertices(vertices[index + 1], nV1);
  66528. nV4 = clipVertices(vertices[index + 1], nV2);
  66529. result.push(nV3);
  66530. result.push(nV2.clone());
  66531. result.push(nV1.clone());
  66532. result.push(nV2.clone());
  66533. result.push(nV3.clone());
  66534. result.push(nV4);
  66535. break;
  66536. }
  66537. if (v3Out) {
  66538. nV1 = vertices[index];
  66539. nV2 = vertices[index + 1];
  66540. nV3 = clipVertices(vertices[index + 2], nV1);
  66541. nV4 = clipVertices(vertices[index + 2], nV2);
  66542. }
  66543. if (nV1 && nV2 && nV3 && nV4) {
  66544. result.push(nV1.clone());
  66545. result.push(nV2.clone());
  66546. result.push(nV3);
  66547. result.push(nV4);
  66548. result.push(nV3.clone());
  66549. result.push(nV2.clone());
  66550. }
  66551. break;
  66552. case 2:
  66553. if (!v1Out) {
  66554. nV1 = vertices[index].clone();
  66555. nV2 = clipVertices(nV1, vertices[index + 1]);
  66556. nV3 = clipVertices(nV1, vertices[index + 2]);
  66557. result.push(nV1);
  66558. result.push(nV2);
  66559. result.push(nV3);
  66560. }
  66561. if (!v2Out) {
  66562. nV1 = vertices[index + 1].clone();
  66563. nV2 = clipVertices(nV1, vertices[index + 2]);
  66564. nV3 = clipVertices(nV1, vertices[index]);
  66565. result.push(nV1);
  66566. result.push(nV2);
  66567. result.push(nV3);
  66568. }
  66569. if (!v3Out) {
  66570. nV1 = vertices[index + 2].clone();
  66571. nV2 = clipVertices(nV1, vertices[index]);
  66572. nV3 = clipVertices(nV1, vertices[index + 1]);
  66573. result.push(nV1);
  66574. result.push(nV2);
  66575. result.push(nV3);
  66576. }
  66577. break;
  66578. case 3:
  66579. break;
  66580. }
  66581. }
  66582. return result;
  66583. };
  66584. for (var index = 0; index < indices.length; index += 3) {
  66585. var faceVertices = new Array();
  66586. faceVertices.push(extractDecalVector3(index));
  66587. faceVertices.push(extractDecalVector3(index + 1));
  66588. faceVertices.push(extractDecalVector3(index + 2));
  66589. // Clip
  66590. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  66591. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  66592. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  66593. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  66594. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  66595. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  66596. if (faceVertices.length === 0) {
  66597. continue;
  66598. }
  66599. // Add UVs and get back to world
  66600. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  66601. var vertex = faceVertices[vIndex];
  66602. //TODO check for Int32Array | Uint32Array | Uint16Array
  66603. vertexData.indices.push(currentVertexDataIndex);
  66604. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  66605. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  66606. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  66607. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  66608. currentVertexDataIndex++;
  66609. }
  66610. }
  66611. // Return mesh
  66612. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  66613. vertexData.applyToMesh(decal);
  66614. decal.position = position.clone();
  66615. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  66616. return decal;
  66617. };
  66618. // Privates
  66619. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  66620. // extrusion geometry
  66621. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  66622. var tangents = path3D.getTangents();
  66623. var normals = path3D.getNormals();
  66624. var binormals = path3D.getBinormals();
  66625. var distances = path3D.getDistances();
  66626. var angle = 0;
  66627. var returnScale = function () { return scale !== null ? scale : 1; };
  66628. var returnRotation = function () { return rotation !== null ? rotation : 0; };
  66629. var rotate = custom && rotateFunction ? rotateFunction : returnRotation;
  66630. var scl = custom && scaleFunction ? scaleFunction : returnScale;
  66631. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  66632. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  66633. for (var i = 0; i < curve.length; i++) {
  66634. var shapePath = new Array();
  66635. var angleStep = rotate(i, distances[i]);
  66636. var scaleRatio = scl(i, distances[i]);
  66637. for (var p = 0; p < shape.length; p++) {
  66638. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  66639. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  66640. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  66641. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  66642. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  66643. shapePath[p] = rotated;
  66644. }
  66645. shapePaths[index] = shapePath;
  66646. angle += angleStep;
  66647. index++;
  66648. }
  66649. // cap
  66650. var capPath = function (shapePath) {
  66651. var pointCap = Array();
  66652. var barycenter = BABYLON.Vector3.Zero();
  66653. var i;
  66654. for (i = 0; i < shapePath.length; i++) {
  66655. barycenter.addInPlace(shapePath[i]);
  66656. }
  66657. barycenter.scaleInPlace(1.0 / shapePath.length);
  66658. for (i = 0; i < shapePath.length; i++) {
  66659. pointCap.push(barycenter);
  66660. }
  66661. return pointCap;
  66662. };
  66663. switch (cap) {
  66664. case BABYLON.Mesh.NO_CAP:
  66665. break;
  66666. case BABYLON.Mesh.CAP_START:
  66667. shapePaths[0] = capPath(shapePaths[2]);
  66668. shapePaths[1] = shapePaths[2];
  66669. break;
  66670. case BABYLON.Mesh.CAP_END:
  66671. shapePaths[index] = shapePaths[index - 1];
  66672. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  66673. break;
  66674. case BABYLON.Mesh.CAP_ALL:
  66675. shapePaths[0] = capPath(shapePaths[2]);
  66676. shapePaths[1] = shapePaths[2];
  66677. shapePaths[index] = shapePaths[index - 1];
  66678. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  66679. break;
  66680. default:
  66681. break;
  66682. }
  66683. return shapePaths;
  66684. };
  66685. var path3D;
  66686. var pathArray;
  66687. if (instance) { // instance update
  66688. path3D = (instance.path3D).update(curve);
  66689. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  66690. instance = BABYLON.Mesh.CreateRibbon("", pathArray, false, false, 0, scene || undefined, false, 0, instance);
  66691. return instance;
  66692. }
  66693. // extruded shape creation
  66694. path3D = new BABYLON.Path3D(curve);
  66695. var newShapePaths = new Array();
  66696. cap = (cap < 0 || cap > 3) ? 0 : cap;
  66697. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  66698. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs || undefined, backUVs: backUVs || undefined }, scene);
  66699. extrudedGeneric.pathArray = pathArray;
  66700. extrudedGeneric.path3D = path3D;
  66701. extrudedGeneric.cap = cap;
  66702. return extrudedGeneric;
  66703. };
  66704. return MeshBuilder;
  66705. }());
  66706. BABYLON.MeshBuilder = MeshBuilder;
  66707. })(BABYLON || (BABYLON = {}));
  66708. //# sourceMappingURL=babylon.meshBuilder.js.map
  66709. var BABYLON;
  66710. (function (BABYLON) {
  66711. /**
  66712. * Draco compression (https://google.github.io/draco/)
  66713. *
  66714. * This class wraps the Draco module.
  66715. *
  66716. * **Encoder**
  66717. *
  66718. * The encoder is not currently implemented.
  66719. *
  66720. * **Decoder**
  66721. *
  66722. * By default, the configuration points to a copy of the Draco decoder files for glTF from the babylon.js preview cdn https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js.
  66723. *
  66724. * To update the configuration, use the following code:
  66725. * ```javascript
  66726. * BABYLON.DracoCompression.Configuration = {
  66727. * decoder: {
  66728. * wasmUrl: "<url to the WebAssembly library>",
  66729. * wasmBinaryUrl: "<url to the WebAssembly binary>",
  66730. * fallbackUrl: "<url to the fallback JavaScript library>",
  66731. * }
  66732. * };
  66733. * ```
  66734. *
  66735. * 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.
  66736. * Decoding will automatically fallback to the JavaScript version if WebAssembly version is not configured or if WebAssembly is not supported by the browser.
  66737. * Use `BABYLON.DracoCompression.DecoderAvailable` to determine if the decoder is available for the current session.
  66738. *
  66739. * To decode Draco compressed data, create a DracoCompression object and call decodeMeshAsync:
  66740. * ```javascript
  66741. * var dracoCompression = new BABYLON.DracoCompression();
  66742. * var vertexData = await dracoCompression.decodeMeshAsync(data, {
  66743. * [BABYLON.VertexBuffer.PositionKind]: 0
  66744. * });
  66745. * ```
  66746. *
  66747. * @see https://www.babylonjs-playground.com/#N3EK4B#0
  66748. */
  66749. var DracoCompression = /** @class */ (function () {
  66750. /**
  66751. * Constructor
  66752. */
  66753. function DracoCompression() {
  66754. }
  66755. Object.defineProperty(DracoCompression, "DecoderAvailable", {
  66756. /**
  66757. * Returns true if the decoder is available.
  66758. */
  66759. get: function () {
  66760. if (typeof DracoDecoderModule !== "undefined") {
  66761. return true;
  66762. }
  66763. var decoder = DracoCompression.Configuration.decoder;
  66764. if (decoder) {
  66765. if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") {
  66766. return true;
  66767. }
  66768. if (decoder.fallbackUrl) {
  66769. return true;
  66770. }
  66771. }
  66772. return false;
  66773. },
  66774. enumerable: true,
  66775. configurable: true
  66776. });
  66777. /**
  66778. * Stop all async operations and release resources.
  66779. */
  66780. DracoCompression.prototype.dispose = function () {
  66781. };
  66782. /**
  66783. * Decode Draco compressed mesh data to vertex data.
  66784. * @param data The ArrayBuffer or ArrayBufferView for the Draco compression data
  66785. * @param attributes A map of attributes from vertex buffer kinds to Draco unique ids
  66786. * @returns A promise that resolves with the decoded vertex data
  66787. */
  66788. DracoCompression.prototype.decodeMeshAsync = function (data, attributes) {
  66789. var dataView = data instanceof ArrayBuffer ? new Uint8Array(data) : data;
  66790. return DracoCompression._GetDecoderModule().then(function (wrappedModule) {
  66791. var module = wrappedModule.module;
  66792. var vertexData = new BABYLON.VertexData();
  66793. var buffer = new module.DecoderBuffer();
  66794. buffer.Init(dataView, dataView.byteLength);
  66795. var decoder = new module.Decoder();
  66796. var geometry;
  66797. var status;
  66798. try {
  66799. var type = decoder.GetEncodedGeometryType(buffer);
  66800. switch (type) {
  66801. case module.TRIANGULAR_MESH:
  66802. geometry = new module.Mesh();
  66803. status = decoder.DecodeBufferToMesh(buffer, geometry);
  66804. break;
  66805. case module.POINT_CLOUD:
  66806. geometry = new module.PointCloud();
  66807. status = decoder.DecodeBufferToPointCloud(buffer, geometry);
  66808. break;
  66809. default:
  66810. throw new Error("Invalid geometry type " + type);
  66811. }
  66812. if (!status.ok() || !geometry.ptr) {
  66813. throw new Error(status.error_msg());
  66814. }
  66815. var numPoints = geometry.num_points();
  66816. if (type === module.TRIANGULAR_MESH) {
  66817. var numFaces = geometry.num_faces();
  66818. var faceIndices = new module.DracoInt32Array();
  66819. try {
  66820. var indices = new Uint32Array(numFaces * 3);
  66821. for (var i = 0; i < numFaces; i++) {
  66822. decoder.GetFaceFromMesh(geometry, i, faceIndices);
  66823. var offset = i * 3;
  66824. indices[offset + 0] = faceIndices.GetValue(0);
  66825. indices[offset + 1] = faceIndices.GetValue(1);
  66826. indices[offset + 2] = faceIndices.GetValue(2);
  66827. }
  66828. vertexData.indices = indices;
  66829. }
  66830. finally {
  66831. module.destroy(faceIndices);
  66832. }
  66833. }
  66834. for (var kind in attributes) {
  66835. var uniqueId = attributes[kind];
  66836. var attribute = decoder.GetAttributeByUniqueId(geometry, uniqueId);
  66837. var dracoData = new module.DracoFloat32Array();
  66838. try {
  66839. decoder.GetAttributeFloatForAllPoints(geometry, attribute, dracoData);
  66840. var babylonData = new Float32Array(numPoints * attribute.num_components());
  66841. for (var i = 0; i < babylonData.length; i++) {
  66842. babylonData[i] = dracoData.GetValue(i);
  66843. }
  66844. vertexData.set(babylonData, kind);
  66845. }
  66846. finally {
  66847. module.destroy(dracoData);
  66848. }
  66849. }
  66850. }
  66851. finally {
  66852. if (geometry) {
  66853. module.destroy(geometry);
  66854. }
  66855. module.destroy(decoder);
  66856. module.destroy(buffer);
  66857. }
  66858. return vertexData;
  66859. });
  66860. };
  66861. DracoCompression._GetDecoderModule = function () {
  66862. if (!DracoCompression._DecoderModulePromise) {
  66863. var promise = null;
  66864. var config_1 = {};
  66865. if (typeof DracoDecoderModule !== "undefined") {
  66866. promise = Promise.resolve();
  66867. }
  66868. else {
  66869. var decoder = DracoCompression.Configuration.decoder;
  66870. if (decoder) {
  66871. if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") {
  66872. promise = Promise.all([
  66873. DracoCompression._LoadScriptAsync(decoder.wasmUrl),
  66874. DracoCompression._LoadFileAsync(decoder.wasmBinaryUrl).then(function (data) {
  66875. config_1.wasmBinary = data;
  66876. })
  66877. ]);
  66878. }
  66879. else if (decoder.fallbackUrl) {
  66880. promise = DracoCompression._LoadScriptAsync(decoder.fallbackUrl);
  66881. }
  66882. }
  66883. }
  66884. if (!promise) {
  66885. throw new Error("Draco decoder module is not available");
  66886. }
  66887. DracoCompression._DecoderModulePromise = promise.then(function () {
  66888. return new Promise(function (resolve) {
  66889. config_1.onModuleLoaded = function (decoderModule) {
  66890. // decoderModule is Promise-like. Wrap before resolving to avoid loop.
  66891. resolve({ module: decoderModule });
  66892. };
  66893. DracoDecoderModule(config_1);
  66894. });
  66895. });
  66896. }
  66897. return DracoCompression._DecoderModulePromise;
  66898. };
  66899. DracoCompression._LoadScriptAsync = function (url) {
  66900. return new Promise(function (resolve, reject) {
  66901. BABYLON.Tools.LoadScript(url, function () {
  66902. resolve();
  66903. }, function (message) {
  66904. reject(new Error(message));
  66905. });
  66906. });
  66907. };
  66908. DracoCompression._LoadFileAsync = function (url) {
  66909. return new Promise(function (resolve, reject) {
  66910. BABYLON.Tools.LoadFile(url, function (data) {
  66911. resolve(data);
  66912. }, undefined, undefined, true, function (request, exception) {
  66913. reject(exception);
  66914. });
  66915. });
  66916. };
  66917. /**
  66918. * The configuration. Defaults to the following urls:
  66919. * - wasmUrl: "https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js"
  66920. * - wasmBinaryUrl: "https://preview.babylonjs.com/draco_decoder_gltf.wasm"
  66921. * - fallbackUrl: "https://preview.babylonjs.com/draco_decoder_gltf.js"
  66922. */
  66923. DracoCompression.Configuration = {
  66924. decoder: {
  66925. wasmUrl: "https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js",
  66926. wasmBinaryUrl: "https://preview.babylonjs.com/draco_decoder_gltf.wasm",
  66927. fallbackUrl: "https://preview.babylonjs.com/draco_decoder_gltf.js"
  66928. }
  66929. };
  66930. return DracoCompression;
  66931. }());
  66932. BABYLON.DracoCompression = DracoCompression;
  66933. })(BABYLON || (BABYLON = {}));
  66934. //# sourceMappingURL=babylon.dracoCompression.js.map
  66935. var BABYLON;
  66936. (function (BABYLON) {
  66937. // Sets the default audio engine to Babylon JS.
  66938. BABYLON.Engine.AudioEngineFactory = function (engine) { return new AudioEngine(engine); };
  66939. /**
  66940. * This represents the default audio engine used in babylon.
  66941. * It is responsible to play, synchronize and analyse sounds throughout the application.
  66942. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  66943. */
  66944. var AudioEngine = /** @class */ (function () {
  66945. /**
  66946. * Instantiates a new audio engine.
  66947. *
  66948. * There should be only one per page as some browsers restrict the number
  66949. * of audio contexts you can create.
  66950. * @param engine defines the hosting engine
  66951. */
  66952. function AudioEngine(engine) {
  66953. if (engine === void 0) { engine = BABYLON.Engine.LastCreatedEngine; }
  66954. var _this = this;
  66955. this._audioContext = null;
  66956. this._audioContextInitialized = false;
  66957. this._muteButton = null;
  66958. /**
  66959. * Gets whether the current host supports Web Audio and thus could create AudioContexts.
  66960. */
  66961. this.canUseWebAudio = false;
  66962. /**
  66963. * Defines if Babylon should emit a warning if WebAudio is not supported.
  66964. * @ignoreNaming
  66965. */
  66966. this.WarnedWebAudioUnsupported = false;
  66967. /**
  66968. * Gets whether or not mp3 are supported by your browser.
  66969. */
  66970. this.isMP3supported = false;
  66971. /**
  66972. * Gets whether or not ogg are supported by your browser.
  66973. */
  66974. this.isOGGsupported = false;
  66975. /**
  66976. * Gets whether audio has been unlocked on the device.
  66977. * Some Browsers have strong restrictions about Audio and won t autoplay unless
  66978. * a user interaction has happened.
  66979. */
  66980. this.unlocked = true;
  66981. /**
  66982. * Defines if the audio engine relies on a custom unlocked button.
  66983. * In this case, the embedded button will not be displayed.
  66984. */
  66985. this.useCustomUnlockedButton = false;
  66986. /**
  66987. * Event raised when audio has been unlocked on the browser.
  66988. */
  66989. this.onAudioUnlockedObservable = new BABYLON.Observable();
  66990. /**
  66991. * Event raised when audio has been locked on the browser.
  66992. */
  66993. this.onAudioLockedObservable = new BABYLON.Observable();
  66994. this._onResize = function () {
  66995. _this._moveButtonToTopLeft();
  66996. };
  66997. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  66998. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  66999. this.canUseWebAudio = true;
  67000. }
  67001. var audioElem = document.createElement('audio');
  67002. this._engine = engine;
  67003. try {
  67004. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  67005. this.isMP3supported = true;
  67006. }
  67007. }
  67008. catch (e) {
  67009. // protect error during capability check.
  67010. }
  67011. try {
  67012. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  67013. this.isOGGsupported = true;
  67014. }
  67015. }
  67016. catch (e) {
  67017. // protect error during capability check.
  67018. }
  67019. }
  67020. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  67021. /**
  67022. * Gets the current AudioContext if available.
  67023. */
  67024. get: function () {
  67025. if (!this._audioContextInitialized) {
  67026. this._initializeAudioContext();
  67027. }
  67028. else {
  67029. if (!this.unlocked && !this._muteButton) {
  67030. this._displayMuteButton();
  67031. }
  67032. }
  67033. return this._audioContext;
  67034. },
  67035. enumerable: true,
  67036. configurable: true
  67037. });
  67038. /**
  67039. * Flags the audio engine in Locked state.
  67040. * This happens due to new browser policies preventing audio to autoplay.
  67041. */
  67042. AudioEngine.prototype.lock = function () {
  67043. this._triggerSuspendedState();
  67044. };
  67045. /**
  67046. * Unlocks the audio engine once a user action has been done on the dom.
  67047. * This is helpful to resume play once browser policies have been satisfied.
  67048. */
  67049. AudioEngine.prototype.unlock = function () {
  67050. this._triggerRunningState();
  67051. };
  67052. AudioEngine.prototype._resumeAudioContext = function () {
  67053. var result;
  67054. if (this._audioContext.resume) {
  67055. result = this._audioContext.resume();
  67056. }
  67057. return result || Promise.resolve();
  67058. };
  67059. AudioEngine.prototype._initializeAudioContext = function () {
  67060. var _this = this;
  67061. try {
  67062. if (this.canUseWebAudio) {
  67063. this._audioContext = new AudioContext();
  67064. // create a global volume gain node
  67065. this.masterGain = this._audioContext.createGain();
  67066. this.masterGain.gain.value = 1;
  67067. this.masterGain.connect(this._audioContext.destination);
  67068. this._audioContextInitialized = true;
  67069. if (this._audioContext.state === "running") {
  67070. // Do not wait for the promise to unlock.
  67071. this._triggerRunningState();
  67072. }
  67073. else {
  67074. if (this._audioContext && this._audioContext.resume) {
  67075. this._resumeAudioContext().then(function () {
  67076. _this._triggerRunningState();
  67077. }).catch(function () {
  67078. // Can not resume automatically
  67079. // Needs user action
  67080. _this.lock();
  67081. });
  67082. }
  67083. }
  67084. }
  67085. }
  67086. catch (e) {
  67087. this.canUseWebAudio = false;
  67088. BABYLON.Tools.Error("Web Audio: " + e.message);
  67089. }
  67090. };
  67091. AudioEngine.prototype._triggerRunningState = function () {
  67092. var _this = this;
  67093. this._resumeAudioContext()
  67094. .then(function () {
  67095. _this.unlocked = true;
  67096. if (_this._muteButton) {
  67097. _this._hideMuteButton();
  67098. }
  67099. // Notify users that the audio stack is unlocked/unmuted
  67100. _this.onAudioUnlockedObservable.notifyObservers(_this);
  67101. }).catch(function () {
  67102. _this.unlocked = false;
  67103. });
  67104. };
  67105. AudioEngine.prototype._triggerSuspendedState = function () {
  67106. this.unlocked = false;
  67107. this.onAudioLockedObservable.notifyObservers(this);
  67108. this._displayMuteButton();
  67109. };
  67110. AudioEngine.prototype._displayMuteButton = function () {
  67111. var _this = this;
  67112. if (this.useCustomUnlockedButton) {
  67113. return;
  67114. }
  67115. this._canvas = this._engine.getRenderingCanvas();
  67116. this._muteButton = document.createElement("BUTTON");
  67117. this._muteButton.className = "babylonUnmuteIcon";
  67118. this._muteButton.id = "babylonUnmuteIconBtn";
  67119. this._muteButton.title = "Unmute";
  67120. var css = ".babylonUnmuteIcon { position: absolute; left: 20px; top: 20px; height: 40px; width: 60px; background-color: rgba(51,51,51,0.7); background-image: url(data:image/svg+xml;charset=UTF-8,%3Csvg%20version%3D%221.1%22%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2239%22%20height%3D%2232%22%20viewBox%3D%220%200%2039%2032%22%3E%3Cpath%20fill%3D%22white%22%20d%3D%22M9.625%2018.938l-0.031%200.016h-4.953q-0.016%200-0.031-0.016v-12.453q0-0.016%200.031-0.016h4.953q0.031%200%200.031%200.016v12.453zM12.125%207.688l8.719-8.703v27.453l-8.719-8.719-0.016-0.047v-9.938zM23.359%207.875l1.406-1.406%204.219%204.203%204.203-4.203%201.422%201.406-4.219%204.219%204.219%204.203-1.484%201.359-4.141-4.156-4.219%204.219-1.406-1.422%204.219-4.203z%22%3E%3C%2Fpath%3E%3C%2Fsvg%3E); background-size: 80%; background-repeat:no-repeat; background-position: center; background-position-y: 4px; border: none; outline: none; transition: transform 0.125s ease-out; cursor: pointer; z-index: 9999; } .babylonUnmuteIcon:hover { transform: scale(1.05) } .babylonUnmuteIcon:active { background-color: rgba(51,51,51,1) }";
  67121. var style = document.createElement('style');
  67122. style.appendChild(document.createTextNode(css));
  67123. document.getElementsByTagName('head')[0].appendChild(style);
  67124. document.body.appendChild(this._muteButton);
  67125. this._moveButtonToTopLeft();
  67126. this._muteButton.addEventListener('mousedown', function () {
  67127. _this._triggerRunningState();
  67128. }, false);
  67129. this._muteButton.addEventListener('touchend', function () {
  67130. _this._triggerRunningState();
  67131. }, false);
  67132. window.addEventListener("resize", this._onResize);
  67133. };
  67134. AudioEngine.prototype._moveButtonToTopLeft = function () {
  67135. if (this._canvas && this._muteButton) {
  67136. this._muteButton.style.top = this._canvas.offsetTop + 20 + "px";
  67137. this._muteButton.style.left = this._canvas.offsetLeft + 20 + "px";
  67138. }
  67139. };
  67140. AudioEngine.prototype._hideMuteButton = function () {
  67141. if (this._muteButton) {
  67142. document.body.removeChild(this._muteButton);
  67143. this._muteButton = null;
  67144. }
  67145. };
  67146. /**
  67147. * Destroy and release the resources associated with the audio ccontext.
  67148. */
  67149. AudioEngine.prototype.dispose = function () {
  67150. if (this.canUseWebAudio && this._audioContextInitialized) {
  67151. if (this._connectedAnalyser && this._audioContext) {
  67152. this._connectedAnalyser.stopDebugCanvas();
  67153. this._connectedAnalyser.dispose();
  67154. this.masterGain.disconnect();
  67155. this.masterGain.connect(this._audioContext.destination);
  67156. this._connectedAnalyser = null;
  67157. }
  67158. this.masterGain.gain.value = 1;
  67159. }
  67160. this.WarnedWebAudioUnsupported = false;
  67161. this._hideMuteButton();
  67162. window.removeEventListener("resize", this._onResize);
  67163. this.onAudioUnlockedObservable.clear();
  67164. this.onAudioLockedObservable.clear();
  67165. };
  67166. /**
  67167. * Gets the global volume sets on the master gain.
  67168. * @returns the global volume if set or -1 otherwise
  67169. */
  67170. AudioEngine.prototype.getGlobalVolume = function () {
  67171. if (this.canUseWebAudio && this._audioContextInitialized) {
  67172. return this.masterGain.gain.value;
  67173. }
  67174. else {
  67175. return -1;
  67176. }
  67177. };
  67178. /**
  67179. * Sets the global volume of your experience (sets on the master gain).
  67180. * @param newVolume Defines the new global volume of the application
  67181. */
  67182. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  67183. if (this.canUseWebAudio && this._audioContextInitialized) {
  67184. this.masterGain.gain.value = newVolume;
  67185. }
  67186. };
  67187. /**
  67188. * Connect the audio engine to an audio analyser allowing some amazing
  67189. * synchornization between the sounds/music and your visualization (VuMeter for instance).
  67190. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#using-the-analyser
  67191. * @param analyser The analyser to connect to the engine
  67192. */
  67193. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  67194. if (this._connectedAnalyser) {
  67195. this._connectedAnalyser.stopDebugCanvas();
  67196. }
  67197. if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) {
  67198. this._connectedAnalyser = analyser;
  67199. this.masterGain.disconnect();
  67200. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  67201. }
  67202. };
  67203. return AudioEngine;
  67204. }());
  67205. BABYLON.AudioEngine = AudioEngine;
  67206. })(BABYLON || (BABYLON = {}));
  67207. //# sourceMappingURL=babylon.audioEngine.js.map
  67208. var BABYLON;
  67209. (function (BABYLON) {
  67210. /**
  67211. * Defines a sound that can be played in the application.
  67212. * The sound can either be an ambient track or a simple sound played in reaction to a user action.
  67213. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  67214. */
  67215. var Sound = /** @class */ (function () {
  67216. /**
  67217. * Create a sound and attach it to a scene
  67218. * @param name Name of your sound
  67219. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer, it also works with MediaStreams
  67220. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  67221. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  67222. */
  67223. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  67224. if (readyToPlayCallback === void 0) { readyToPlayCallback = null; }
  67225. var _this = this;
  67226. /**
  67227. * Does the sound autoplay once loaded.
  67228. */
  67229. this.autoplay = false;
  67230. /**
  67231. * Does the sound loop after it finishes playing once.
  67232. */
  67233. this.loop = false;
  67234. /**
  67235. * Does the sound use a custom attenuation curve to simulate the falloff
  67236. * happening when the source gets further away from the camera.
  67237. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-your-own-custom-attenuation-function
  67238. */
  67239. this.useCustomAttenuation = false;
  67240. /**
  67241. * Is this sound currently played.
  67242. */
  67243. this.isPlaying = false;
  67244. /**
  67245. * Is this sound currently paused.
  67246. */
  67247. this.isPaused = false;
  67248. /**
  67249. * Does this sound enables spatial sound.
  67250. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
  67251. */
  67252. this.spatialSound = false;
  67253. /**
  67254. * Define the reference distance the sound should be heard perfectly.
  67255. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
  67256. */
  67257. this.refDistance = 1;
  67258. /**
  67259. * Define the roll off factor of spatial sounds.
  67260. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
  67261. */
  67262. this.rolloffFactor = 1;
  67263. /**
  67264. * Define the max distance the sound should be heard (intensity just became 0 at this point).
  67265. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
  67266. */
  67267. this.maxDistance = 100;
  67268. /**
  67269. * Define the distance attenuation model the sound will follow.
  67270. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
  67271. */
  67272. this.distanceModel = "linear";
  67273. /**
  67274. * Observable event when the current playing sound finishes.
  67275. */
  67276. this.onEndedObservable = new BABYLON.Observable();
  67277. this._panningModel = "equalpower";
  67278. this._playbackRate = 1;
  67279. this._streaming = false;
  67280. this._startTime = 0;
  67281. this._startOffset = 0;
  67282. this._position = BABYLON.Vector3.Zero();
  67283. /** @hidden */
  67284. this._positionInEmitterSpace = false;
  67285. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  67286. this._volume = 1;
  67287. this._isReadyToPlay = false;
  67288. this._isDirectional = false;
  67289. // Used if you'd like to create a directional sound.
  67290. // If not set, the sound will be omnidirectional
  67291. this._coneInnerAngle = 360;
  67292. this._coneOuterAngle = 360;
  67293. this._coneOuterGain = 0;
  67294. this._isOutputConnected = false;
  67295. this._urlType = "Unknown";
  67296. this.name = name;
  67297. this._scene = scene;
  67298. var compo = scene._getComponent(BABYLON.SceneComponentConstants.NAME_AUDIO);
  67299. if (!compo) {
  67300. compo = new BABYLON.AudioSceneComponent(scene);
  67301. scene._addComponent(compo);
  67302. }
  67303. this._readyToPlayCallback = readyToPlayCallback;
  67304. // Default custom attenuation function is a linear attenuation
  67305. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  67306. if (currentDistance < maxDistance) {
  67307. return currentVolume * (1 - currentDistance / maxDistance);
  67308. }
  67309. else {
  67310. return 0;
  67311. }
  67312. };
  67313. if (options) {
  67314. this.autoplay = options.autoplay || false;
  67315. this.loop = options.loop || false;
  67316. // if volume === 0, we need another way to check this option
  67317. if (options.volume !== undefined) {
  67318. this._volume = options.volume;
  67319. }
  67320. this.spatialSound = options.spatialSound || false;
  67321. this.maxDistance = options.maxDistance || 100;
  67322. this.useCustomAttenuation = options.useCustomAttenuation || false;
  67323. this.rolloffFactor = options.rolloffFactor || 1;
  67324. this.refDistance = options.refDistance || 1;
  67325. this.distanceModel = options.distanceModel || "linear";
  67326. this._playbackRate = options.playbackRate || 1;
  67327. this._streaming = options.streaming || false;
  67328. }
  67329. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  67330. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  67331. this._soundGain.gain.value = this._volume;
  67332. this._inputAudioNode = this._soundGain;
  67333. this._outputAudioNode = this._soundGain;
  67334. if (this.spatialSound) {
  67335. this._createSpatialParameters();
  67336. }
  67337. this._scene.mainSoundTrack.AddSound(this);
  67338. var validParameter = true;
  67339. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  67340. if (urlOrArrayBuffer) {
  67341. try {
  67342. if (typeof (urlOrArrayBuffer) === "string") {
  67343. this._urlType = "String";
  67344. }
  67345. else if (urlOrArrayBuffer instanceof ArrayBuffer) {
  67346. this._urlType = "ArrayBuffer";
  67347. }
  67348. else if (urlOrArrayBuffer instanceof MediaStream) {
  67349. this._urlType = "MediaStream";
  67350. }
  67351. else if (Array.isArray(urlOrArrayBuffer)) {
  67352. this._urlType = "Array";
  67353. }
  67354. var urls = [];
  67355. var codecSupportedFound = false;
  67356. switch (this._urlType) {
  67357. case "MediaStream":
  67358. this._streaming = true;
  67359. this._isReadyToPlay = true;
  67360. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(urlOrArrayBuffer);
  67361. if (this.autoplay) {
  67362. this.play();
  67363. }
  67364. if (this._readyToPlayCallback) {
  67365. this._readyToPlayCallback();
  67366. }
  67367. break;
  67368. case "ArrayBuffer":
  67369. if (urlOrArrayBuffer.byteLength > 0) {
  67370. codecSupportedFound = true;
  67371. this._soundLoaded(urlOrArrayBuffer);
  67372. }
  67373. break;
  67374. case "String":
  67375. urls.push(urlOrArrayBuffer);
  67376. case "Array":
  67377. if (urls.length === 0)
  67378. urls = urlOrArrayBuffer;
  67379. // If we found a supported format, we load it immediately and stop the loop
  67380. for (var i = 0; i < urls.length; i++) {
  67381. var url = urls[i];
  67382. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  67383. codecSupportedFound = true;
  67384. }
  67385. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  67386. codecSupportedFound = true;
  67387. }
  67388. if (url.indexOf(".wav", url.length - 4) !== -1) {
  67389. codecSupportedFound = true;
  67390. }
  67391. if (url.indexOf("blob:") !== -1) {
  67392. codecSupportedFound = true;
  67393. }
  67394. if (codecSupportedFound) {
  67395. // Loading sound using XHR2
  67396. if (!this._streaming) {
  67397. this._scene._loadFile(url, function (data) {
  67398. _this._soundLoaded(data);
  67399. }, undefined, true, true, function (exception) {
  67400. if (exception) {
  67401. BABYLON.Tools.Error("XHR " + exception.status + " error on: " + url + ".");
  67402. }
  67403. BABYLON.Tools.Error("Sound creation aborted.");
  67404. _this._scene.mainSoundTrack.RemoveSound(_this);
  67405. });
  67406. }
  67407. // Streaming sound using HTML5 Audio tag
  67408. else {
  67409. this._htmlAudioElement = new Audio(url);
  67410. this._htmlAudioElement.controls = false;
  67411. this._htmlAudioElement.loop = this.loop;
  67412. BABYLON.Tools.SetCorsBehavior(url, this._htmlAudioElement);
  67413. this._htmlAudioElement.preload = "auto";
  67414. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  67415. _this._isReadyToPlay = true;
  67416. if (_this.autoplay) {
  67417. _this.play();
  67418. }
  67419. if (_this._readyToPlayCallback) {
  67420. _this._readyToPlayCallback();
  67421. }
  67422. });
  67423. document.body.appendChild(this._htmlAudioElement);
  67424. this._htmlAudioElement.load();
  67425. }
  67426. break;
  67427. }
  67428. }
  67429. break;
  67430. default:
  67431. validParameter = false;
  67432. break;
  67433. }
  67434. if (!validParameter) {
  67435. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  67436. }
  67437. else {
  67438. if (!codecSupportedFound) {
  67439. this._isReadyToPlay = true;
  67440. // Simulating a ready to play event to avoid breaking code path
  67441. if (this._readyToPlayCallback) {
  67442. window.setTimeout(function () {
  67443. if (_this._readyToPlayCallback) {
  67444. _this._readyToPlayCallback();
  67445. }
  67446. }, 1000);
  67447. }
  67448. }
  67449. }
  67450. }
  67451. catch (ex) {
  67452. BABYLON.Tools.Error("Unexpected error. Sound creation aborted.");
  67453. this._scene.mainSoundTrack.RemoveSound(this);
  67454. }
  67455. }
  67456. }
  67457. else {
  67458. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  67459. this._scene.mainSoundTrack.AddSound(this);
  67460. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  67461. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  67462. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  67463. }
  67464. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  67465. if (this._readyToPlayCallback) {
  67466. window.setTimeout(function () {
  67467. if (_this._readyToPlayCallback) {
  67468. _this._readyToPlayCallback();
  67469. }
  67470. }, 1000);
  67471. }
  67472. }
  67473. }
  67474. /**
  67475. * Release the sound and its associated resources
  67476. */
  67477. Sound.prototype.dispose = function () {
  67478. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  67479. if (this.isPlaying) {
  67480. this.stop();
  67481. }
  67482. this._isReadyToPlay = false;
  67483. if (this.soundTrackId === -1) {
  67484. this._scene.mainSoundTrack.RemoveSound(this);
  67485. }
  67486. else if (this._scene.soundTracks) {
  67487. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  67488. }
  67489. if (this._soundGain) {
  67490. this._soundGain.disconnect();
  67491. this._soundGain = null;
  67492. }
  67493. if (this._soundPanner) {
  67494. this._soundPanner.disconnect();
  67495. this._soundPanner = null;
  67496. }
  67497. if (this._soundSource) {
  67498. this._soundSource.disconnect();
  67499. this._soundSource = null;
  67500. }
  67501. this._audioBuffer = null;
  67502. if (this._htmlAudioElement) {
  67503. this._htmlAudioElement.pause();
  67504. this._htmlAudioElement.src = "";
  67505. document.body.removeChild(this._htmlAudioElement);
  67506. }
  67507. if (this._streamingSource) {
  67508. this._streamingSource.disconnect();
  67509. }
  67510. if (this._connectedMesh && this._registerFunc) {
  67511. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  67512. this._connectedMesh = null;
  67513. }
  67514. }
  67515. };
  67516. /**
  67517. * Gets if the sounds is ready to be played or not.
  67518. * @returns true if ready, otherwise false
  67519. */
  67520. Sound.prototype.isReady = function () {
  67521. return this._isReadyToPlay;
  67522. };
  67523. Sound.prototype._soundLoaded = function (audioData) {
  67524. var _this = this;
  67525. if (!BABYLON.Engine.audioEngine.audioContext) {
  67526. return;
  67527. }
  67528. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  67529. _this._audioBuffer = buffer;
  67530. _this._isReadyToPlay = true;
  67531. if (_this.autoplay) {
  67532. _this.play();
  67533. }
  67534. if (_this._readyToPlayCallback) {
  67535. _this._readyToPlayCallback();
  67536. }
  67537. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  67538. };
  67539. /**
  67540. * Sets the data of the sound from an audiobuffer
  67541. * @param audioBuffer The audioBuffer containing the data
  67542. */
  67543. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  67544. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  67545. this._audioBuffer = audioBuffer;
  67546. this._isReadyToPlay = true;
  67547. }
  67548. };
  67549. /**
  67550. * Updates the current sounds options such as maxdistance, loop...
  67551. * @param options A JSON object containing values named as the object properties
  67552. */
  67553. Sound.prototype.updateOptions = function (options) {
  67554. if (options) {
  67555. this.loop = options.loop || this.loop;
  67556. this.maxDistance = options.maxDistance || this.maxDistance;
  67557. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  67558. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  67559. this.refDistance = options.refDistance || this.refDistance;
  67560. this.distanceModel = options.distanceModel || this.distanceModel;
  67561. this._playbackRate = options.playbackRate || this._playbackRate;
  67562. this._updateSpatialParameters();
  67563. if (this.isPlaying) {
  67564. if (this._streaming && this._htmlAudioElement) {
  67565. this._htmlAudioElement.playbackRate = this._playbackRate;
  67566. }
  67567. else {
  67568. if (this._soundSource) {
  67569. this._soundSource.playbackRate.value = this._playbackRate;
  67570. }
  67571. }
  67572. }
  67573. }
  67574. };
  67575. Sound.prototype._createSpatialParameters = function () {
  67576. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  67577. if (this._scene.headphone) {
  67578. this._panningModel = "HRTF";
  67579. }
  67580. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  67581. this._updateSpatialParameters();
  67582. this._soundPanner.connect(this._outputAudioNode);
  67583. this._inputAudioNode = this._soundPanner;
  67584. }
  67585. };
  67586. Sound.prototype._updateSpatialParameters = function () {
  67587. if (this.spatialSound && this._soundPanner) {
  67588. if (this.useCustomAttenuation) {
  67589. // Tricks to disable in a way embedded Web Audio attenuation
  67590. this._soundPanner.distanceModel = "linear";
  67591. this._soundPanner.maxDistance = Number.MAX_VALUE;
  67592. this._soundPanner.refDistance = 1;
  67593. this._soundPanner.rolloffFactor = 1;
  67594. this._soundPanner.panningModel = this._panningModel;
  67595. }
  67596. else {
  67597. this._soundPanner.distanceModel = this.distanceModel;
  67598. this._soundPanner.maxDistance = this.maxDistance;
  67599. this._soundPanner.refDistance = this.refDistance;
  67600. this._soundPanner.rolloffFactor = this.rolloffFactor;
  67601. this._soundPanner.panningModel = this._panningModel;
  67602. }
  67603. }
  67604. };
  67605. /**
  67606. * Switch the panning model to HRTF:
  67607. * Renders a stereo output of higher quality than equalpower — it uses a convolution with measured impulse responses from human subjects.
  67608. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
  67609. */
  67610. Sound.prototype.switchPanningModelToHRTF = function () {
  67611. this._panningModel = "HRTF";
  67612. this._switchPanningModel();
  67613. };
  67614. /**
  67615. * Switch the panning model to Equal Power:
  67616. * Represents the equal-power panning algorithm, generally regarded as simple and efficient. equalpower is the default value.
  67617. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
  67618. */
  67619. Sound.prototype.switchPanningModelToEqualPower = function () {
  67620. this._panningModel = "equalpower";
  67621. this._switchPanningModel();
  67622. };
  67623. Sound.prototype._switchPanningModel = function () {
  67624. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  67625. this._soundPanner.panningModel = this._panningModel;
  67626. }
  67627. };
  67628. /**
  67629. * Connect this sound to a sound track audio node like gain...
  67630. * @param soundTrackAudioNode the sound track audio node to connect to
  67631. */
  67632. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  67633. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  67634. if (this._isOutputConnected) {
  67635. this._outputAudioNode.disconnect();
  67636. }
  67637. this._outputAudioNode.connect(soundTrackAudioNode);
  67638. this._isOutputConnected = true;
  67639. }
  67640. };
  67641. /**
  67642. * Transform this sound into a directional source
  67643. * @param coneInnerAngle Size of the inner cone in degree
  67644. * @param coneOuterAngle Size of the outer cone in degree
  67645. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  67646. */
  67647. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  67648. if (coneOuterAngle < coneInnerAngle) {
  67649. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  67650. return;
  67651. }
  67652. this._coneInnerAngle = coneInnerAngle;
  67653. this._coneOuterAngle = coneOuterAngle;
  67654. this._coneOuterGain = coneOuterGain;
  67655. this._isDirectional = true;
  67656. if (this.isPlaying && this.loop) {
  67657. this.stop();
  67658. this.play();
  67659. }
  67660. };
  67661. Object.defineProperty(Sound.prototype, "directionalConeInnerAngle", {
  67662. /**
  67663. * Gets or sets the inner angle for the directional cone.
  67664. */
  67665. get: function () {
  67666. return this._coneInnerAngle;
  67667. },
  67668. /**
  67669. * Gets or sets the inner angle for the directional cone.
  67670. */
  67671. set: function (value) {
  67672. if (value != this._coneInnerAngle) {
  67673. if (this._coneOuterAngle < value) {
  67674. BABYLON.Tools.Error("directionalConeInnerAngle: outer angle of the cone must be superior or equal to the inner angle.");
  67675. return;
  67676. }
  67677. this._coneInnerAngle = value;
  67678. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  67679. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  67680. }
  67681. }
  67682. },
  67683. enumerable: true,
  67684. configurable: true
  67685. });
  67686. Object.defineProperty(Sound.prototype, "directionalConeOuterAngle", {
  67687. /**
  67688. * Gets or sets the outer angle for the directional cone.
  67689. */
  67690. get: function () {
  67691. return this._coneOuterAngle;
  67692. },
  67693. /**
  67694. * Gets or sets the outer angle for the directional cone.
  67695. */
  67696. set: function (value) {
  67697. if (value != this._coneOuterAngle) {
  67698. if (value < this._coneInnerAngle) {
  67699. BABYLON.Tools.Error("directionalConeOuterAngle: outer angle of the cone must be superior or equal to the inner angle.");
  67700. return;
  67701. }
  67702. this._coneOuterAngle = value;
  67703. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  67704. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  67705. }
  67706. }
  67707. },
  67708. enumerable: true,
  67709. configurable: true
  67710. });
  67711. /**
  67712. * Sets the position of the emitter if spatial sound is enabled
  67713. * @param newPosition Defines the new posisiton
  67714. */
  67715. Sound.prototype.setPosition = function (newPosition) {
  67716. this._position = newPosition;
  67717. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner && !isNaN(this._position.x) && !isNaN(this._position.y) && !isNaN(this._position.z)) {
  67718. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  67719. }
  67720. };
  67721. /**
  67722. * Sets the local direction of the emitter if spatial sound is enabled
  67723. * @param newLocalDirection Defines the new local direction
  67724. */
  67725. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  67726. this._localDirection = newLocalDirection;
  67727. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  67728. this._updateDirection();
  67729. }
  67730. };
  67731. Sound.prototype._updateDirection = function () {
  67732. if (!this._connectedMesh || !this._soundPanner) {
  67733. return;
  67734. }
  67735. var mat = this._connectedMesh.getWorldMatrix();
  67736. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  67737. direction.normalize();
  67738. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  67739. };
  67740. /** @hidden */
  67741. Sound.prototype.updateDistanceFromListener = function () {
  67742. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {
  67743. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  67744. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  67745. }
  67746. };
  67747. /**
  67748. * Sets a new custom attenuation function for the sound.
  67749. * @param callback Defines the function used for the attenuation
  67750. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-your-own-custom-attenuation-function
  67751. */
  67752. Sound.prototype.setAttenuationFunction = function (callback) {
  67753. this._customAttenuationFunction = callback;
  67754. };
  67755. /**
  67756. * Play the sound
  67757. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  67758. * @param offset (optional) Start the sound setting it at a specific time
  67759. */
  67760. Sound.prototype.play = function (time, offset) {
  67761. var _this = this;
  67762. if (this._isReadyToPlay && this._scene.audioEnabled && BABYLON.Engine.audioEngine.audioContext) {
  67763. try {
  67764. if (this._startOffset < 0) {
  67765. time = -this._startOffset;
  67766. this._startOffset = 0;
  67767. }
  67768. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  67769. if (!this._soundSource || !this._streamingSource) {
  67770. if (this.spatialSound && this._soundPanner) {
  67771. if (!isNaN(this._position.x) && !isNaN(this._position.y) && !isNaN(this._position.z)) {
  67772. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  67773. }
  67774. if (this._isDirectional) {
  67775. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  67776. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  67777. this._soundPanner.coneOuterGain = this._coneOuterGain;
  67778. if (this._connectedMesh) {
  67779. this._updateDirection();
  67780. }
  67781. else {
  67782. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  67783. }
  67784. }
  67785. }
  67786. }
  67787. if (this._streaming) {
  67788. if (!this._streamingSource) {
  67789. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  67790. this._htmlAudioElement.onended = function () { _this._onended(); };
  67791. this._htmlAudioElement.playbackRate = this._playbackRate;
  67792. }
  67793. this._streamingSource.disconnect();
  67794. this._streamingSource.connect(this._inputAudioNode);
  67795. if (this._htmlAudioElement) {
  67796. // required to manage properly the new suspended default state of Chrome
  67797. // When the option 'streaming: true' is used, we need first to wait for
  67798. // the audio engine to be unlocked by a user gesture before trying to play
  67799. // an HTML Audio elememt
  67800. var tryToPlay = function () {
  67801. if (BABYLON.Engine.audioEngine.unlocked) {
  67802. var playPromise = _this._htmlAudioElement.play();
  67803. // In browsers that don’t yet support this functionality,
  67804. // playPromise won’t be defined.
  67805. if (playPromise !== undefined) {
  67806. playPromise.catch(function (error) {
  67807. // Automatic playback failed.
  67808. // Waiting for the audio engine to be unlocked by user click on unmute
  67809. BABYLON.Engine.audioEngine.lock();
  67810. BABYLON.Engine.audioEngine.onAudioUnlockedObservable.addOnce(function () { tryToPlay(); });
  67811. });
  67812. }
  67813. }
  67814. else {
  67815. BABYLON.Engine.audioEngine.onAudioUnlockedObservable.addOnce(function () { tryToPlay(); });
  67816. }
  67817. };
  67818. tryToPlay();
  67819. }
  67820. }
  67821. else {
  67822. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  67823. this._soundSource.buffer = this._audioBuffer;
  67824. this._soundSource.connect(this._inputAudioNode);
  67825. this._soundSource.loop = this.loop;
  67826. this._soundSource.playbackRate.value = this._playbackRate;
  67827. this._soundSource.onended = function () { _this._onended(); };
  67828. if (this._soundSource.buffer) {
  67829. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  67830. }
  67831. }
  67832. this._startTime = startTime;
  67833. this.isPlaying = true;
  67834. this.isPaused = false;
  67835. }
  67836. catch (ex) {
  67837. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  67838. }
  67839. }
  67840. };
  67841. Sound.prototype._onended = function () {
  67842. this.isPlaying = false;
  67843. if (this.onended) {
  67844. this.onended();
  67845. }
  67846. this.onEndedObservable.notifyObservers(this);
  67847. };
  67848. /**
  67849. * Stop the sound
  67850. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  67851. */
  67852. Sound.prototype.stop = function (time) {
  67853. if (this.isPlaying) {
  67854. if (this._streaming) {
  67855. if (this._htmlAudioElement) {
  67856. this._htmlAudioElement.pause();
  67857. // Test needed for Firefox or it will generate an Invalid State Error
  67858. if (this._htmlAudioElement.currentTime > 0) {
  67859. this._htmlAudioElement.currentTime = 0;
  67860. }
  67861. }
  67862. else {
  67863. this._streamingSource.disconnect();
  67864. }
  67865. }
  67866. else if (BABYLON.Engine.audioEngine.audioContext && this._soundSource) {
  67867. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  67868. this._soundSource.stop(stopTime);
  67869. this._soundSource.onended = function () { };
  67870. if (!this.isPaused) {
  67871. this._startOffset = 0;
  67872. }
  67873. }
  67874. this.isPlaying = false;
  67875. }
  67876. };
  67877. /**
  67878. * Put the sound in pause
  67879. */
  67880. Sound.prototype.pause = function () {
  67881. if (this.isPlaying) {
  67882. this.isPaused = true;
  67883. if (this._streaming) {
  67884. if (this._htmlAudioElement) {
  67885. this._htmlAudioElement.pause();
  67886. }
  67887. else {
  67888. this._streamingSource.disconnect();
  67889. }
  67890. }
  67891. else if (BABYLON.Engine.audioEngine.audioContext) {
  67892. this.stop(0);
  67893. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  67894. }
  67895. }
  67896. };
  67897. /**
  67898. * Sets a dedicated volume for this sounds
  67899. * @param newVolume Define the new volume of the sound
  67900. * @param time Define in how long the sound should be at this value
  67901. */
  67902. Sound.prototype.setVolume = function (newVolume, time) {
  67903. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._soundGain) {
  67904. if (time && BABYLON.Engine.audioEngine.audioContext) {
  67905. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  67906. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  67907. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  67908. }
  67909. else {
  67910. this._soundGain.gain.value = newVolume;
  67911. }
  67912. }
  67913. this._volume = newVolume;
  67914. };
  67915. /**
  67916. * Set the sound play back rate
  67917. * @param newPlaybackRate Define the playback rate the sound should be played at
  67918. */
  67919. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  67920. this._playbackRate = newPlaybackRate;
  67921. if (this.isPlaying) {
  67922. if (this._streaming && this._htmlAudioElement) {
  67923. this._htmlAudioElement.playbackRate = this._playbackRate;
  67924. }
  67925. else if (this._soundSource) {
  67926. this._soundSource.playbackRate.value = this._playbackRate;
  67927. }
  67928. }
  67929. };
  67930. /**
  67931. * Gets the volume of the sound.
  67932. * @returns the volume of the sound
  67933. */
  67934. Sound.prototype.getVolume = function () {
  67935. return this._volume;
  67936. };
  67937. /**
  67938. * Attach the sound to a dedicated mesh
  67939. * @param meshToConnectTo The mesh to connect the sound with
  67940. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#attaching-a-sound-to-a-mesh
  67941. */
  67942. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  67943. var _this = this;
  67944. if (this._connectedMesh && this._registerFunc) {
  67945. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  67946. this._registerFunc = null;
  67947. }
  67948. this._connectedMesh = meshToConnectTo;
  67949. if (!this.spatialSound) {
  67950. this.spatialSound = true;
  67951. this._createSpatialParameters();
  67952. if (this.isPlaying && this.loop) {
  67953. this.stop();
  67954. this.play();
  67955. }
  67956. }
  67957. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  67958. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  67959. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  67960. };
  67961. /**
  67962. * Detach the sound from the previously attached mesh
  67963. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#attaching-a-sound-to-a-mesh
  67964. */
  67965. Sound.prototype.detachFromMesh = function () {
  67966. if (this._connectedMesh && this._registerFunc) {
  67967. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  67968. this._registerFunc = null;
  67969. this._connectedMesh = null;
  67970. }
  67971. };
  67972. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (node) {
  67973. if (!node.getBoundingInfo) {
  67974. return;
  67975. }
  67976. var mesh = node;
  67977. if (this._positionInEmitterSpace) {
  67978. mesh.worldMatrixFromCache.invertToRef(BABYLON.Tmp.Matrix[0]);
  67979. this.setPosition(BABYLON.Tmp.Matrix[0].getTranslation());
  67980. }
  67981. else {
  67982. var boundingInfo = mesh.getBoundingInfo();
  67983. this.setPosition(boundingInfo.boundingSphere.centerWorld);
  67984. }
  67985. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  67986. this._updateDirection();
  67987. }
  67988. };
  67989. /**
  67990. * Clone the current sound in the scene.
  67991. * @returns the new sound clone
  67992. */
  67993. Sound.prototype.clone = function () {
  67994. var _this = this;
  67995. if (!this._streaming) {
  67996. var setBufferAndRun = function () {
  67997. if (_this._isReadyToPlay) {
  67998. clonedSound._audioBuffer = _this.getAudioBuffer();
  67999. clonedSound._isReadyToPlay = true;
  68000. if (clonedSound.autoplay) {
  68001. clonedSound.play();
  68002. }
  68003. }
  68004. else {
  68005. window.setTimeout(setBufferAndRun, 300);
  68006. }
  68007. };
  68008. var currentOptions = {
  68009. autoplay: this.autoplay, loop: this.loop,
  68010. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  68011. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  68012. refDistance: this.refDistance, distanceModel: this.distanceModel
  68013. };
  68014. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  68015. if (this.useCustomAttenuation) {
  68016. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  68017. }
  68018. clonedSound.setPosition(this._position);
  68019. clonedSound.setPlaybackRate(this._playbackRate);
  68020. setBufferAndRun();
  68021. return clonedSound;
  68022. }
  68023. // Can't clone a streaming sound
  68024. else {
  68025. return null;
  68026. }
  68027. };
  68028. /**
  68029. * Gets the current underlying audio buffer containing the data
  68030. * @returns the audio buffer
  68031. */
  68032. Sound.prototype.getAudioBuffer = function () {
  68033. return this._audioBuffer;
  68034. };
  68035. /**
  68036. * Serializes the Sound in a JSON representation
  68037. * @returns the JSON representation of the sound
  68038. */
  68039. Sound.prototype.serialize = function () {
  68040. var serializationObject = {
  68041. name: this.name,
  68042. url: this.name,
  68043. autoplay: this.autoplay,
  68044. loop: this.loop,
  68045. volume: this._volume,
  68046. spatialSound: this.spatialSound,
  68047. maxDistance: this.maxDistance,
  68048. rolloffFactor: this.rolloffFactor,
  68049. refDistance: this.refDistance,
  68050. distanceModel: this.distanceModel,
  68051. playbackRate: this._playbackRate,
  68052. panningModel: this._panningModel,
  68053. soundTrackId: this.soundTrackId
  68054. };
  68055. if (this.spatialSound) {
  68056. if (this._connectedMesh)
  68057. serializationObject.connectedMeshId = this._connectedMesh.id;
  68058. serializationObject.position = this._position.asArray();
  68059. serializationObject.refDistance = this.refDistance;
  68060. serializationObject.distanceModel = this.distanceModel;
  68061. serializationObject.isDirectional = this._isDirectional;
  68062. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  68063. serializationObject.coneInnerAngle = this._coneInnerAngle;
  68064. serializationObject.coneOuterAngle = this._coneOuterAngle;
  68065. serializationObject.coneOuterGain = this._coneOuterGain;
  68066. }
  68067. return serializationObject;
  68068. };
  68069. /**
  68070. * Parse a JSON representation of a sound to innstantiate in a given scene
  68071. * @param parsedSound Define the JSON representation of the sound (usually coming from the serialize method)
  68072. * @param scene Define the scene the new parsed sound should be created in
  68073. * @param rootUrl Define the rooturl of the load in case we need to fetch relative dependencies
  68074. * @param sourceSound Define a cound place holder if do not need to instantiate a new one
  68075. * @returns the newly parsed sound
  68076. */
  68077. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  68078. var soundName = parsedSound.name;
  68079. var soundUrl;
  68080. if (parsedSound.url) {
  68081. soundUrl = rootUrl + parsedSound.url;
  68082. }
  68083. else {
  68084. soundUrl = rootUrl + soundName;
  68085. }
  68086. var options = {
  68087. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  68088. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  68089. rolloffFactor: parsedSound.rolloffFactor,
  68090. refDistance: parsedSound.refDistance,
  68091. distanceModel: parsedSound.distanceModel,
  68092. playbackRate: parsedSound.playbackRate
  68093. };
  68094. var newSound;
  68095. if (!sourceSound) {
  68096. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  68097. scene._addPendingData(newSound);
  68098. }
  68099. else {
  68100. var setBufferAndRun = function () {
  68101. if (sourceSound._isReadyToPlay) {
  68102. newSound._audioBuffer = sourceSound.getAudioBuffer();
  68103. newSound._isReadyToPlay = true;
  68104. if (newSound.autoplay) {
  68105. newSound.play();
  68106. }
  68107. }
  68108. else {
  68109. window.setTimeout(setBufferAndRun, 300);
  68110. }
  68111. };
  68112. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  68113. setBufferAndRun();
  68114. }
  68115. if (parsedSound.position) {
  68116. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  68117. newSound.setPosition(soundPosition);
  68118. }
  68119. if (parsedSound.isDirectional) {
  68120. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  68121. if (parsedSound.localDirectionToMesh) {
  68122. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  68123. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  68124. }
  68125. }
  68126. if (parsedSound.connectedMeshId) {
  68127. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  68128. if (connectedMesh) {
  68129. newSound.attachToMesh(connectedMesh);
  68130. }
  68131. }
  68132. return newSound;
  68133. };
  68134. return Sound;
  68135. }());
  68136. BABYLON.Sound = Sound;
  68137. })(BABYLON || (BABYLON = {}));
  68138. //# sourceMappingURL=babylon.sound.js.map
  68139. var BABYLON;
  68140. (function (BABYLON) {
  68141. /**
  68142. * It could be useful to isolate your music & sounds on several tracks to better manage volume on a grouped instance of sounds.
  68143. * It will be also used in a future release to apply effects on a specific track.
  68144. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#using-sound-tracks
  68145. */
  68146. var SoundTrack = /** @class */ (function () {
  68147. /**
  68148. * Creates a new sound track.
  68149. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#using-sound-tracks
  68150. * @param scene Define the scene the sound track belongs to
  68151. * @param options
  68152. */
  68153. function SoundTrack(scene, options) {
  68154. if (options === void 0) { options = {}; }
  68155. /**
  68156. * The unique identifier of the sound track in the scene.
  68157. */
  68158. this.id = -1;
  68159. this._isMainTrack = false;
  68160. this._isInitialized = false;
  68161. this._scene = scene;
  68162. this.soundCollection = new Array();
  68163. this._options = options;
  68164. if (!this._isMainTrack && this._scene.soundTracks) {
  68165. this._scene.soundTracks.push(this);
  68166. this.id = this._scene.soundTracks.length - 1;
  68167. }
  68168. }
  68169. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  68170. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  68171. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  68172. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  68173. if (this._options) {
  68174. if (this._options.volume) {
  68175. this._outputAudioNode.gain.value = this._options.volume;
  68176. }
  68177. if (this._options.mainTrack) {
  68178. this._isMainTrack = this._options.mainTrack;
  68179. }
  68180. }
  68181. this._isInitialized = true;
  68182. }
  68183. };
  68184. /**
  68185. * Release the sound track and its associated resources
  68186. */
  68187. SoundTrack.prototype.dispose = function () {
  68188. if (BABYLON.Engine.audioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  68189. if (this._connectedAnalyser) {
  68190. this._connectedAnalyser.stopDebugCanvas();
  68191. }
  68192. while (this.soundCollection.length) {
  68193. this.soundCollection[0].dispose();
  68194. }
  68195. if (this._outputAudioNode) {
  68196. this._outputAudioNode.disconnect();
  68197. }
  68198. this._outputAudioNode = null;
  68199. }
  68200. };
  68201. /**
  68202. * Adds a sound to this sound track
  68203. * @param sound define the cound to add
  68204. * @ignoreNaming
  68205. */
  68206. SoundTrack.prototype.AddSound = function (sound) {
  68207. if (!this._isInitialized) {
  68208. this._initializeSoundTrackAudioGraph();
  68209. }
  68210. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  68211. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  68212. }
  68213. if (sound.soundTrackId) {
  68214. if (sound.soundTrackId === -1) {
  68215. this._scene.mainSoundTrack.RemoveSound(sound);
  68216. }
  68217. else if (this._scene.soundTracks) {
  68218. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  68219. }
  68220. }
  68221. this.soundCollection.push(sound);
  68222. sound.soundTrackId = this.id;
  68223. };
  68224. /**
  68225. * Removes a sound to this sound track
  68226. * @param sound define the cound to remove
  68227. * @ignoreNaming
  68228. */
  68229. SoundTrack.prototype.RemoveSound = function (sound) {
  68230. var index = this.soundCollection.indexOf(sound);
  68231. if (index !== -1) {
  68232. this.soundCollection.splice(index, 1);
  68233. }
  68234. };
  68235. /**
  68236. * Set a global volume for the full sound track.
  68237. * @param newVolume Define the new volume of the sound track
  68238. */
  68239. SoundTrack.prototype.setVolume = function (newVolume) {
  68240. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  68241. this._outputAudioNode.gain.value = newVolume;
  68242. }
  68243. };
  68244. /**
  68245. * Switch the panning model to HRTF:
  68246. * Renders a stereo output of higher quality than equalpower — it uses a convolution with measured impulse responses from human subjects.
  68247. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
  68248. */
  68249. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  68250. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  68251. for (var i = 0; i < this.soundCollection.length; i++) {
  68252. this.soundCollection[i].switchPanningModelToHRTF();
  68253. }
  68254. }
  68255. };
  68256. /**
  68257. * Switch the panning model to Equal Power:
  68258. * Represents the equal-power panning algorithm, generally regarded as simple and efficient. equalpower is the default value.
  68259. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
  68260. */
  68261. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  68262. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  68263. for (var i = 0; i < this.soundCollection.length; i++) {
  68264. this.soundCollection[i].switchPanningModelToEqualPower();
  68265. }
  68266. }
  68267. };
  68268. /**
  68269. * Connect the sound track to an audio analyser allowing some amazing
  68270. * synchornization between the sounds/music and your visualization (VuMeter for instance).
  68271. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#using-the-analyser
  68272. * @param analyser The analyser to connect to the engine
  68273. */
  68274. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  68275. if (this._connectedAnalyser) {
  68276. this._connectedAnalyser.stopDebugCanvas();
  68277. }
  68278. this._connectedAnalyser = analyser;
  68279. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  68280. this._outputAudioNode.disconnect();
  68281. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  68282. }
  68283. };
  68284. return SoundTrack;
  68285. }());
  68286. BABYLON.SoundTrack = SoundTrack;
  68287. })(BABYLON || (BABYLON = {}));
  68288. //# sourceMappingURL=babylon.soundtrack.js.map
  68289. var BABYLON;
  68290. (function (BABYLON) {
  68291. /**
  68292. * Class used to work with sound analyzer using fast fourier transform (FFT)
  68293. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  68294. */
  68295. var Analyser = /** @class */ (function () {
  68296. /**
  68297. * Creates a new analyser
  68298. * @param scene defines hosting scene
  68299. */
  68300. function Analyser(scene) {
  68301. /**
  68302. * Gets or sets the smoothing
  68303. * @ignorenaming
  68304. */
  68305. this.SMOOTHING = 0.75;
  68306. /**
  68307. * Gets or sets the FFT table size
  68308. * @ignorenaming
  68309. */
  68310. this.FFT_SIZE = 512;
  68311. /**
  68312. * Gets or sets the bar graph amplitude
  68313. * @ignorenaming
  68314. */
  68315. this.BARGRAPHAMPLITUDE = 256;
  68316. /**
  68317. * Gets or sets the position of the debug canvas
  68318. * @ignorenaming
  68319. */
  68320. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  68321. /**
  68322. * Gets or sets the debug canvas size
  68323. * @ignorenaming
  68324. */
  68325. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  68326. this._scene = scene;
  68327. this._audioEngine = BABYLON.Engine.audioEngine;
  68328. if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) {
  68329. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  68330. this._webAudioAnalyser.minDecibels = -140;
  68331. this._webAudioAnalyser.maxDecibels = 0;
  68332. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  68333. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  68334. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  68335. }
  68336. }
  68337. /**
  68338. * Get the number of data values you will have to play with for the visualization
  68339. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/frequencyBinCount
  68340. * @returns a number
  68341. */
  68342. Analyser.prototype.getFrequencyBinCount = function () {
  68343. if (this._audioEngine.canUseWebAudio) {
  68344. return this._webAudioAnalyser.frequencyBinCount;
  68345. }
  68346. else {
  68347. return 0;
  68348. }
  68349. };
  68350. /**
  68351. * Gets the current frequency data as a byte array
  68352. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData
  68353. * @returns a Uint8Array
  68354. */
  68355. Analyser.prototype.getByteFrequencyData = function () {
  68356. if (this._audioEngine.canUseWebAudio) {
  68357. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  68358. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  68359. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  68360. }
  68361. return this._byteFreqs;
  68362. };
  68363. /**
  68364. * Gets the current waveform as a byte array
  68365. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteTimeDomainData
  68366. * @returns a Uint8Array
  68367. */
  68368. Analyser.prototype.getByteTimeDomainData = function () {
  68369. if (this._audioEngine.canUseWebAudio) {
  68370. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  68371. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  68372. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  68373. }
  68374. return this._byteTime;
  68375. };
  68376. /**
  68377. * Gets the current frequency data as a float array
  68378. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData
  68379. * @returns a Float32Array
  68380. */
  68381. Analyser.prototype.getFloatFrequencyData = function () {
  68382. if (this._audioEngine.canUseWebAudio) {
  68383. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  68384. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  68385. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  68386. }
  68387. return this._floatFreqs;
  68388. };
  68389. /**
  68390. * Renders the debug canvas
  68391. */
  68392. Analyser.prototype.drawDebugCanvas = function () {
  68393. var _this = this;
  68394. if (this._audioEngine.canUseWebAudio) {
  68395. if (!this._debugCanvas) {
  68396. this._debugCanvas = document.createElement("canvas");
  68397. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  68398. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  68399. this._debugCanvas.style.position = "absolute";
  68400. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  68401. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  68402. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  68403. document.body.appendChild(this._debugCanvas);
  68404. this._registerFunc = function () {
  68405. _this.drawDebugCanvas();
  68406. };
  68407. this._scene.registerBeforeRender(this._registerFunc);
  68408. }
  68409. if (this._registerFunc && this._debugCanvasContext) {
  68410. var workingArray = this.getByteFrequencyData();
  68411. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  68412. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  68413. // Draw the frequency domain chart.
  68414. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  68415. var value = workingArray[i];
  68416. var percent = value / this.BARGRAPHAMPLITUDE;
  68417. var height = this.DEBUGCANVASSIZE.height * percent;
  68418. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  68419. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  68420. var hue = i / this.getFrequencyBinCount() * 360;
  68421. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  68422. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  68423. }
  68424. }
  68425. }
  68426. };
  68427. /**
  68428. * Stops rendering the debug canvas and removes it
  68429. */
  68430. Analyser.prototype.stopDebugCanvas = function () {
  68431. if (this._debugCanvas) {
  68432. if (this._registerFunc) {
  68433. this._scene.unregisterBeforeRender(this._registerFunc);
  68434. this._registerFunc = null;
  68435. }
  68436. document.body.removeChild(this._debugCanvas);
  68437. this._debugCanvas = null;
  68438. this._debugCanvasContext = null;
  68439. }
  68440. };
  68441. /**
  68442. * Connects two audio nodes
  68443. * @param inputAudioNode defines first node to connect
  68444. * @param outputAudioNode defines second node to connect
  68445. */
  68446. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  68447. if (this._audioEngine.canUseWebAudio) {
  68448. inputAudioNode.connect(this._webAudioAnalyser);
  68449. this._webAudioAnalyser.connect(outputAudioNode);
  68450. }
  68451. };
  68452. /**
  68453. * Releases all associated resources
  68454. */
  68455. Analyser.prototype.dispose = function () {
  68456. if (this._audioEngine.canUseWebAudio) {
  68457. this._webAudioAnalyser.disconnect();
  68458. }
  68459. };
  68460. return Analyser;
  68461. }());
  68462. BABYLON.Analyser = Analyser;
  68463. })(BABYLON || (BABYLON = {}));
  68464. //# sourceMappingURL=babylon.analyser.js.map
  68465. var BABYLON;
  68466. (function (BABYLON) {
  68467. /**
  68468. * Wraps one or more Sound objects and selects one with random weight for playback.
  68469. */
  68470. var WeightedSound = /** @class */ (function () {
  68471. /**
  68472. * Creates a new WeightedSound from the list of sounds given.
  68473. * @param loop When true a Sound will be selected and played when the current playing Sound completes.
  68474. * @param sounds Array of Sounds that will be selected from.
  68475. * @param weights Array of number values for selection weights; length must equal sounds, values will be normalized to 1
  68476. */
  68477. function WeightedSound(loop, sounds, weights) {
  68478. var _this = this;
  68479. /** When true a Sound will be selected and played when the current playing Sound completes. */
  68480. this.loop = false;
  68481. this._coneInnerAngle = 360;
  68482. this._coneOuterAngle = 360;
  68483. this._volume = 1;
  68484. /** A Sound is currently playing. */
  68485. this.isPlaying = false;
  68486. /** A Sound is currently paused. */
  68487. this.isPaused = false;
  68488. this._sounds = [];
  68489. this._weights = [];
  68490. if (sounds.length !== weights.length) {
  68491. throw new Error('Sounds length does not equal weights length');
  68492. }
  68493. this.loop = loop;
  68494. this._weights = weights;
  68495. // Normalize the weights
  68496. var weightSum = 0;
  68497. for (var _i = 0, weights_1 = weights; _i < weights_1.length; _i++) {
  68498. var weight = weights_1[_i];
  68499. weightSum += weight;
  68500. }
  68501. var invWeightSum = weightSum > 0 ? 1 / weightSum : 0;
  68502. for (var i = 0; i < this._weights.length; i++) {
  68503. this._weights[i] *= invWeightSum;
  68504. }
  68505. this._sounds = sounds;
  68506. for (var _a = 0, _b = this._sounds; _a < _b.length; _a++) {
  68507. var sound = _b[_a];
  68508. sound.onEndedObservable.add(function () { _this._onended(); });
  68509. }
  68510. }
  68511. Object.defineProperty(WeightedSound.prototype, "directionalConeInnerAngle", {
  68512. /**
  68513. * The size of cone in degrees for a directional sound in which there will be no attenuation.
  68514. */
  68515. get: function () {
  68516. return this._coneInnerAngle;
  68517. },
  68518. /**
  68519. * The size of cone in degress for a directional sound in which there will be no attenuation.
  68520. */
  68521. set: function (value) {
  68522. if (value !== this._coneInnerAngle) {
  68523. if (this._coneOuterAngle < value) {
  68524. BABYLON.Tools.Error("directionalConeInnerAngle: outer angle of the cone must be superior or equal to the inner angle.");
  68525. return;
  68526. }
  68527. this._coneInnerAngle = value;
  68528. for (var _i = 0, _a = this._sounds; _i < _a.length; _i++) {
  68529. var sound = _a[_i];
  68530. sound.directionalConeInnerAngle = value;
  68531. }
  68532. }
  68533. },
  68534. enumerable: true,
  68535. configurable: true
  68536. });
  68537. Object.defineProperty(WeightedSound.prototype, "directionalConeOuterAngle", {
  68538. /**
  68539. * Size of cone in degrees for a directional sound outside of which there will be no sound.
  68540. * Listener angles between innerAngle and outerAngle will falloff linearly.
  68541. */
  68542. get: function () {
  68543. return this._coneOuterAngle;
  68544. },
  68545. /**
  68546. * Size of cone in degrees for a directional sound outside of which there will be no sound.
  68547. * Listener angles between innerAngle and outerAngle will falloff linearly.
  68548. */
  68549. set: function (value) {
  68550. if (value !== this._coneOuterAngle) {
  68551. if (value < this._coneInnerAngle) {
  68552. BABYLON.Tools.Error("directionalConeOuterAngle: outer angle of the cone must be superior or equal to the inner angle.");
  68553. return;
  68554. }
  68555. this._coneOuterAngle = value;
  68556. for (var _i = 0, _a = this._sounds; _i < _a.length; _i++) {
  68557. var sound = _a[_i];
  68558. sound.directionalConeOuterAngle = value;
  68559. }
  68560. }
  68561. },
  68562. enumerable: true,
  68563. configurable: true
  68564. });
  68565. Object.defineProperty(WeightedSound.prototype, "volume", {
  68566. /**
  68567. * Playback volume.
  68568. */
  68569. get: function () {
  68570. return this._volume;
  68571. },
  68572. /**
  68573. * Playback volume.
  68574. */
  68575. set: function (value) {
  68576. if (value !== this._volume) {
  68577. for (var _i = 0, _a = this._sounds; _i < _a.length; _i++) {
  68578. var sound = _a[_i];
  68579. sound.setVolume(value);
  68580. }
  68581. }
  68582. },
  68583. enumerable: true,
  68584. configurable: true
  68585. });
  68586. WeightedSound.prototype._onended = function () {
  68587. if (this._currentIndex !== undefined) {
  68588. this._sounds[this._currentIndex].autoplay = false;
  68589. }
  68590. if (this.loop && this.isPlaying) {
  68591. this.play();
  68592. }
  68593. else {
  68594. this.isPlaying = false;
  68595. }
  68596. };
  68597. /**
  68598. * Suspend playback
  68599. */
  68600. WeightedSound.prototype.pause = function () {
  68601. this.isPaused = true;
  68602. if (this._currentIndex !== undefined) {
  68603. this._sounds[this._currentIndex].pause();
  68604. }
  68605. };
  68606. /**
  68607. * Stop playback
  68608. */
  68609. WeightedSound.prototype.stop = function () {
  68610. this.isPlaying = false;
  68611. if (this._currentIndex !== undefined) {
  68612. this._sounds[this._currentIndex].stop();
  68613. }
  68614. };
  68615. /**
  68616. * Start playback.
  68617. * @param startOffset Position the clip head at a specific time in seconds.
  68618. */
  68619. WeightedSound.prototype.play = function (startOffset) {
  68620. if (!this.isPaused) {
  68621. this.stop();
  68622. var randomValue = Math.random();
  68623. var total = 0;
  68624. for (var i = 0; i < this._weights.length; i++) {
  68625. total += this._weights[i];
  68626. if (randomValue <= total) {
  68627. this._currentIndex = i;
  68628. break;
  68629. }
  68630. }
  68631. }
  68632. var sound = this._sounds[this._currentIndex];
  68633. if (sound.isReady()) {
  68634. sound.play(0, this.isPaused ? undefined : startOffset);
  68635. }
  68636. else {
  68637. sound.autoplay = true;
  68638. }
  68639. this.isPlaying = true;
  68640. this.isPaused = false;
  68641. };
  68642. return WeightedSound;
  68643. }());
  68644. BABYLON.WeightedSound = WeightedSound;
  68645. })(BABYLON || (BABYLON = {}));
  68646. //# sourceMappingURL=babylon.weightedsound.js.map
  68647. var BABYLON;
  68648. (function (BABYLON) {
  68649. // Adds the parser to the scene parsers.
  68650. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_AUDIO, function (parsedData, scene, container, rootUrl) {
  68651. // TODO: add sound
  68652. var loadedSounds = [];
  68653. var loadedSound;
  68654. container.sounds = container.sounds || [];
  68655. if (parsedData.sounds !== undefined && parsedData.sounds !== null) {
  68656. for (var index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  68657. var parsedSound = parsedData.sounds[index];
  68658. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  68659. if (!parsedSound.url)
  68660. parsedSound.url = parsedSound.name;
  68661. if (!loadedSounds[parsedSound.url]) {
  68662. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  68663. loadedSounds[parsedSound.url] = loadedSound;
  68664. container.sounds.push(loadedSound);
  68665. }
  68666. else {
  68667. container.sounds.push(BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]));
  68668. }
  68669. }
  68670. else {
  68671. container.sounds.push(new BABYLON.Sound(parsedSound.name, null, scene));
  68672. }
  68673. }
  68674. }
  68675. loadedSounds = [];
  68676. });
  68677. Object.defineProperty(BABYLON.Scene.prototype, "mainSoundTrack", {
  68678. get: function () {
  68679. var compo = this._getComponent(BABYLON.SceneComponentConstants.NAME_AUDIO);
  68680. if (!compo) {
  68681. compo = new AudioSceneComponent(this);
  68682. this._addComponent(compo);
  68683. }
  68684. if (!this._mainSoundTrack) {
  68685. this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  68686. }
  68687. return this._mainSoundTrack;
  68688. },
  68689. enumerable: true,
  68690. configurable: true
  68691. });
  68692. BABYLON.Scene.prototype.getSoundByName = function (name) {
  68693. var index;
  68694. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  68695. if (this.mainSoundTrack.soundCollection[index].name === name) {
  68696. return this.mainSoundTrack.soundCollection[index];
  68697. }
  68698. }
  68699. if (this.soundTracks) {
  68700. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  68701. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  68702. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  68703. return this.soundTracks[sdIndex].soundCollection[index];
  68704. }
  68705. }
  68706. }
  68707. }
  68708. return null;
  68709. };
  68710. Object.defineProperty(BABYLON.Scene.prototype, "audioEnabled", {
  68711. get: function () {
  68712. var compo = this._getComponent(BABYLON.SceneComponentConstants.NAME_AUDIO);
  68713. if (!compo) {
  68714. compo = new AudioSceneComponent(this);
  68715. this._addComponent(compo);
  68716. }
  68717. return compo.audioEnabled;
  68718. },
  68719. set: function (value) {
  68720. var compo = this._getComponent(BABYLON.SceneComponentConstants.NAME_AUDIO);
  68721. if (!compo) {
  68722. compo = new AudioSceneComponent(this);
  68723. this._addComponent(compo);
  68724. }
  68725. if (value) {
  68726. compo.enableAudio();
  68727. }
  68728. else {
  68729. compo.disableAudio();
  68730. }
  68731. },
  68732. enumerable: true,
  68733. configurable: true
  68734. });
  68735. Object.defineProperty(BABYLON.Scene.prototype, "headphone", {
  68736. get: function () {
  68737. var compo = this._getComponent(BABYLON.SceneComponentConstants.NAME_AUDIO);
  68738. if (!compo) {
  68739. compo = new AudioSceneComponent(this);
  68740. this._addComponent(compo);
  68741. }
  68742. return compo.headphone;
  68743. },
  68744. set: function (value) {
  68745. var compo = this._getComponent(BABYLON.SceneComponentConstants.NAME_AUDIO);
  68746. if (!compo) {
  68747. compo = new AudioSceneComponent(this);
  68748. this._addComponent(compo);
  68749. }
  68750. if (value) {
  68751. compo.switchAudioModeForHeadphones();
  68752. }
  68753. else {
  68754. compo.switchAudioModeForNormalSpeakers();
  68755. }
  68756. },
  68757. enumerable: true,
  68758. configurable: true
  68759. });
  68760. /**
  68761. * Defines the sound scene component responsible to manage any sounds
  68762. * in a given scene.
  68763. */
  68764. var AudioSceneComponent = /** @class */ (function () {
  68765. /**
  68766. * Creates a new instance of the component for the given scene
  68767. * @param scene Defines the scene to register the component in
  68768. */
  68769. function AudioSceneComponent(scene) {
  68770. /**
  68771. * The component name helpfull to identify the component in the list of scene components.
  68772. */
  68773. this.name = BABYLON.SceneComponentConstants.NAME_AUDIO;
  68774. this._audioEnabled = true;
  68775. this._headphone = false;
  68776. this.scene = scene;
  68777. scene.soundTracks = new Array();
  68778. scene.sounds = new Array();
  68779. }
  68780. Object.defineProperty(AudioSceneComponent.prototype, "audioEnabled", {
  68781. /**
  68782. * Gets whether audio is enabled or not.
  68783. * Please use related enable/disable method to switch state.
  68784. */
  68785. get: function () {
  68786. return this._audioEnabled;
  68787. },
  68788. enumerable: true,
  68789. configurable: true
  68790. });
  68791. Object.defineProperty(AudioSceneComponent.prototype, "headphone", {
  68792. /**
  68793. * Gets whether audio is outputing to headphone or not.
  68794. * Please use the according Switch methods to change output.
  68795. */
  68796. get: function () {
  68797. return this._headphone;
  68798. },
  68799. enumerable: true,
  68800. configurable: true
  68801. });
  68802. /**
  68803. * Registers the component in a given scene
  68804. */
  68805. AudioSceneComponent.prototype.register = function () {
  68806. this.scene._afterRenderStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERRENDER_AUDIO, this, this._afterRender);
  68807. };
  68808. /**
  68809. * Rebuilds the elements related to this component in case of
  68810. * context lost for instance.
  68811. */
  68812. AudioSceneComponent.prototype.rebuild = function () {
  68813. // Nothing to do here. (Not rendering related)
  68814. };
  68815. /**
  68816. * Serializes the component data to the specified json object
  68817. * @param serializationObject The object to serialize to
  68818. */
  68819. AudioSceneComponent.prototype.serialize = function (serializationObject) {
  68820. serializationObject.sounds = [];
  68821. if (this.scene.soundTracks) {
  68822. for (var index = 0; index < this.scene.soundTracks.length; index++) {
  68823. var soundtrack = this.scene.soundTracks[index];
  68824. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  68825. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  68826. }
  68827. }
  68828. }
  68829. };
  68830. /**
  68831. * Adds all the element from the container to the scene
  68832. * @param container the container holding the elements
  68833. */
  68834. AudioSceneComponent.prototype.addFromContainer = function (container) {
  68835. var _this = this;
  68836. if (!container.sounds) {
  68837. return;
  68838. }
  68839. container.sounds.forEach(function (sound) {
  68840. sound.play();
  68841. sound.autoplay = true;
  68842. _this.scene.mainSoundTrack.AddSound(sound);
  68843. });
  68844. };
  68845. /**
  68846. * Removes all the elements in the container from the scene
  68847. * @param container contains the elements to remove
  68848. */
  68849. AudioSceneComponent.prototype.removeFromContainer = function (container) {
  68850. var _this = this;
  68851. if (!container.sounds) {
  68852. return;
  68853. }
  68854. container.sounds.forEach(function (sound) {
  68855. sound.stop();
  68856. sound.autoplay = false;
  68857. _this.scene.mainSoundTrack.RemoveSound(sound);
  68858. });
  68859. };
  68860. /**
  68861. * Disposes the component and the associated ressources.
  68862. */
  68863. AudioSceneComponent.prototype.dispose = function () {
  68864. var scene = this.scene;
  68865. if (scene._mainSoundTrack) {
  68866. scene.mainSoundTrack.dispose();
  68867. }
  68868. if (scene.soundTracks) {
  68869. for (var scIndex = 0; scIndex < scene.soundTracks.length; scIndex++) {
  68870. scene.soundTracks[scIndex].dispose();
  68871. }
  68872. }
  68873. };
  68874. /**
  68875. * Disables audio in the associated scene.
  68876. */
  68877. AudioSceneComponent.prototype.disableAudio = function () {
  68878. var scene = this.scene;
  68879. this._audioEnabled = false;
  68880. var i;
  68881. for (i = 0; i < scene.mainSoundTrack.soundCollection.length; i++) {
  68882. scene.mainSoundTrack.soundCollection[i].pause();
  68883. }
  68884. if (scene.soundTracks) {
  68885. for (i = 0; i < scene.soundTracks.length; i++) {
  68886. for (var j = 0; j < scene.soundTracks[i].soundCollection.length; j++) {
  68887. scene.soundTracks[i].soundCollection[j].pause();
  68888. }
  68889. }
  68890. }
  68891. };
  68892. /**
  68893. * Enables audio in the associated scene.
  68894. */
  68895. AudioSceneComponent.prototype.enableAudio = function () {
  68896. var scene = this.scene;
  68897. this._audioEnabled = true;
  68898. var i;
  68899. for (i = 0; i < scene.mainSoundTrack.soundCollection.length; i++) {
  68900. if (scene.mainSoundTrack.soundCollection[i].isPaused) {
  68901. scene.mainSoundTrack.soundCollection[i].play();
  68902. }
  68903. }
  68904. if (scene.soundTracks) {
  68905. for (i = 0; i < scene.soundTracks.length; i++) {
  68906. for (var j = 0; j < scene.soundTracks[i].soundCollection.length; j++) {
  68907. if (scene.soundTracks[i].soundCollection[j].isPaused) {
  68908. scene.soundTracks[i].soundCollection[j].play();
  68909. }
  68910. }
  68911. }
  68912. }
  68913. };
  68914. /**
  68915. * Switch audio to headphone output.
  68916. */
  68917. AudioSceneComponent.prototype.switchAudioModeForHeadphones = function () {
  68918. var scene = this.scene;
  68919. this._headphone = true;
  68920. scene.mainSoundTrack.switchPanningModelToHRTF();
  68921. if (scene.soundTracks) {
  68922. for (var i = 0; i < scene.soundTracks.length; i++) {
  68923. scene.soundTracks[i].switchPanningModelToHRTF();
  68924. }
  68925. }
  68926. };
  68927. /**
  68928. * Switch audio to normal speakers.
  68929. */
  68930. AudioSceneComponent.prototype.switchAudioModeForNormalSpeakers = function () {
  68931. var scene = this.scene;
  68932. this._headphone = false;
  68933. scene.mainSoundTrack.switchPanningModelToEqualPower();
  68934. if (scene.soundTracks) {
  68935. for (var i = 0; i < scene.soundTracks.length; i++) {
  68936. scene.soundTracks[i].switchPanningModelToEqualPower();
  68937. }
  68938. }
  68939. };
  68940. AudioSceneComponent.prototype._afterRender = function () {
  68941. var scene = this.scene;
  68942. if (!this._audioEnabled || !scene._mainSoundTrack || !scene.soundTracks || (scene._mainSoundTrack.soundCollection.length === 0 && scene.soundTracks.length === 1)) {
  68943. return;
  68944. }
  68945. var listeningCamera;
  68946. var audioEngine = BABYLON.Engine.audioEngine;
  68947. if (scene.activeCameras.length > 0) {
  68948. listeningCamera = scene.activeCameras[0];
  68949. }
  68950. else {
  68951. listeningCamera = scene.activeCamera;
  68952. }
  68953. if (listeningCamera && audioEngine.audioContext) {
  68954. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  68955. // for VR cameras
  68956. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  68957. listeningCamera = listeningCamera.rigCameras[0];
  68958. }
  68959. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  68960. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  68961. cameraDirection.normalize();
  68962. // To avoid some errors on GearVR
  68963. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  68964. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  68965. }
  68966. var i;
  68967. for (i = 0; i < scene.mainSoundTrack.soundCollection.length; i++) {
  68968. var sound = scene.mainSoundTrack.soundCollection[i];
  68969. if (sound.useCustomAttenuation) {
  68970. sound.updateDistanceFromListener();
  68971. }
  68972. }
  68973. if (scene.soundTracks) {
  68974. for (i = 0; i < scene.soundTracks.length; i++) {
  68975. for (var j = 0; j < scene.soundTracks[i].soundCollection.length; j++) {
  68976. sound = scene.soundTracks[i].soundCollection[j];
  68977. if (sound.useCustomAttenuation) {
  68978. sound.updateDistanceFromListener();
  68979. }
  68980. }
  68981. }
  68982. }
  68983. }
  68984. };
  68985. return AudioSceneComponent;
  68986. }());
  68987. BABYLON.AudioSceneComponent = AudioSceneComponent;
  68988. })(BABYLON || (BABYLON = {}));
  68989. //# sourceMappingURL=babylon.audioSceneComponent.js.map
  68990. var BABYLON;
  68991. (function (BABYLON) {
  68992. /**
  68993. * This defines an action helpful to play a defined sound on a triggered action.
  68994. */
  68995. var PlaySoundAction = /** @class */ (function (_super) {
  68996. __extends(PlaySoundAction, _super);
  68997. /**
  68998. * Instantiate the action
  68999. * @param triggerOptions defines the trigger options
  69000. * @param sound defines the sound to play
  69001. * @param condition defines the trigger related conditions
  69002. */
  69003. function PlaySoundAction(triggerOptions, sound, condition) {
  69004. var _this = _super.call(this, triggerOptions, condition) || this;
  69005. _this._sound = sound;
  69006. return _this;
  69007. }
  69008. /** @hidden */
  69009. PlaySoundAction.prototype._prepare = function () {
  69010. };
  69011. /**
  69012. * Execute the action and play the sound.
  69013. */
  69014. PlaySoundAction.prototype.execute = function () {
  69015. if (this._sound !== undefined)
  69016. this._sound.play();
  69017. };
  69018. /**
  69019. * Serializes the actions and its related information.
  69020. * @param parent defines the object to serialize in
  69021. * @returns the serialized object
  69022. */
  69023. PlaySoundAction.prototype.serialize = function (parent) {
  69024. return _super.prototype._serialize.call(this, {
  69025. name: "PlaySoundAction",
  69026. properties: [{ name: "sound", value: this._sound.name }]
  69027. }, parent);
  69028. };
  69029. return PlaySoundAction;
  69030. }(BABYLON.Action));
  69031. BABYLON.PlaySoundAction = PlaySoundAction;
  69032. /**
  69033. * This defines an action helpful to stop a defined sound on a triggered action.
  69034. */
  69035. var StopSoundAction = /** @class */ (function (_super) {
  69036. __extends(StopSoundAction, _super);
  69037. /**
  69038. * Instantiate the action
  69039. * @param triggerOptions defines the trigger options
  69040. * @param sound defines the sound to stop
  69041. * @param condition defines the trigger related conditions
  69042. */
  69043. function StopSoundAction(triggerOptions, sound, condition) {
  69044. var _this = _super.call(this, triggerOptions, condition) || this;
  69045. _this._sound = sound;
  69046. return _this;
  69047. }
  69048. /** @hidden */
  69049. StopSoundAction.prototype._prepare = function () {
  69050. };
  69051. /**
  69052. * Execute the action and stop the sound.
  69053. */
  69054. StopSoundAction.prototype.execute = function () {
  69055. if (this._sound !== undefined)
  69056. this._sound.stop();
  69057. };
  69058. /**
  69059. * Serializes the actions and its related information.
  69060. * @param parent defines the object to serialize in
  69061. * @returns the serialized object
  69062. */
  69063. StopSoundAction.prototype.serialize = function (parent) {
  69064. return _super.prototype._serialize.call(this, {
  69065. name: "StopSoundAction",
  69066. properties: [{ name: "sound", value: this._sound.name }]
  69067. }, parent);
  69068. };
  69069. return StopSoundAction;
  69070. }(BABYLON.Action));
  69071. BABYLON.StopSoundAction = StopSoundAction;
  69072. })(BABYLON || (BABYLON = {}));
  69073. //# sourceMappingURL=babylon.directAudioActions.js.map
  69074. var BABYLON;
  69075. (function (BABYLON) {
  69076. var CubeTexture = /** @class */ (function (_super) {
  69077. __extends(CubeTexture, _super);
  69078. /**
  69079. * Creates a cube texture to use with reflection for instance. It can be based upon dds or six images as well
  69080. * as prefiltered data.
  69081. * @param rootUrl defines the url of the texture or the root name of the six images
  69082. * @param scene defines the scene the texture is attached to
  69083. * @param extensions defines the suffixes add to the picture name in case six images are in use like _px.jpg...
  69084. * @param noMipmap defines if mipmaps should be created or not
  69085. * @param files defines the six files to load for the different faces
  69086. * @param onLoad defines a callback triggered at the end of the file load if no errors occured
  69087. * @param onError defines a callback triggered in case of error during load
  69088. * @param format defines the internal format to use for the texture once loaded
  69089. * @param prefiltered defines whether or not the texture is created from prefiltered data
  69090. * @param forcedExtension defines the extensions to use (force a special type of file to load) in case it is different from the file name
  69091. * @param createPolynomials defines whether or not to create polynomial harmonics from the texture data if necessary
  69092. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  69093. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  69094. * @return the cube texture
  69095. */
  69096. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension, createPolynomials, lodScale, lodOffset) {
  69097. if (extensions === void 0) { extensions = null; }
  69098. if (noMipmap === void 0) { noMipmap = false; }
  69099. if (files === void 0) { files = null; }
  69100. if (onLoad === void 0) { onLoad = null; }
  69101. if (onError === void 0) { onError = null; }
  69102. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  69103. if (prefiltered === void 0) { prefiltered = false; }
  69104. if (forcedExtension === void 0) { forcedExtension = null; }
  69105. if (createPolynomials === void 0) { createPolynomials = false; }
  69106. if (lodScale === void 0) { lodScale = 0.8; }
  69107. if (lodOffset === void 0) { lodOffset = 0; }
  69108. var _this = _super.call(this, scene) || this;
  69109. /**
  69110. * Gets or sets the center of the bounding box associated with the cube texture
  69111. * It must define where the camera used to render the texture was set
  69112. */
  69113. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  69114. _this._rotationY = 0;
  69115. /** @hidden */
  69116. _this._prefiltered = false;
  69117. _this.name = rootUrl;
  69118. _this.url = rootUrl;
  69119. _this._noMipmap = noMipmap;
  69120. _this.hasAlpha = false;
  69121. _this._format = format;
  69122. _this.isCube = true;
  69123. _this._textureMatrix = BABYLON.Matrix.Identity();
  69124. _this._createPolynomials = createPolynomials;
  69125. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  69126. if (!rootUrl && !files) {
  69127. return _this;
  69128. }
  69129. var lastDot = rootUrl.lastIndexOf(".");
  69130. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  69131. var isDDS = (extension === ".dds");
  69132. var isEnv = (extension === ".env");
  69133. if (isEnv) {
  69134. _this.gammaSpace = false;
  69135. _this._prefiltered = false;
  69136. }
  69137. else {
  69138. _this._prefiltered = prefiltered;
  69139. if (prefiltered) {
  69140. _this.gammaSpace = false;
  69141. }
  69142. }
  69143. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  69144. if (!files) {
  69145. if (!isEnv && !isDDS && !extensions) {
  69146. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  69147. }
  69148. files = [];
  69149. if (extensions) {
  69150. for (var index = 0; index < extensions.length; index++) {
  69151. files.push(rootUrl + extensions[index]);
  69152. }
  69153. }
  69154. }
  69155. _this._files = files;
  69156. if (!_this._texture) {
  69157. if (!scene.useDelayedTextureLoading) {
  69158. if (prefiltered) {
  69159. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, lodScale, lodOffset, onLoad, onError, format, forcedExtension, _this._createPolynomials);
  69160. }
  69161. else {
  69162. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension, false, lodScale, lodOffset);
  69163. }
  69164. }
  69165. else {
  69166. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  69167. }
  69168. }
  69169. else if (onLoad) {
  69170. if (_this._texture.isReady) {
  69171. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  69172. }
  69173. else {
  69174. _this._texture.onLoadedObservable.add(onLoad);
  69175. }
  69176. }
  69177. return _this;
  69178. }
  69179. Object.defineProperty(CubeTexture.prototype, "boundingBoxSize", {
  69180. get: function () {
  69181. return this._boundingBoxSize;
  69182. },
  69183. /**
  69184. * Gets or sets the size of the bounding box associated with the cube texture
  69185. * When defined, the cubemap will switch to local mode
  69186. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  69187. * @example https://www.babylonjs-playground.com/#RNASML
  69188. */
  69189. set: function (value) {
  69190. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  69191. return;
  69192. }
  69193. this._boundingBoxSize = value;
  69194. var scene = this.getScene();
  69195. if (scene) {
  69196. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  69197. }
  69198. },
  69199. enumerable: true,
  69200. configurable: true
  69201. });
  69202. Object.defineProperty(CubeTexture.prototype, "rotationY", {
  69203. /**
  69204. * Gets texture matrix rotation angle around Y axis radians.
  69205. */
  69206. get: function () {
  69207. return this._rotationY;
  69208. },
  69209. /**
  69210. * Sets texture matrix rotation angle around Y axis in radians.
  69211. */
  69212. set: function (value) {
  69213. this._rotationY = value;
  69214. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  69215. },
  69216. enumerable: true,
  69217. configurable: true
  69218. });
  69219. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  69220. var rootUrlKey = "";
  69221. files.forEach(function (url) { return rootUrlKey += url; });
  69222. return new CubeTexture(rootUrlKey, scene, null, noMipmap, files);
  69223. };
  69224. /**
  69225. * Creates and return a texture created from prefilterd data by tools like IBL Baker or Lys.
  69226. * @param url defines the url of the prefiltered texture
  69227. * @param scene defines the scene the texture is attached to
  69228. * @param forcedExtension defines the extension of the file if different from the url
  69229. * @param createPolynomials defines whether or not to create polynomial harmonics from the texture data if necessary
  69230. * @return the prefiltered texture
  69231. */
  69232. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension, createPolynomials) {
  69233. if (forcedExtension === void 0) { forcedExtension = null; }
  69234. if (createPolynomials === void 0) { createPolynomials = true; }
  69235. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension, createPolynomials);
  69236. };
  69237. // Methods
  69238. CubeTexture.prototype.delayLoad = function () {
  69239. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  69240. return;
  69241. }
  69242. var scene = this.getScene();
  69243. if (!scene) {
  69244. return;
  69245. }
  69246. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  69247. this._texture = this._getFromCache(this.url, this._noMipmap);
  69248. if (!this._texture) {
  69249. if (this._prefiltered) {
  69250. this._texture = scene.getEngine().createPrefilteredCubeTexture(this.url, scene, this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format, undefined, this._createPolynomials);
  69251. }
  69252. else {
  69253. this._texture = scene.getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, undefined, undefined, this._format);
  69254. }
  69255. }
  69256. };
  69257. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  69258. return this._textureMatrix;
  69259. };
  69260. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  69261. this._textureMatrix = value;
  69262. };
  69263. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  69264. var texture = BABYLON.SerializationHelper.Parse(function () {
  69265. var prefiltered = false;
  69266. if (parsedTexture.prefiltered) {
  69267. prefiltered = parsedTexture.prefiltered;
  69268. }
  69269. return new CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions, false, null, null, null, undefined, prefiltered);
  69270. }, parsedTexture, scene);
  69271. // Local Cubemaps
  69272. if (parsedTexture.boundingBoxPosition) {
  69273. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  69274. }
  69275. if (parsedTexture.boundingBoxSize) {
  69276. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  69277. }
  69278. // Animations
  69279. if (parsedTexture.animations) {
  69280. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  69281. var parsedAnimation = parsedTexture.animations[animationIndex];
  69282. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  69283. }
  69284. }
  69285. return texture;
  69286. };
  69287. CubeTexture.prototype.clone = function () {
  69288. var _this = this;
  69289. return BABYLON.SerializationHelper.Clone(function () {
  69290. var scene = _this.getScene();
  69291. if (!scene) {
  69292. return _this;
  69293. }
  69294. return new CubeTexture(_this.url, scene, _this._extensions, _this._noMipmap, _this._files);
  69295. }, this);
  69296. };
  69297. __decorate([
  69298. BABYLON.serialize("rotationY")
  69299. ], CubeTexture.prototype, "rotationY", null);
  69300. return CubeTexture;
  69301. }(BABYLON.BaseTexture));
  69302. BABYLON.CubeTexture = CubeTexture;
  69303. })(BABYLON || (BABYLON = {}));
  69304. //# sourceMappingURL=babylon.cubeTexture.js.map
  69305. var BABYLON;
  69306. (function (BABYLON) {
  69307. /**
  69308. * Raw cube texture where the raw buffers are passed in
  69309. */
  69310. var RawCubeTexture = /** @class */ (function (_super) {
  69311. __extends(RawCubeTexture, _super);
  69312. /**
  69313. * Creates a cube texture where the raw buffers are passed in.
  69314. * @param scene defines the scene the texture is attached to
  69315. * @param data defines the array of data to use to create each face
  69316. * @param size defines the size of the textures
  69317. * @param format defines the format of the data
  69318. * @param type defines the type of the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  69319. * @param generateMipMaps defines if the engine should generate the mip levels
  69320. * @param invertY defines if data must be stored with Y axis inverted
  69321. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  69322. * @param compression defines the compression used (null by default)
  69323. */
  69324. function RawCubeTexture(scene, data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  69325. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  69326. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  69327. if (generateMipMaps === void 0) { generateMipMaps = false; }
  69328. if (invertY === void 0) { invertY = false; }
  69329. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  69330. if (compression === void 0) { compression = null; }
  69331. var _this = _super.call(this, "", scene) || this;
  69332. _this._texture = scene.getEngine().createRawCubeTexture(data, size, format, type, generateMipMaps, invertY, samplingMode, compression);
  69333. return _this;
  69334. }
  69335. /**
  69336. * Updates the raw cube texture.
  69337. * @param data defines the data to store
  69338. * @param format defines the data format
  69339. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  69340. * @param invertY defines if data must be stored with Y axis inverted
  69341. * @param compression defines the compression used (null by default)
  69342. * @param level defines which level of the texture to update
  69343. */
  69344. RawCubeTexture.prototype.update = function (data, format, type, invertY, compression, level) {
  69345. if (compression === void 0) { compression = null; }
  69346. if (level === void 0) { level = 0; }
  69347. this._texture.getEngine().updateRawCubeTexture(this._texture, data, format, type, invertY, compression);
  69348. };
  69349. /**
  69350. * Updates a raw cube texture with RGBD encoded data.
  69351. * @param data defines the array of data [mipmap][face] to use to create each face
  69352. * @param sphericalPolynomial defines the spherical polynomial for irradiance
  69353. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  69354. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  69355. * @returns a promsie that resolves when the operation is complete
  69356. */
  69357. RawCubeTexture.prototype.updateRGBDAsync = function (data, sphericalPolynomial, lodScale, lodOffset) {
  69358. if (sphericalPolynomial === void 0) { sphericalPolynomial = null; }
  69359. if (lodScale === void 0) { lodScale = 0.8; }
  69360. if (lodOffset === void 0) { lodOffset = 0; }
  69361. return RawCubeTexture._UpdateRGBDAsync(this._texture, data, sphericalPolynomial, lodScale, lodOffset);
  69362. };
  69363. /**
  69364. * Clones the raw cube texture.
  69365. * @return a new cube texture
  69366. */
  69367. RawCubeTexture.prototype.clone = function () {
  69368. var _this = this;
  69369. return BABYLON.SerializationHelper.Clone(function () {
  69370. var scene = _this.getScene();
  69371. var internalTexture = _this._texture;
  69372. var texture = new RawCubeTexture(scene, internalTexture._bufferViewArray, internalTexture.width, internalTexture.format, internalTexture.type, internalTexture.generateMipMaps, internalTexture.invertY, internalTexture.samplingMode, internalTexture._compression);
  69373. if (internalTexture.dataSource === BABYLON.InternalTexture.DATASOURCE_CUBERAW_RGBD) {
  69374. texture.updateRGBDAsync(internalTexture._bufferViewArrayArray, internalTexture._sphericalPolynomial, internalTexture._lodGenerationScale, internalTexture._lodGenerationOffset);
  69375. }
  69376. return texture;
  69377. }, this);
  69378. };
  69379. /** @hidden */
  69380. RawCubeTexture._UpdateRGBDAsync = function (internalTexture, data, sphericalPolynomial, lodScale, lodOffset) {
  69381. internalTexture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBERAW_RGBD;
  69382. internalTexture._bufferViewArrayArray = data;
  69383. internalTexture._lodGenerationScale = lodScale;
  69384. internalTexture._lodGenerationOffset = lodOffset;
  69385. internalTexture._sphericalPolynomial = sphericalPolynomial;
  69386. return BABYLON.EnvironmentTextureTools.UploadLevelsAsync(internalTexture, data).then(function () {
  69387. internalTexture.isReady = true;
  69388. });
  69389. };
  69390. return RawCubeTexture;
  69391. }(BABYLON.CubeTexture));
  69392. BABYLON.RawCubeTexture = RawCubeTexture;
  69393. })(BABYLON || (BABYLON = {}));
  69394. //# sourceMappingURL=babylon.rawCubeTexture.js.map
  69395. var BABYLON;
  69396. (function (BABYLON) {
  69397. var RenderTargetTexture = /** @class */ (function (_super) {
  69398. __extends(RenderTargetTexture, _super);
  69399. /**
  69400. * Instantiate a render target texture. This is mainly to render of screen the scene to for instance apply post processse
  69401. * or used a shadow, depth texture...
  69402. * @param name The friendly name of the texture
  69403. * @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)
  69404. * @param scene The scene the RTT belongs to. The latest created scene will be used if not precised.
  69405. * @param generateMipMaps True if mip maps need to be generated after render.
  69406. * @param doNotChangeAspectRatio True to not change the aspect ratio of the scene in the RTT
  69407. * @param type The type of the buffer in the RTT (int, half float, float...)
  69408. * @param isCube True if a cube texture needs to be created
  69409. * @param samplingMode The sampling mode to be usedwith the render target (Linear, Nearest...)
  69410. * @param generateDepthBuffer True to generate a depth buffer
  69411. * @param generateStencilBuffer True to generate a stencil buffer
  69412. * @param isMulti True if multiple textures need to be created (Draw Buffers)
  69413. * @param format The internal format of the buffer in the RTT (RED, RG, RGB, RGBA, ALPHA...)
  69414. */
  69415. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti, format) {
  69416. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  69417. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  69418. if (isCube === void 0) { isCube = false; }
  69419. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  69420. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  69421. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  69422. if (isMulti === void 0) { isMulti = false; }
  69423. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  69424. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  69425. _this.isCube = isCube;
  69426. _this.renderParticles = true;
  69427. _this.renderSprites = false;
  69428. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  69429. _this.ignoreCameraViewport = false;
  69430. // Events
  69431. /**
  69432. * An event triggered when the texture is unbind.
  69433. */
  69434. _this.onBeforeBindObservable = new BABYLON.Observable();
  69435. /**
  69436. * An event triggered when the texture is unbind.
  69437. */
  69438. _this.onAfterUnbindObservable = new BABYLON.Observable();
  69439. /**
  69440. * An event triggered before rendering the texture
  69441. */
  69442. _this.onBeforeRenderObservable = new BABYLON.Observable();
  69443. /**
  69444. * An event triggered after rendering the texture
  69445. */
  69446. _this.onAfterRenderObservable = new BABYLON.Observable();
  69447. /**
  69448. * An event triggered after the texture clear
  69449. */
  69450. _this.onClearObservable = new BABYLON.Observable();
  69451. _this._currentRefreshId = -1;
  69452. _this._refreshRate = 1;
  69453. _this._samples = 1;
  69454. /**
  69455. * Gets or sets the center of the bounding box associated with the texture (when in cube mode)
  69456. * It must define where the camera used to render the texture is set
  69457. */
  69458. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  69459. scene = _this.getScene();
  69460. if (!scene) {
  69461. return _this;
  69462. }
  69463. _this.renderList = new Array();
  69464. _this._engine = scene.getEngine();
  69465. _this.name = name;
  69466. _this.isRenderTarget = true;
  69467. _this._initialSizeParameter = size;
  69468. _this._processSizeParameter(size);
  69469. _this._resizeObserver = _this.getScene().getEngine().onResizeObservable.add(function () {
  69470. });
  69471. _this._generateMipMaps = generateMipMaps ? true : false;
  69472. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  69473. // Rendering groups
  69474. _this._renderingManager = new BABYLON.RenderingManager(scene);
  69475. _this._renderingManager._useSceneAutoClearSetup = true;
  69476. if (isMulti) {
  69477. return _this;
  69478. }
  69479. _this._renderTargetOptions = {
  69480. generateMipMaps: generateMipMaps,
  69481. type: type,
  69482. format: format,
  69483. samplingMode: samplingMode,
  69484. generateDepthBuffer: generateDepthBuffer,
  69485. generateStencilBuffer: generateStencilBuffer
  69486. };
  69487. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  69488. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  69489. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  69490. }
  69491. if (isCube) {
  69492. _this._texture = scene.getEngine().createRenderTargetCubeTexture(_this.getRenderSize(), _this._renderTargetOptions);
  69493. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  69494. _this._textureMatrix = BABYLON.Matrix.Identity();
  69495. }
  69496. else {
  69497. _this._texture = scene.getEngine().createRenderTargetTexture(_this._size, _this._renderTargetOptions);
  69498. }
  69499. return _this;
  69500. }
  69501. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  69502. get: function () {
  69503. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  69504. },
  69505. enumerable: true,
  69506. configurable: true
  69507. });
  69508. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  69509. get: function () {
  69510. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  69511. },
  69512. enumerable: true,
  69513. configurable: true
  69514. });
  69515. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  69516. get: function () {
  69517. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  69518. },
  69519. enumerable: true,
  69520. configurable: true
  69521. });
  69522. Object.defineProperty(RenderTargetTexture.prototype, "renderList", {
  69523. /**
  69524. * Use this list to define the list of mesh you want to render.
  69525. */
  69526. get: function () {
  69527. return this._renderList;
  69528. },
  69529. set: function (value) {
  69530. this._renderList = value;
  69531. if (this._renderList) {
  69532. this._hookArray(this._renderList);
  69533. }
  69534. },
  69535. enumerable: true,
  69536. configurable: true
  69537. });
  69538. RenderTargetTexture.prototype._hookArray = function (array) {
  69539. var _this = this;
  69540. var oldPush = array.push;
  69541. array.push = function () {
  69542. var items = [];
  69543. for (var _i = 0; _i < arguments.length; _i++) {
  69544. items[_i] = arguments[_i];
  69545. }
  69546. var result = oldPush.apply(array, items);
  69547. _this.getScene().meshes.forEach(function (mesh) {
  69548. mesh._markSubMeshesAsLightDirty();
  69549. });
  69550. return result;
  69551. };
  69552. var oldSplice = array.splice;
  69553. array.splice = function (index, deleteCount) {
  69554. var deleted = oldSplice.apply(array, [index, deleteCount]);
  69555. _this.getScene().meshes.forEach(function (mesh) {
  69556. mesh._markSubMeshesAsLightDirty();
  69557. });
  69558. return deleted;
  69559. };
  69560. };
  69561. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  69562. set: function (callback) {
  69563. if (this._onAfterUnbindObserver) {
  69564. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  69565. }
  69566. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  69567. },
  69568. enumerable: true,
  69569. configurable: true
  69570. });
  69571. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  69572. set: function (callback) {
  69573. if (this._onBeforeRenderObserver) {
  69574. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  69575. }
  69576. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  69577. },
  69578. enumerable: true,
  69579. configurable: true
  69580. });
  69581. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  69582. set: function (callback) {
  69583. if (this._onAfterRenderObserver) {
  69584. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  69585. }
  69586. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  69587. },
  69588. enumerable: true,
  69589. configurable: true
  69590. });
  69591. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  69592. set: function (callback) {
  69593. if (this._onClearObserver) {
  69594. this.onClearObservable.remove(this._onClearObserver);
  69595. }
  69596. this._onClearObserver = this.onClearObservable.add(callback);
  69597. },
  69598. enumerable: true,
  69599. configurable: true
  69600. });
  69601. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  69602. get: function () {
  69603. return this._renderTargetOptions;
  69604. },
  69605. enumerable: true,
  69606. configurable: true
  69607. });
  69608. RenderTargetTexture.prototype._onRatioRescale = function () {
  69609. if (this._sizeRatio) {
  69610. this.resize(this._initialSizeParameter);
  69611. }
  69612. };
  69613. Object.defineProperty(RenderTargetTexture.prototype, "boundingBoxSize", {
  69614. get: function () {
  69615. return this._boundingBoxSize;
  69616. },
  69617. /**
  69618. * Gets or sets the size of the bounding box associated with the texture (when in cube mode)
  69619. * When defined, the cubemap will switch to local mode
  69620. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  69621. * @example https://www.babylonjs-playground.com/#RNASML
  69622. */
  69623. set: function (value) {
  69624. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  69625. return;
  69626. }
  69627. this._boundingBoxSize = value;
  69628. var scene = this.getScene();
  69629. if (scene) {
  69630. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  69631. }
  69632. },
  69633. enumerable: true,
  69634. configurable: true
  69635. });
  69636. /**
  69637. * Creates a depth stencil texture.
  69638. * This is only available in WebGL 2 or with the depth texture extension available.
  69639. * @param comparisonFunction Specifies the comparison function to set on the texture. If 0 or undefined, the texture is not in comparison mode
  69640. * @param bilinearFiltering Specifies whether or not bilinear filtering is enable on the texture
  69641. * @param generateStencil Specifies whether or not a stencil should be allocated in the texture
  69642. */
  69643. RenderTargetTexture.prototype.createDepthStencilTexture = function (comparisonFunction, bilinearFiltering, generateStencil) {
  69644. if (comparisonFunction === void 0) { comparisonFunction = 0; }
  69645. if (bilinearFiltering === void 0) { bilinearFiltering = true; }
  69646. if (generateStencil === void 0) { generateStencil = false; }
  69647. if (!this.getScene()) {
  69648. return;
  69649. }
  69650. var engine = this.getScene().getEngine();
  69651. this.depthStencilTexture = engine.createDepthStencilTexture(this._size, {
  69652. bilinearFiltering: bilinearFiltering,
  69653. comparisonFunction: comparisonFunction,
  69654. generateStencil: generateStencil,
  69655. isCube: this.isCube
  69656. });
  69657. engine.setFrameBufferDepthStencilTexture(this);
  69658. };
  69659. RenderTargetTexture.prototype._processSizeParameter = function (size) {
  69660. if (size.ratio) {
  69661. this._sizeRatio = size.ratio;
  69662. this._size = {
  69663. width: this._bestReflectionRenderTargetDimension(this._engine.getRenderWidth(), this._sizeRatio),
  69664. height: this._bestReflectionRenderTargetDimension(this._engine.getRenderHeight(), this._sizeRatio)
  69665. };
  69666. }
  69667. else {
  69668. this._size = size;
  69669. }
  69670. };
  69671. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  69672. get: function () {
  69673. return this._samples;
  69674. },
  69675. set: function (value) {
  69676. if (this._samples === value) {
  69677. return;
  69678. }
  69679. var scene = this.getScene();
  69680. if (!scene) {
  69681. return;
  69682. }
  69683. this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  69684. },
  69685. enumerable: true,
  69686. configurable: true
  69687. });
  69688. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  69689. this._currentRefreshId = -1;
  69690. };
  69691. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  69692. get: function () {
  69693. return this._refreshRate;
  69694. },
  69695. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  69696. set: function (value) {
  69697. this._refreshRate = value;
  69698. this.resetRefreshCounter();
  69699. },
  69700. enumerable: true,
  69701. configurable: true
  69702. });
  69703. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  69704. if (!this._postProcessManager) {
  69705. var scene = this.getScene();
  69706. if (!scene) {
  69707. return;
  69708. }
  69709. this._postProcessManager = new BABYLON.PostProcessManager(scene);
  69710. this._postProcesses = new Array();
  69711. }
  69712. this._postProcesses.push(postProcess);
  69713. this._postProcesses[0].autoClear = false;
  69714. };
  69715. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  69716. if (!this._postProcesses) {
  69717. return;
  69718. }
  69719. if (dispose) {
  69720. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  69721. var postProcess = _a[_i];
  69722. postProcess.dispose();
  69723. }
  69724. }
  69725. this._postProcesses = [];
  69726. };
  69727. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  69728. if (!this._postProcesses) {
  69729. return;
  69730. }
  69731. var index = this._postProcesses.indexOf(postProcess);
  69732. if (index === -1) {
  69733. return;
  69734. }
  69735. this._postProcesses.splice(index, 1);
  69736. if (this._postProcesses.length > 0) {
  69737. this._postProcesses[0].autoClear = false;
  69738. }
  69739. };
  69740. /** @hidden */
  69741. RenderTargetTexture.prototype._shouldRender = function () {
  69742. if (this._currentRefreshId === -1) { // At least render once
  69743. this._currentRefreshId = 1;
  69744. return true;
  69745. }
  69746. if (this.refreshRate === this._currentRefreshId) {
  69747. this._currentRefreshId = 1;
  69748. return true;
  69749. }
  69750. this._currentRefreshId++;
  69751. return false;
  69752. };
  69753. RenderTargetTexture.prototype.getRenderSize = function () {
  69754. if (this._size.width) {
  69755. return this._size.width;
  69756. }
  69757. return this._size;
  69758. };
  69759. RenderTargetTexture.prototype.getRenderWidth = function () {
  69760. if (this._size.width) {
  69761. return this._size.width;
  69762. }
  69763. return this._size;
  69764. };
  69765. RenderTargetTexture.prototype.getRenderHeight = function () {
  69766. if (this._size.width) {
  69767. return this._size.height;
  69768. }
  69769. return this._size;
  69770. };
  69771. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  69772. get: function () {
  69773. return true;
  69774. },
  69775. enumerable: true,
  69776. configurable: true
  69777. });
  69778. RenderTargetTexture.prototype.scale = function (ratio) {
  69779. var newSize = this.getRenderSize() * ratio;
  69780. this.resize(newSize);
  69781. };
  69782. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  69783. if (this.isCube) {
  69784. return this._textureMatrix;
  69785. }
  69786. return _super.prototype.getReflectionTextureMatrix.call(this);
  69787. };
  69788. RenderTargetTexture.prototype.resize = function (size) {
  69789. this.releaseInternalTexture();
  69790. var scene = this.getScene();
  69791. if (!scene) {
  69792. return;
  69793. }
  69794. this._processSizeParameter(size);
  69795. if (this.isCube) {
  69796. this._texture = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);
  69797. }
  69798. else {
  69799. this._texture = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);
  69800. }
  69801. };
  69802. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  69803. if (useCameraPostProcess === void 0) { useCameraPostProcess = false; }
  69804. if (dumpForDebug === void 0) { dumpForDebug = false; }
  69805. var scene = this.getScene();
  69806. if (!scene) {
  69807. return;
  69808. }
  69809. var engine = scene.getEngine();
  69810. if (this.useCameraPostProcesses !== undefined) {
  69811. useCameraPostProcess = this.useCameraPostProcesses;
  69812. }
  69813. if (this._waitingRenderList) {
  69814. this.renderList = [];
  69815. for (var index = 0; index < this._waitingRenderList.length; index++) {
  69816. var id = this._waitingRenderList[index];
  69817. var mesh_1 = scene.getMeshByID(id);
  69818. if (mesh_1) {
  69819. this.renderList.push(mesh_1);
  69820. }
  69821. }
  69822. delete this._waitingRenderList;
  69823. }
  69824. // Is predicate defined?
  69825. if (this.renderListPredicate) {
  69826. if (this.renderList) {
  69827. this.renderList.splice(0); // Clear previous renderList
  69828. }
  69829. else {
  69830. this.renderList = [];
  69831. }
  69832. var scene = this.getScene();
  69833. if (!scene) {
  69834. return;
  69835. }
  69836. var sceneMeshes = scene.meshes;
  69837. for (var index = 0; index < sceneMeshes.length; index++) {
  69838. var mesh = sceneMeshes[index];
  69839. if (this.renderListPredicate(mesh)) {
  69840. this.renderList.push(mesh);
  69841. }
  69842. }
  69843. }
  69844. this.onBeforeBindObservable.notifyObservers(this);
  69845. // Set custom projection.
  69846. // Needs to be before binding to prevent changing the aspect ratio.
  69847. var camera;
  69848. if (this.activeCamera) {
  69849. camera = this.activeCamera;
  69850. engine.setViewport(this.activeCamera.viewport, this.getRenderWidth(), this.getRenderHeight());
  69851. if (this.activeCamera !== scene.activeCamera) {
  69852. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  69853. }
  69854. }
  69855. else {
  69856. camera = scene.activeCamera;
  69857. if (camera) {
  69858. engine.setViewport(camera.viewport, this.getRenderWidth(), this.getRenderHeight());
  69859. }
  69860. }
  69861. // Prepare renderingManager
  69862. this._renderingManager.reset();
  69863. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  69864. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  69865. var sceneRenderId = scene.getRenderId();
  69866. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  69867. var mesh = currentRenderList[meshIndex];
  69868. if (mesh) {
  69869. if (!mesh.isReady(this.refreshRate === 0)) {
  69870. this.resetRefreshCounter();
  69871. continue;
  69872. }
  69873. mesh._preActivateForIntermediateRendering(sceneRenderId);
  69874. var isMasked = void 0;
  69875. if (!this.renderList && camera) {
  69876. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  69877. }
  69878. else {
  69879. isMasked = false;
  69880. }
  69881. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  69882. mesh._activate(sceneRenderId);
  69883. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  69884. var subMesh = mesh.subMeshes[subIndex];
  69885. scene._activeIndices.addCount(subMesh.indexCount, false);
  69886. this._renderingManager.dispatch(subMesh, mesh);
  69887. }
  69888. }
  69889. }
  69890. }
  69891. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  69892. var particleSystem = scene.particleSystems[particleIndex];
  69893. var emitter = particleSystem.emitter;
  69894. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  69895. continue;
  69896. }
  69897. if (currentRenderList.indexOf(emitter) >= 0) {
  69898. this._renderingManager.dispatchParticles(particleSystem);
  69899. }
  69900. }
  69901. if (this.isCube) {
  69902. for (var face = 0; face < 6; face++) {
  69903. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  69904. scene.incrementRenderId();
  69905. scene.resetCachedMaterial();
  69906. }
  69907. }
  69908. else {
  69909. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  69910. }
  69911. this.onAfterUnbindObservable.notifyObservers(this);
  69912. if (scene.activeCamera) {
  69913. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  69914. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  69915. }
  69916. engine.setViewport(scene.activeCamera.viewport);
  69917. }
  69918. scene.resetCachedMaterial();
  69919. };
  69920. RenderTargetTexture.prototype._bestReflectionRenderTargetDimension = function (renderDimension, scale) {
  69921. var minimum = 128;
  69922. var x = renderDimension * scale;
  69923. var curved = BABYLON.Tools.NearestPOT(x + (minimum * minimum / (minimum + x)));
  69924. // Ensure we don't exceed the render dimension (while staying POT)
  69925. return Math.min(BABYLON.Tools.FloorPOT(renderDimension), curved);
  69926. };
  69927. RenderTargetTexture.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  69928. var _this = this;
  69929. if (!this._texture) {
  69930. return;
  69931. }
  69932. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  69933. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  69934. });
  69935. };
  69936. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  69937. var scene = this.getScene();
  69938. if (!scene) {
  69939. return;
  69940. }
  69941. var engine = scene.getEngine();
  69942. if (!this._texture) {
  69943. return;
  69944. }
  69945. // Bind
  69946. if (this._postProcessManager) {
  69947. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  69948. }
  69949. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  69950. if (this._texture) {
  69951. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport, this.depthStencilTexture ? this.depthStencilTexture : undefined);
  69952. }
  69953. }
  69954. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  69955. // Clear
  69956. if (this.onClearObservable.hasObservers()) {
  69957. this.onClearObservable.notifyObservers(engine);
  69958. }
  69959. else {
  69960. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  69961. }
  69962. if (!this._doNotChangeAspectRatio) {
  69963. scene.updateTransformMatrix(true);
  69964. }
  69965. // Render
  69966. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  69967. if (this._postProcessManager) {
  69968. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  69969. }
  69970. else if (useCameraPostProcess) {
  69971. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  69972. }
  69973. if (!this._doNotChangeAspectRatio) {
  69974. scene.updateTransformMatrix(true);
  69975. }
  69976. // Dump ?
  69977. if (dumpForDebug) {
  69978. BABYLON.Tools.DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), engine);
  69979. }
  69980. // Unbind
  69981. if (!this.isCube || faceIndex === 5) {
  69982. if (this.isCube) {
  69983. if (faceIndex === 5) {
  69984. engine.generateMipMapsForCubemap(this._texture);
  69985. }
  69986. }
  69987. this.unbindFrameBuffer(engine, faceIndex);
  69988. }
  69989. else {
  69990. this.onAfterRenderObservable.notifyObservers(faceIndex);
  69991. }
  69992. };
  69993. /**
  69994. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  69995. * This allowed control for front to back rendering or reversly depending of the special needs.
  69996. *
  69997. * @param renderingGroupId The rendering group id corresponding to its index
  69998. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  69999. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  70000. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  70001. */
  70002. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  70003. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  70004. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  70005. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  70006. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  70007. };
  70008. /**
  70009. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  70010. *
  70011. * @param renderingGroupId The rendering group id corresponding to its index
  70012. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  70013. */
  70014. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  70015. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  70016. this._renderingManager._useSceneAutoClearSetup = false;
  70017. };
  70018. RenderTargetTexture.prototype.clone = function () {
  70019. var textureSize = this.getSize();
  70020. 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);
  70021. // Base texture
  70022. newTexture.hasAlpha = this.hasAlpha;
  70023. newTexture.level = this.level;
  70024. // RenderTarget Texture
  70025. newTexture.coordinatesMode = this.coordinatesMode;
  70026. if (this.renderList) {
  70027. newTexture.renderList = this.renderList.slice(0);
  70028. }
  70029. return newTexture;
  70030. };
  70031. RenderTargetTexture.prototype.serialize = function () {
  70032. if (!this.name) {
  70033. return null;
  70034. }
  70035. var serializationObject = _super.prototype.serialize.call(this);
  70036. serializationObject.renderTargetSize = this.getRenderSize();
  70037. serializationObject.renderList = [];
  70038. if (this.renderList) {
  70039. for (var index = 0; index < this.renderList.length; index++) {
  70040. serializationObject.renderList.push(this.renderList[index].id);
  70041. }
  70042. }
  70043. return serializationObject;
  70044. };
  70045. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  70046. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  70047. var objBuffer = this.getInternalTexture();
  70048. var scene = this.getScene();
  70049. if (objBuffer && scene) {
  70050. scene.getEngine()._releaseFramebufferObjects(objBuffer);
  70051. }
  70052. };
  70053. RenderTargetTexture.prototype.dispose = function () {
  70054. if (this._postProcessManager) {
  70055. this._postProcessManager.dispose();
  70056. this._postProcessManager = null;
  70057. }
  70058. this.clearPostProcesses(true);
  70059. if (this._resizeObserver) {
  70060. this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver);
  70061. this._resizeObserver = null;
  70062. }
  70063. this.renderList = null;
  70064. // Remove from custom render targets
  70065. var scene = this.getScene();
  70066. if (!scene) {
  70067. return;
  70068. }
  70069. var index = scene.customRenderTargets.indexOf(this);
  70070. if (index >= 0) {
  70071. scene.customRenderTargets.splice(index, 1);
  70072. }
  70073. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  70074. var camera = _a[_i];
  70075. index = camera.customRenderTargets.indexOf(this);
  70076. if (index >= 0) {
  70077. camera.customRenderTargets.splice(index, 1);
  70078. }
  70079. }
  70080. _super.prototype.dispose.call(this);
  70081. };
  70082. /** @hidden */
  70083. RenderTargetTexture.prototype._rebuild = function () {
  70084. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  70085. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  70086. }
  70087. if (this._postProcessManager) {
  70088. this._postProcessManager._rebuild();
  70089. }
  70090. };
  70091. /**
  70092. * Clear the info related to rendering groups preventing retention point in material dispose.
  70093. */
  70094. RenderTargetTexture.prototype.freeRenderingGroups = function () {
  70095. if (this._renderingManager) {
  70096. this._renderingManager.freeRenderingGroups();
  70097. }
  70098. };
  70099. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  70100. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  70101. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  70102. return RenderTargetTexture;
  70103. }(BABYLON.Texture));
  70104. BABYLON.RenderTargetTexture = RenderTargetTexture;
  70105. })(BABYLON || (BABYLON = {}));
  70106. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  70107. var BABYLON;
  70108. (function (BABYLON) {
  70109. ;
  70110. var MultiRenderTarget = /** @class */ (function (_super) {
  70111. __extends(MultiRenderTarget, _super);
  70112. function MultiRenderTarget(name, size, count, scene, options) {
  70113. var _this = this;
  70114. var generateMipMaps = options && options.generateMipMaps ? options.generateMipMaps : false;
  70115. var generateDepthTexture = options && options.generateDepthTexture ? options.generateDepthTexture : false;
  70116. var doNotChangeAspectRatio = !options || options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  70117. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  70118. _this._engine = scene.getEngine();
  70119. if (!_this.isSupported) {
  70120. _this.dispose();
  70121. return;
  70122. }
  70123. var types = [];
  70124. var samplingModes = [];
  70125. for (var i = 0; i < count; i++) {
  70126. if (options && options.types && options.types[i] !== undefined) {
  70127. types.push(options.types[i]);
  70128. }
  70129. else {
  70130. types.push(options && options.defaultType ? options.defaultType : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  70131. }
  70132. if (options && options.samplingModes && options.samplingModes[i] !== undefined) {
  70133. samplingModes.push(options.samplingModes[i]);
  70134. }
  70135. else {
  70136. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  70137. }
  70138. }
  70139. var generateDepthBuffer = !options || options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  70140. var generateStencilBuffer = !options || options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  70141. _this._size = size;
  70142. _this._multiRenderTargetOptions = {
  70143. samplingModes: samplingModes,
  70144. generateMipMaps: generateMipMaps,
  70145. generateDepthBuffer: generateDepthBuffer,
  70146. generateStencilBuffer: generateStencilBuffer,
  70147. generateDepthTexture: generateDepthTexture,
  70148. types: types,
  70149. textureCount: count
  70150. };
  70151. _this._createInternalTextures();
  70152. _this._createTextures();
  70153. return _this;
  70154. }
  70155. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  70156. get: function () {
  70157. return this._engine.webGLVersion > 1 || this._engine.getCaps().drawBuffersExtension;
  70158. },
  70159. enumerable: true,
  70160. configurable: true
  70161. });
  70162. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  70163. get: function () {
  70164. return this._textures;
  70165. },
  70166. enumerable: true,
  70167. configurable: true
  70168. });
  70169. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  70170. get: function () {
  70171. return this._textures[this._textures.length - 1];
  70172. },
  70173. enumerable: true,
  70174. configurable: true
  70175. });
  70176. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  70177. set: function (wrap) {
  70178. if (this._textures) {
  70179. for (var i = 0; i < this._textures.length; i++) {
  70180. this._textures[i].wrapU = wrap;
  70181. }
  70182. }
  70183. },
  70184. enumerable: true,
  70185. configurable: true
  70186. });
  70187. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  70188. set: function (wrap) {
  70189. if (this._textures) {
  70190. for (var i = 0; i < this._textures.length; i++) {
  70191. this._textures[i].wrapV = wrap;
  70192. }
  70193. }
  70194. },
  70195. enumerable: true,
  70196. configurable: true
  70197. });
  70198. /** @hidden */
  70199. MultiRenderTarget.prototype._rebuild = function () {
  70200. this.releaseInternalTextures();
  70201. this._createInternalTextures();
  70202. for (var i = 0; i < this._internalTextures.length; i++) {
  70203. var texture = this._textures[i];
  70204. texture._texture = this._internalTextures[i];
  70205. }
  70206. // Keeps references to frame buffer and stencil/depth buffer
  70207. this._texture = this._internalTextures[0];
  70208. };
  70209. MultiRenderTarget.prototype._createInternalTextures = function () {
  70210. this._internalTextures = this._engine.createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  70211. };
  70212. MultiRenderTarget.prototype._createTextures = function () {
  70213. this._textures = [];
  70214. for (var i = 0; i < this._internalTextures.length; i++) {
  70215. var texture = new BABYLON.Texture(null, this.getScene());
  70216. texture._texture = this._internalTextures[i];
  70217. this._textures.push(texture);
  70218. }
  70219. // Keeps references to frame buffer and stencil/depth buffer
  70220. this._texture = this._internalTextures[0];
  70221. };
  70222. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  70223. get: function () {
  70224. return this._samples;
  70225. },
  70226. set: function (value) {
  70227. if (this._samples === value) {
  70228. return;
  70229. }
  70230. this._samples = this._engine.updateMultipleRenderTargetTextureSampleCount(this._internalTextures, value);
  70231. },
  70232. enumerable: true,
  70233. configurable: true
  70234. });
  70235. MultiRenderTarget.prototype.resize = function (size) {
  70236. this.releaseInternalTextures();
  70237. this._internalTextures = this._engine.createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  70238. this._createInternalTextures();
  70239. };
  70240. MultiRenderTarget.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  70241. var _this = this;
  70242. engine.unBindMultiColorAttachmentFramebuffer(this._internalTextures, this.isCube, function () {
  70243. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  70244. });
  70245. };
  70246. MultiRenderTarget.prototype.dispose = function () {
  70247. this.releaseInternalTextures();
  70248. _super.prototype.dispose.call(this);
  70249. };
  70250. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  70251. if (!this._internalTextures) {
  70252. return;
  70253. }
  70254. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  70255. if (this._internalTextures[i] !== undefined) {
  70256. this._internalTextures[i].dispose();
  70257. this._internalTextures.splice(i, 1);
  70258. }
  70259. }
  70260. };
  70261. return MultiRenderTarget;
  70262. }(BABYLON.RenderTargetTexture));
  70263. BABYLON.MultiRenderTarget = MultiRenderTarget;
  70264. })(BABYLON || (BABYLON = {}));
  70265. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  70266. var BABYLON;
  70267. (function (BABYLON) {
  70268. var MirrorTexture = /** @class */ (function (_super) {
  70269. __extends(MirrorTexture, _super);
  70270. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  70271. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  70272. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  70273. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  70274. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  70275. _this.scene = scene;
  70276. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  70277. _this._transformMatrix = BABYLON.Matrix.Zero();
  70278. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  70279. _this._adaptiveBlurKernel = 0;
  70280. _this._blurKernelX = 0;
  70281. _this._blurKernelY = 0;
  70282. _this._blurRatio = 1.0;
  70283. _this.ignoreCameraViewport = true;
  70284. _this._updateGammaSpace();
  70285. _this._imageProcessingConfigChangeObserver = scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  70286. _this._updateGammaSpace;
  70287. });
  70288. _this.onBeforeRenderObservable.add(function () {
  70289. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  70290. _this._savedViewMatrix = scene.getViewMatrix();
  70291. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  70292. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  70293. scene.clipPlane = _this.mirrorPlane;
  70294. scene.getEngine().cullBackFaces = false;
  70295. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  70296. });
  70297. _this.onAfterRenderObservable.add(function () {
  70298. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  70299. scene.getEngine().cullBackFaces = true;
  70300. scene._mirroredCameraPosition = null;
  70301. delete scene.clipPlane;
  70302. });
  70303. return _this;
  70304. }
  70305. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  70306. get: function () {
  70307. return this._blurRatio;
  70308. },
  70309. set: function (value) {
  70310. if (this._blurRatio === value) {
  70311. return;
  70312. }
  70313. this._blurRatio = value;
  70314. this._preparePostProcesses();
  70315. },
  70316. enumerable: true,
  70317. configurable: true
  70318. });
  70319. Object.defineProperty(MirrorTexture.prototype, "adaptiveBlurKernel", {
  70320. set: function (value) {
  70321. this._adaptiveBlurKernel = value;
  70322. this._autoComputeBlurKernel();
  70323. },
  70324. enumerable: true,
  70325. configurable: true
  70326. });
  70327. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  70328. set: function (value) {
  70329. this.blurKernelX = value;
  70330. this.blurKernelY = value;
  70331. },
  70332. enumerable: true,
  70333. configurable: true
  70334. });
  70335. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  70336. get: function () {
  70337. return this._blurKernelX;
  70338. },
  70339. set: function (value) {
  70340. if (this._blurKernelX === value) {
  70341. return;
  70342. }
  70343. this._blurKernelX = value;
  70344. this._preparePostProcesses();
  70345. },
  70346. enumerable: true,
  70347. configurable: true
  70348. });
  70349. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  70350. get: function () {
  70351. return this._blurKernelY;
  70352. },
  70353. set: function (value) {
  70354. if (this._blurKernelY === value) {
  70355. return;
  70356. }
  70357. this._blurKernelY = value;
  70358. this._preparePostProcesses();
  70359. },
  70360. enumerable: true,
  70361. configurable: true
  70362. });
  70363. MirrorTexture.prototype._autoComputeBlurKernel = function () {
  70364. var engine = this.getScene().getEngine();
  70365. var dw = this.getRenderWidth() / engine.getRenderWidth();
  70366. var dh = this.getRenderHeight() / engine.getRenderHeight();
  70367. this.blurKernelX = this._adaptiveBlurKernel * dw;
  70368. this.blurKernelY = this._adaptiveBlurKernel * dh;
  70369. };
  70370. MirrorTexture.prototype._onRatioRescale = function () {
  70371. if (this._sizeRatio) {
  70372. this.resize(this._initialSizeParameter);
  70373. if (!this._adaptiveBlurKernel) {
  70374. this._preparePostProcesses();
  70375. }
  70376. }
  70377. if (this._adaptiveBlurKernel) {
  70378. this._autoComputeBlurKernel();
  70379. }
  70380. };
  70381. MirrorTexture.prototype._updateGammaSpace = function () {
  70382. this.gammaSpace = !this.scene.imageProcessingConfiguration.isEnabled || !this.scene.imageProcessingConfiguration.applyByPostProcess;
  70383. };
  70384. MirrorTexture.prototype._preparePostProcesses = function () {
  70385. this.clearPostProcesses(true);
  70386. if (this._blurKernelX && this._blurKernelY) {
  70387. var engine = this.getScene().getEngine();
  70388. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  70389. 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);
  70390. this._blurX.autoClear = false;
  70391. if (this._blurRatio === 1 && this.samples < 2 && this._texture) {
  70392. this._blurX.inputTexture = this._texture;
  70393. }
  70394. else {
  70395. this._blurX.alwaysForcePOT = true;
  70396. }
  70397. 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);
  70398. this._blurY.autoClear = false;
  70399. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  70400. this.addPostProcess(this._blurX);
  70401. this.addPostProcess(this._blurY);
  70402. }
  70403. else {
  70404. if (this._blurY) {
  70405. this.removePostProcess(this._blurY);
  70406. this._blurY.dispose();
  70407. this._blurY = null;
  70408. }
  70409. if (this._blurX) {
  70410. this.removePostProcess(this._blurX);
  70411. this._blurX.dispose();
  70412. this._blurX = null;
  70413. }
  70414. }
  70415. };
  70416. MirrorTexture.prototype.clone = function () {
  70417. var scene = this.getScene();
  70418. if (!scene) {
  70419. return this;
  70420. }
  70421. var textureSize = this.getSize();
  70422. var newTexture = new MirrorTexture(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  70423. // Base texture
  70424. newTexture.hasAlpha = this.hasAlpha;
  70425. newTexture.level = this.level;
  70426. // Mirror Texture
  70427. newTexture.mirrorPlane = this.mirrorPlane.clone();
  70428. if (this.renderList) {
  70429. newTexture.renderList = this.renderList.slice(0);
  70430. }
  70431. return newTexture;
  70432. };
  70433. MirrorTexture.prototype.serialize = function () {
  70434. if (!this.name) {
  70435. return null;
  70436. }
  70437. var serializationObject = _super.prototype.serialize.call(this);
  70438. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  70439. return serializationObject;
  70440. };
  70441. MirrorTexture.prototype.dispose = function () {
  70442. _super.prototype.dispose.call(this);
  70443. this.scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigChangeObserver);
  70444. };
  70445. return MirrorTexture;
  70446. }(BABYLON.RenderTargetTexture));
  70447. BABYLON.MirrorTexture = MirrorTexture;
  70448. })(BABYLON || (BABYLON = {}));
  70449. //# sourceMappingURL=babylon.mirrorTexture.js.map
  70450. var BABYLON;
  70451. (function (BABYLON) {
  70452. /**
  70453. * Creates a refraction texture used by refraction channel of the standard material.
  70454. * @param name the texture name
  70455. * @param size size of the underlying texture
  70456. * @param scene root scene
  70457. */
  70458. var RefractionTexture = /** @class */ (function (_super) {
  70459. __extends(RefractionTexture, _super);
  70460. function RefractionTexture(name, size, scene, generateMipMaps) {
  70461. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  70462. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  70463. _this.depth = 2.0;
  70464. _this.onBeforeRenderObservable.add(function () {
  70465. scene.clipPlane = _this.refractionPlane;
  70466. });
  70467. _this.onAfterRenderObservable.add(function () {
  70468. delete scene.clipPlane;
  70469. });
  70470. return _this;
  70471. }
  70472. RefractionTexture.prototype.clone = function () {
  70473. var scene = this.getScene();
  70474. if (!scene) {
  70475. return this;
  70476. }
  70477. var textureSize = this.getSize();
  70478. var newTexture = new RefractionTexture(this.name, textureSize.width, scene, this._generateMipMaps);
  70479. // Base texture
  70480. newTexture.hasAlpha = this.hasAlpha;
  70481. newTexture.level = this.level;
  70482. // Refraction Texture
  70483. newTexture.refractionPlane = this.refractionPlane.clone();
  70484. if (this.renderList) {
  70485. newTexture.renderList = this.renderList.slice(0);
  70486. }
  70487. newTexture.depth = this.depth;
  70488. return newTexture;
  70489. };
  70490. RefractionTexture.prototype.serialize = function () {
  70491. if (!this.name) {
  70492. return null;
  70493. }
  70494. var serializationObject = _super.prototype.serialize.call(this);
  70495. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  70496. serializationObject.depth = this.depth;
  70497. return serializationObject;
  70498. };
  70499. return RefractionTexture;
  70500. }(BABYLON.RenderTargetTexture));
  70501. BABYLON.RefractionTexture = RefractionTexture;
  70502. })(BABYLON || (BABYLON = {}));
  70503. //# sourceMappingURL=babylon.refractionTexture.js.map
  70504. var BABYLON;
  70505. (function (BABYLON) {
  70506. /**
  70507. * A class extending {BABYLON.Texture} allowing drawing on a texture
  70508. * @see http://doc.babylonjs.com/how_to/dynamictexture
  70509. */
  70510. var DynamicTexture = /** @class */ (function (_super) {
  70511. __extends(DynamicTexture, _super);
  70512. /**
  70513. * Creates a {BABYLON.DynamicTexture}
  70514. * @param name defines the name of the texture
  70515. * @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
  70516. * @param scene defines the scene where you want the texture
  70517. * @param generateMipMaps defines the use of MinMaps or not (default is false)
  70518. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  70519. * @param format defines the texture format to use (default is BABYLON.Engine.TEXTUREFORMAT_RGBA)
  70520. */
  70521. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  70522. if (scene === void 0) { scene = null; }
  70523. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  70524. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  70525. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  70526. _this.name = name;
  70527. _this._engine = _this.getScene().getEngine();
  70528. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  70529. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  70530. _this._generateMipMaps = generateMipMaps;
  70531. if (options.getContext) {
  70532. _this._canvas = options;
  70533. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  70534. }
  70535. else {
  70536. _this._canvas = document.createElement("canvas");
  70537. if (options.width || options.width === 0) {
  70538. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  70539. }
  70540. else {
  70541. _this._texture = _this._engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  70542. }
  70543. }
  70544. var textureSize = _this.getSize();
  70545. _this._canvas.width = textureSize.width;
  70546. _this._canvas.height = textureSize.height;
  70547. _this._context = _this._canvas.getContext("2d");
  70548. return _this;
  70549. }
  70550. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  70551. /**
  70552. * Gets the current state of canRescale
  70553. */
  70554. get: function () {
  70555. return true;
  70556. },
  70557. enumerable: true,
  70558. configurable: true
  70559. });
  70560. DynamicTexture.prototype._recreate = function (textureSize) {
  70561. this._canvas.width = textureSize.width;
  70562. this._canvas.height = textureSize.height;
  70563. this.releaseInternalTexture();
  70564. this._texture = this._engine.createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  70565. };
  70566. /**
  70567. * Scales the texture
  70568. * @param ratio the scale factor to apply to both width and height
  70569. */
  70570. DynamicTexture.prototype.scale = function (ratio) {
  70571. var textureSize = this.getSize();
  70572. textureSize.width *= ratio;
  70573. textureSize.height *= ratio;
  70574. this._recreate(textureSize);
  70575. };
  70576. /**
  70577. * Resizes the texture
  70578. * @param width the new width
  70579. * @param height the new height
  70580. */
  70581. DynamicTexture.prototype.scaleTo = function (width, height) {
  70582. var textureSize = this.getSize();
  70583. textureSize.width = width;
  70584. textureSize.height = height;
  70585. this._recreate(textureSize);
  70586. };
  70587. /**
  70588. * Gets the context of the canvas used by the texture
  70589. * @returns the canvas context of the dynamic texture
  70590. */
  70591. DynamicTexture.prototype.getContext = function () {
  70592. return this._context;
  70593. };
  70594. /**
  70595. * Clears the texture
  70596. */
  70597. DynamicTexture.prototype.clear = function () {
  70598. var size = this.getSize();
  70599. this._context.fillRect(0, 0, size.width, size.height);
  70600. };
  70601. /**
  70602. * Updates the texture
  70603. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  70604. * @param premulAlpha defines if alpha is stored as premultiplied (default is false)
  70605. */
  70606. DynamicTexture.prototype.update = function (invertY, premulAlpha) {
  70607. if (premulAlpha === void 0) { premulAlpha = false; }
  70608. this._engine.updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, premulAlpha, this._format || undefined);
  70609. };
  70610. /**
  70611. * Draws text onto the texture
  70612. * @param text defines the text to be drawn
  70613. * @param x defines the placement of the text from the left
  70614. * @param y defines the placement of the text from the top when invertY is true and from the bottom when false
  70615. * @param font defines the font to be used with font-style, font-size, font-name
  70616. * @param color defines the color used for the text
  70617. * @param clearColor defines the color for the canvas, use null to not overwrite canvas
  70618. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  70619. * @param update defines whether texture is immediately update (default is true)
  70620. */
  70621. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  70622. if (update === void 0) { update = true; }
  70623. var size = this.getSize();
  70624. if (clearColor) {
  70625. this._context.fillStyle = clearColor;
  70626. this._context.fillRect(0, 0, size.width, size.height);
  70627. }
  70628. this._context.font = font;
  70629. if (x === null || x === undefined) {
  70630. var textSize = this._context.measureText(text);
  70631. x = (size.width - textSize.width) / 2;
  70632. }
  70633. if (y === null || y === undefined) {
  70634. var fontSize = parseInt((font.replace(/\D/g, '')));
  70635. y = (size.height / 2) + (fontSize / 3.65);
  70636. }
  70637. this._context.fillStyle = color;
  70638. this._context.fillText(text, x, y);
  70639. if (update) {
  70640. this.update(invertY);
  70641. }
  70642. };
  70643. /**
  70644. * Clones the texture
  70645. * @returns the clone of the texture.
  70646. */
  70647. DynamicTexture.prototype.clone = function () {
  70648. var scene = this.getScene();
  70649. if (!scene) {
  70650. return this;
  70651. }
  70652. var textureSize = this.getSize();
  70653. var newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps);
  70654. // Base texture
  70655. newTexture.hasAlpha = this.hasAlpha;
  70656. newTexture.level = this.level;
  70657. // Dynamic Texture
  70658. newTexture.wrapU = this.wrapU;
  70659. newTexture.wrapV = this.wrapV;
  70660. return newTexture;
  70661. };
  70662. /**
  70663. * Serializes the dynamic texture. The scene should be ready before the dynamic texture is serialized
  70664. * @returns a serialized dynamic texture object
  70665. */
  70666. DynamicTexture.prototype.serialize = function () {
  70667. var scene = this.getScene();
  70668. if (scene && !scene.isReady()) {
  70669. BABYLON.Tools.Warn("The scene must be ready before serializing the dynamic texture");
  70670. }
  70671. var serializationObject = _super.prototype.serialize.call(this);
  70672. serializationObject.base64String = this._canvas.toDataURL();
  70673. serializationObject.invertY = this._invertY;
  70674. serializationObject.samplingMode = this.samplingMode;
  70675. return serializationObject;
  70676. };
  70677. /** @hidden */
  70678. DynamicTexture.prototype._rebuild = function () {
  70679. this.update();
  70680. };
  70681. return DynamicTexture;
  70682. }(BABYLON.Texture));
  70683. BABYLON.DynamicTexture = DynamicTexture;
  70684. })(BABYLON || (BABYLON = {}));
  70685. //# sourceMappingURL=babylon.dynamicTexture.js.map
  70686. var BABYLON;
  70687. (function (BABYLON) {
  70688. var VideoTexture = /** @class */ (function (_super) {
  70689. __extends(VideoTexture, _super);
  70690. /**
  70691. * Creates a video texture.
  70692. * Sample : https://doc.babylonjs.com/how_to/video_texture
  70693. * @param {string | null} name optional name, will detect from video source, if not defined
  70694. * @param {(string | string[] | HTMLVideoElement)} src can be used to provide an url, array of urls or an already setup HTML video element.
  70695. * @param {BABYLON.Scene} scene is obviously the current scene.
  70696. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  70697. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  70698. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  70699. * @param {VideoTextureSettings} [settings] allows finer control over video usage
  70700. */
  70701. function VideoTexture(name, src, scene, generateMipMaps, invertY, samplingMode, settings) {
  70702. if (generateMipMaps === void 0) { generateMipMaps = false; }
  70703. if (invertY === void 0) { invertY = false; }
  70704. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  70705. if (settings === void 0) { settings = {
  70706. autoPlay: true,
  70707. loop: true,
  70708. autoUpdateTexture: true,
  70709. }; }
  70710. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  70711. _this._onUserActionRequestedObservable = null;
  70712. _this._stillImageCaptured = false;
  70713. _this._poster = false;
  70714. _this._createInternalTexture = function () {
  70715. if (_this._texture != null) {
  70716. if (_this._poster) {
  70717. _this._texture.dispose();
  70718. _this._poster = false;
  70719. }
  70720. else {
  70721. return;
  70722. }
  70723. }
  70724. if (!_this._engine.needPOTTextures ||
  70725. (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  70726. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  70727. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  70728. }
  70729. else {
  70730. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  70731. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  70732. _this._generateMipMaps = false;
  70733. }
  70734. _this._texture = _this._engine.createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, _this._generateMipMaps, _this._samplingMode);
  70735. if (!_this.video.autoplay) {
  70736. var oldHandler_1 = _this.video.onplaying;
  70737. var error_1 = false;
  70738. _this.video.onplaying = function () {
  70739. _this.video.onplaying = oldHandler_1;
  70740. _this._texture.isReady = true;
  70741. _this._updateInternalTexture();
  70742. if (!error_1) {
  70743. _this.video.pause();
  70744. }
  70745. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  70746. _this.onLoadObservable.notifyObservers(_this);
  70747. }
  70748. };
  70749. var playing = _this.video.play();
  70750. if (playing) {
  70751. playing.then(function () {
  70752. // Everything is good.
  70753. })
  70754. .catch(function () {
  70755. error_1 = true;
  70756. // On Chrome for instance, new policies might prevent playing without user interaction.
  70757. if (_this._onUserActionRequestedObservable && _this._onUserActionRequestedObservable.hasObservers()) {
  70758. _this._onUserActionRequestedObservable.notifyObservers(_this);
  70759. }
  70760. });
  70761. }
  70762. else {
  70763. _this.video.onplaying = oldHandler_1;
  70764. _this._texture.isReady = true;
  70765. _this._updateInternalTexture();
  70766. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  70767. _this.onLoadObservable.notifyObservers(_this);
  70768. }
  70769. }
  70770. }
  70771. else {
  70772. _this._texture.isReady = true;
  70773. _this._updateInternalTexture();
  70774. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  70775. _this.onLoadObservable.notifyObservers(_this);
  70776. }
  70777. }
  70778. };
  70779. _this.reset = function () {
  70780. if (_this._texture == null) {
  70781. return;
  70782. }
  70783. if (!_this._poster) {
  70784. _this._texture.dispose();
  70785. _this._texture = null;
  70786. }
  70787. };
  70788. _this._updateInternalTexture = function (e) {
  70789. if (_this._texture == null || !_this._texture.isReady) {
  70790. return;
  70791. }
  70792. if (_this.video.readyState < _this.video.HAVE_CURRENT_DATA) {
  70793. return;
  70794. }
  70795. _this._engine.updateVideoTexture(_this._texture, _this.video, _this._invertY);
  70796. };
  70797. _this._engine = _this.getScene().getEngine();
  70798. _this._generateMipMaps = generateMipMaps;
  70799. _this._samplingMode = samplingMode;
  70800. _this.autoUpdateTexture = settings.autoUpdateTexture;
  70801. _this.name = name || _this._getName(src);
  70802. _this.video = _this._getVideo(src);
  70803. if (settings.poster) {
  70804. _this.video.poster = settings.poster;
  70805. }
  70806. if (settings.autoPlay !== undefined) {
  70807. _this.video.autoplay = settings.autoPlay;
  70808. }
  70809. if (settings.loop !== undefined) {
  70810. _this.video.loop = settings.loop;
  70811. }
  70812. _this.video.setAttribute("playsinline", "");
  70813. _this.video.addEventListener("canplay", _this._createInternalTexture);
  70814. _this.video.addEventListener("paused", _this._updateInternalTexture);
  70815. _this.video.addEventListener("seeked", _this._updateInternalTexture);
  70816. _this.video.addEventListener("emptied", _this.reset);
  70817. if (_this.video.readyState >= _this.video.HAVE_CURRENT_DATA) {
  70818. _this._createInternalTexture();
  70819. }
  70820. if (settings.poster) {
  70821. _this._texture = _this._engine.createTexture(settings.poster, false, true, scene);
  70822. _this._poster = true;
  70823. }
  70824. return _this;
  70825. }
  70826. Object.defineProperty(VideoTexture.prototype, "onUserActionRequestedObservable", {
  70827. get: function () {
  70828. if (!this._onUserActionRequestedObservable) {
  70829. this._onUserActionRequestedObservable = new BABYLON.Observable();
  70830. }
  70831. return this._onUserActionRequestedObservable;
  70832. },
  70833. enumerable: true,
  70834. configurable: true
  70835. });
  70836. VideoTexture.prototype._getName = function (src) {
  70837. if (src instanceof HTMLVideoElement) {
  70838. return src.currentSrc;
  70839. }
  70840. if (typeof src === "object") {
  70841. return src.toString();
  70842. }
  70843. return src;
  70844. };
  70845. ;
  70846. VideoTexture.prototype._getVideo = function (src) {
  70847. if (src instanceof HTMLVideoElement) {
  70848. BABYLON.Tools.SetCorsBehavior(src.currentSrc, src);
  70849. return src;
  70850. }
  70851. var video = document.createElement("video");
  70852. if (typeof src === "string") {
  70853. BABYLON.Tools.SetCorsBehavior(src, video);
  70854. video.src = src;
  70855. }
  70856. else {
  70857. BABYLON.Tools.SetCorsBehavior(src[0], video);
  70858. src.forEach(function (url) {
  70859. var source = document.createElement("source");
  70860. source.src = url;
  70861. video.appendChild(source);
  70862. });
  70863. }
  70864. return video;
  70865. };
  70866. ;
  70867. /**
  70868. * @hidden Internal method to initiate `update`.
  70869. */
  70870. VideoTexture.prototype._rebuild = function () {
  70871. this.update();
  70872. };
  70873. /**
  70874. * Update Texture in the `auto` mode. Does not do anything if `settings.autoUpdateTexture` is false.
  70875. */
  70876. VideoTexture.prototype.update = function () {
  70877. if (!this.autoUpdateTexture) {
  70878. // Expecting user to call `updateTexture` manually
  70879. return;
  70880. }
  70881. this.updateTexture(true);
  70882. };
  70883. /**
  70884. * Update Texture in `manual` mode. Does not do anything if not visible or paused.
  70885. * @param isVisible Visibility state, detected by user using `scene.getActiveMeshes()` or othervise.
  70886. */
  70887. VideoTexture.prototype.updateTexture = function (isVisible) {
  70888. if (!isVisible) {
  70889. return;
  70890. }
  70891. if (this.video.paused && this._stillImageCaptured) {
  70892. return;
  70893. }
  70894. this._stillImageCaptured = true;
  70895. this._updateInternalTexture();
  70896. };
  70897. /**
  70898. * Change video content. Changing video instance or setting multiple urls (as in constructor) is not supported.
  70899. * @param url New url.
  70900. */
  70901. VideoTexture.prototype.updateURL = function (url) {
  70902. this.video.src = url;
  70903. };
  70904. VideoTexture.prototype.dispose = function () {
  70905. _super.prototype.dispose.call(this);
  70906. if (this._onUserActionRequestedObservable) {
  70907. this._onUserActionRequestedObservable.clear();
  70908. this._onUserActionRequestedObservable = null;
  70909. }
  70910. this.video.removeEventListener("canplay", this._createInternalTexture);
  70911. this.video.removeEventListener("paused", this._updateInternalTexture);
  70912. this.video.removeEventListener("seeked", this._updateInternalTexture);
  70913. this.video.removeEventListener("emptied", this.reset);
  70914. this.video.pause();
  70915. };
  70916. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  70917. var video = document.createElement("video");
  70918. video.setAttribute('autoplay', '');
  70919. video.setAttribute('muted', '');
  70920. video.setAttribute('playsinline', '');
  70921. var constraintsDeviceId;
  70922. if (constraints && constraints.deviceId) {
  70923. constraintsDeviceId = {
  70924. exact: constraints.deviceId,
  70925. };
  70926. }
  70927. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  70928. if (navigator.mediaDevices) {
  70929. navigator.mediaDevices.getUserMedia({ video: constraints })
  70930. .then(function (stream) {
  70931. if (video.mozSrcObject !== undefined) {
  70932. // hack for Firefox < 19
  70933. video.mozSrcObject = stream;
  70934. }
  70935. else {
  70936. video.srcObject = stream;
  70937. }
  70938. var onPlaying = function () {
  70939. if (onReady) {
  70940. onReady(new VideoTexture("video", video, scene, true, true));
  70941. }
  70942. video.removeEventListener("playing", onPlaying);
  70943. };
  70944. video.addEventListener("playing", onPlaying);
  70945. video.play();
  70946. })
  70947. .catch(function (err) {
  70948. BABYLON.Tools.Error(err.name);
  70949. });
  70950. }
  70951. else {
  70952. navigator.getUserMedia =
  70953. navigator.getUserMedia ||
  70954. navigator.webkitGetUserMedia ||
  70955. navigator.mozGetUserMedia ||
  70956. navigator.msGetUserMedia;
  70957. if (navigator.getUserMedia) {
  70958. navigator.getUserMedia({
  70959. video: {
  70960. deviceId: constraintsDeviceId,
  70961. width: {
  70962. min: (constraints && constraints.minWidth) || 256,
  70963. max: (constraints && constraints.maxWidth) || 640,
  70964. },
  70965. height: {
  70966. min: (constraints && constraints.minHeight) || 256,
  70967. max: (constraints && constraints.maxHeight) || 480,
  70968. },
  70969. },
  70970. }, function (stream) {
  70971. if (video.mozSrcObject !== undefined) {
  70972. // hack for Firefox < 19
  70973. video.mozSrcObject = stream;
  70974. }
  70975. else {
  70976. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  70977. }
  70978. video.play();
  70979. if (onReady) {
  70980. onReady(new VideoTexture("video", video, scene, true, true));
  70981. }
  70982. }, function (e) {
  70983. BABYLON.Tools.Error(e.name);
  70984. });
  70985. }
  70986. }
  70987. };
  70988. return VideoTexture;
  70989. }(BABYLON.Texture));
  70990. BABYLON.VideoTexture = VideoTexture;
  70991. })(BABYLON || (BABYLON = {}));
  70992. //# sourceMappingURL=babylon.videoTexture.js.map
  70993. var BABYLON;
  70994. (function (BABYLON) {
  70995. var RawTexture = /** @class */ (function (_super) {
  70996. __extends(RawTexture, _super);
  70997. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode, type) {
  70998. if (generateMipMaps === void 0) { generateMipMaps = true; }
  70999. if (invertY === void 0) { invertY = false; }
  71000. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  71001. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  71002. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  71003. _this.format = format;
  71004. _this._engine = scene.getEngine();
  71005. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode, null, type);
  71006. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  71007. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  71008. return _this;
  71009. }
  71010. RawTexture.prototype.update = function (data) {
  71011. this._engine.updateRawTexture(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  71012. };
  71013. // Statics
  71014. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  71015. if (generateMipMaps === void 0) { generateMipMaps = true; }
  71016. if (invertY === void 0) { invertY = false; }
  71017. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  71018. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  71019. };
  71020. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  71021. if (generateMipMaps === void 0) { generateMipMaps = true; }
  71022. if (invertY === void 0) { invertY = false; }
  71023. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  71024. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  71025. };
  71026. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  71027. if (generateMipMaps === void 0) { generateMipMaps = true; }
  71028. if (invertY === void 0) { invertY = false; }
  71029. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  71030. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  71031. };
  71032. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  71033. if (generateMipMaps === void 0) { generateMipMaps = true; }
  71034. if (invertY === void 0) { invertY = false; }
  71035. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  71036. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  71037. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode, type);
  71038. };
  71039. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  71040. if (generateMipMaps === void 0) { generateMipMaps = true; }
  71041. if (invertY === void 0) { invertY = false; }
  71042. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  71043. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  71044. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode, type);
  71045. };
  71046. RawTexture.CreateRTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  71047. if (generateMipMaps === void 0) { generateMipMaps = true; }
  71048. if (invertY === void 0) { invertY = false; }
  71049. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  71050. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  71051. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_R, scene, generateMipMaps, invertY, samplingMode, type);
  71052. };
  71053. return RawTexture;
  71054. }(BABYLON.Texture));
  71055. BABYLON.RawTexture = RawTexture;
  71056. })(BABYLON || (BABYLON = {}));
  71057. //# sourceMappingURL=babylon.rawTexture.js.map
  71058. var BABYLON;
  71059. (function (BABYLON) {
  71060. /**
  71061. * Class used to store 3D textures containing user data
  71062. */
  71063. var RawTexture3D = /** @class */ (function (_super) {
  71064. __extends(RawTexture3D, _super);
  71065. /**
  71066. * Create a new RawTexture3D
  71067. * @param data defines the data of the texture
  71068. * @param width defines the width of the texture
  71069. * @param height defines the height of the texture
  71070. * @param depth defines the depth of the texture
  71071. * @param format defines the texture format to use
  71072. * @param scene defines the hosting scene
  71073. * @param generateMipMaps defines a boolean indicating if mip levels should be generated (true by default)
  71074. * @param invertY defines if texture must be stored with Y axis inverted
  71075. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  71076. * @param textureType defines the texture Type (Engine.TEXTURETYPE_UNSIGNED_INT, Engine.TEXTURETYPE_FLOAT...)
  71077. */
  71078. function RawTexture3D(data, width, height, depth,
  71079. /** Gets or sets the texture format to use */
  71080. format, scene, generateMipMaps, invertY, samplingMode, textureType) {
  71081. if (generateMipMaps === void 0) { generateMipMaps = true; }
  71082. if (invertY === void 0) { invertY = false; }
  71083. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  71084. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  71085. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  71086. _this.format = format;
  71087. _this._engine = scene.getEngine();
  71088. _this._texture = scene.getEngine().createRawTexture3D(data, width, height, depth, format, generateMipMaps, invertY, samplingMode, undefined, textureType);
  71089. _this.is3D = true;
  71090. return _this;
  71091. }
  71092. /**
  71093. * Update the texture with new data
  71094. * @param data defines the data to store in the texture
  71095. */
  71096. RawTexture3D.prototype.update = function (data) {
  71097. if (!this._texture) {
  71098. return;
  71099. }
  71100. this._engine.updateRawTexture3D(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  71101. };
  71102. return RawTexture3D;
  71103. }(BABYLON.Texture));
  71104. BABYLON.RawTexture3D = RawTexture3D;
  71105. })(BABYLON || (BABYLON = {}));
  71106. //# sourceMappingURL=babylon.rawTexture3D.js.map
  71107. var BABYLON;
  71108. (function (BABYLON) {
  71109. /**
  71110. * PostProcessManager is used to manage one or more post processes or post process pipelines
  71111. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  71112. */
  71113. var PostProcessManager = /** @class */ (function () {
  71114. /**
  71115. * Creates a new instance PostProcess
  71116. * @param scene The scene that the post process is associated with.
  71117. */
  71118. function PostProcessManager(scene) {
  71119. this._vertexBuffers = {};
  71120. this._scene = scene;
  71121. }
  71122. PostProcessManager.prototype._prepareBuffers = function () {
  71123. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  71124. return;
  71125. }
  71126. // VBO
  71127. var vertices = [];
  71128. vertices.push(1, 1);
  71129. vertices.push(-1, 1);
  71130. vertices.push(-1, -1);
  71131. vertices.push(1, -1);
  71132. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  71133. this._buildIndexBuffer();
  71134. };
  71135. PostProcessManager.prototype._buildIndexBuffer = function () {
  71136. // Indices
  71137. var indices = [];
  71138. indices.push(0);
  71139. indices.push(1);
  71140. indices.push(2);
  71141. indices.push(0);
  71142. indices.push(2);
  71143. indices.push(3);
  71144. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  71145. };
  71146. /**
  71147. * Rebuilds the vertex buffers of the manager.
  71148. * @hidden
  71149. */
  71150. PostProcessManager.prototype._rebuild = function () {
  71151. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  71152. if (!vb) {
  71153. return;
  71154. }
  71155. vb._rebuild();
  71156. this._buildIndexBuffer();
  71157. };
  71158. // Methods
  71159. /**
  71160. * Prepares a frame to be run through a post process.
  71161. * @param sourceTexture The input texture to the post procesess. (default: null)
  71162. * @param postProcesses An array of post processes to be run. (default: null)
  71163. * @returns True if the post processes were able to be run.
  71164. * @hidden
  71165. */
  71166. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  71167. if (sourceTexture === void 0) { sourceTexture = null; }
  71168. if (postProcesses === void 0) { postProcesses = null; }
  71169. var camera = this._scene.activeCamera;
  71170. if (!camera) {
  71171. return false;
  71172. }
  71173. var postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  71174. if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  71175. return false;
  71176. }
  71177. postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  71178. return true;
  71179. };
  71180. /**
  71181. * Manually render a set of post processes to a texture.
  71182. * @param postProcesses An array of post processes to be run.
  71183. * @param targetTexture The target texture to render to.
  71184. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight
  71185. * @param faceIndex defines the face to render to if a cubemap is defined as the target
  71186. * @param lodLevel defines which lod of the texture to render to
  71187. */
  71188. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport, faceIndex, lodLevel) {
  71189. if (targetTexture === void 0) { targetTexture = null; }
  71190. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  71191. if (faceIndex === void 0) { faceIndex = 0; }
  71192. if (lodLevel === void 0) { lodLevel = 0; }
  71193. var engine = this._scene.getEngine();
  71194. for (var index = 0; index < postProcesses.length; index++) {
  71195. if (index < postProcesses.length - 1) {
  71196. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  71197. }
  71198. else {
  71199. if (targetTexture) {
  71200. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport, undefined, lodLevel);
  71201. }
  71202. else {
  71203. engine.restoreDefaultFramebuffer();
  71204. }
  71205. }
  71206. var pp = postProcesses[index];
  71207. var effect = pp.apply();
  71208. if (effect) {
  71209. pp.onBeforeRenderObservable.notifyObservers(effect);
  71210. // VBOs
  71211. this._prepareBuffers();
  71212. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  71213. // Draw order
  71214. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  71215. pp.onAfterRenderObservable.notifyObservers(effect);
  71216. }
  71217. }
  71218. // Restore depth buffer
  71219. engine.setDepthBuffer(true);
  71220. engine.setDepthWrite(true);
  71221. };
  71222. /**
  71223. * Finalize the result of the output of the postprocesses.
  71224. * @param doNotPresent If true the result will not be displayed to the screen.
  71225. * @param targetTexture The target texture to render to.
  71226. * @param faceIndex The index of the face to bind the target texture to.
  71227. * @param postProcesses The array of post processes to render.
  71228. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight (default: false)
  71229. * @hidden
  71230. */
  71231. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  71232. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  71233. var camera = this._scene.activeCamera;
  71234. if (!camera) {
  71235. return;
  71236. }
  71237. postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  71238. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  71239. return;
  71240. }
  71241. var engine = this._scene.getEngine();
  71242. for (var index = 0, len = postProcesses.length; index < len; index++) {
  71243. var pp = postProcesses[index];
  71244. if (index < len - 1) {
  71245. pp._outputTexture = postProcesses[index + 1].activate(camera, targetTexture);
  71246. }
  71247. else {
  71248. if (targetTexture) {
  71249. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);
  71250. pp._outputTexture = targetTexture;
  71251. }
  71252. else {
  71253. engine.restoreDefaultFramebuffer();
  71254. pp._outputTexture = null;
  71255. }
  71256. }
  71257. if (doNotPresent) {
  71258. break;
  71259. }
  71260. var effect = pp.apply();
  71261. if (effect) {
  71262. pp.onBeforeRenderObservable.notifyObservers(effect);
  71263. // VBOs
  71264. this._prepareBuffers();
  71265. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  71266. // Draw order
  71267. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  71268. pp.onAfterRenderObservable.notifyObservers(effect);
  71269. }
  71270. }
  71271. // Restore states
  71272. engine.setDepthBuffer(true);
  71273. engine.setDepthWrite(true);
  71274. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  71275. };
  71276. /**
  71277. * Disposes of the post process manager.
  71278. */
  71279. PostProcessManager.prototype.dispose = function () {
  71280. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  71281. if (buffer) {
  71282. buffer.dispose();
  71283. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  71284. }
  71285. if (this._indexBuffer) {
  71286. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  71287. this._indexBuffer = null;
  71288. }
  71289. };
  71290. return PostProcessManager;
  71291. }());
  71292. BABYLON.PostProcessManager = PostProcessManager;
  71293. })(BABYLON || (BABYLON = {}));
  71294. //# sourceMappingURL=babylon.postProcessManager.js.map
  71295. var BABYLON;
  71296. (function (BABYLON) {
  71297. /**
  71298. * PostProcess can be used to apply a shader to a texture after it has been rendered
  71299. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  71300. */
  71301. var PostProcess = /** @class */ (function () {
  71302. /**
  71303. * Creates a new instance PostProcess
  71304. * @param name The name of the PostProcess.
  71305. * @param fragmentUrl The url of the fragment shader to be used.
  71306. * @param parameters Array of the names of uniform non-sampler2D variables that will be passed to the shader.
  71307. * @param samplers Array of the names of uniform sampler2D variables that will be passed to the shader.
  71308. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  71309. * @param camera The camera to apply the render pass to.
  71310. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  71311. * @param engine The engine which the post process will be applied. (default: current engine)
  71312. * @param reusable If the post process can be reused on the same frame. (default: false)
  71313. * @param defines String of defines that will be set when running the fragment shader. (default: null)
  71314. * @param textureType Type of textures used when performing the post process. (default: 0)
  71315. * @param vertexUrl The url of the vertex shader to be used. (default: "postprocess")
  71316. * @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
  71317. * @param blockCompilation If the shader should not be compiled imediatly. (default: false)
  71318. */
  71319. function PostProcess(
  71320. /** Name of the PostProcess. */
  71321. name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  71322. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  71323. if (defines === void 0) { defines = null; }
  71324. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  71325. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  71326. if (blockCompilation === void 0) { blockCompilation = false; }
  71327. this.name = name;
  71328. /**
  71329. * Width of the texture to apply the post process on
  71330. */
  71331. this.width = -1;
  71332. /**
  71333. * Height of the texture to apply the post process on
  71334. */
  71335. this.height = -1;
  71336. /**
  71337. * Internal, reference to the location where this postprocess was output to. (Typically the texture on the next postprocess in the chain)
  71338. * @hidden
  71339. */
  71340. this._outputTexture = null;
  71341. /**
  71342. * If the buffer needs to be cleared before applying the post process. (default: true)
  71343. * Should be set to false if shader will overwrite all previous pixels.
  71344. */
  71345. this.autoClear = true;
  71346. /**
  71347. * Type of alpha mode to use when performing the post process (default: Engine.ALPHA_DISABLE)
  71348. */
  71349. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  71350. /**
  71351. * Animations to be used for the post processing
  71352. */
  71353. this.animations = new Array();
  71354. /**
  71355. * Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  71356. * Can only be used on a single postprocess or on the last one of a chain. (default: false)
  71357. */
  71358. this.enablePixelPerfectMode = false;
  71359. /**
  71360. * Force the postprocess to be applied without taking in account viewport
  71361. */
  71362. this.forceFullscreenViewport = true;
  71363. /**
  71364. * Scale mode for the post process (default: Engine.SCALEMODE_FLOOR)
  71365. *
  71366. * | Value | Type | Description |
  71367. * | ----- | ----------------------------------- | ----------- |
  71368. * | 1 | SCALEMODE_FLOOR | [engine.scalemode_floor](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_floor) |
  71369. * | 2 | SCALEMODE_NEAREST | [engine.scalemode_nearest](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_nearest) |
  71370. * | 3 | SCALEMODE_CEILING | [engine.scalemode_ceiling](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_ceiling) |
  71371. *
  71372. */
  71373. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  71374. /**
  71375. * Force textures to be a power of two (default: false)
  71376. */
  71377. this.alwaysForcePOT = false;
  71378. this._samples = 1;
  71379. /**
  71380. * Modify the scale of the post process to be the same as the viewport (default: false)
  71381. */
  71382. this.adaptScaleToCurrentViewport = false;
  71383. this._reusable = false;
  71384. /**
  71385. * Smart array of input and output textures for the post process.
  71386. * @hidden
  71387. */
  71388. this._textures = new BABYLON.SmartArray(2);
  71389. /**
  71390. * The index in _textures that corresponds to the output texture.
  71391. * @hidden
  71392. */
  71393. this._currentRenderTextureInd = 0;
  71394. this._scaleRatio = new BABYLON.Vector2(1, 1);
  71395. this._texelSize = BABYLON.Vector2.Zero();
  71396. // Events
  71397. /**
  71398. * An event triggered when the postprocess is activated.
  71399. */
  71400. this.onActivateObservable = new BABYLON.Observable();
  71401. /**
  71402. * An event triggered when the postprocess changes its size.
  71403. */
  71404. this.onSizeChangedObservable = new BABYLON.Observable();
  71405. /**
  71406. * An event triggered when the postprocess applies its effect.
  71407. */
  71408. this.onApplyObservable = new BABYLON.Observable();
  71409. /**
  71410. * An event triggered before rendering the postprocess
  71411. */
  71412. this.onBeforeRenderObservable = new BABYLON.Observable();
  71413. /**
  71414. * An event triggered after rendering the postprocess
  71415. */
  71416. this.onAfterRenderObservable = new BABYLON.Observable();
  71417. if (camera != null) {
  71418. this._camera = camera;
  71419. this._scene = camera.getScene();
  71420. camera.attachPostProcess(this);
  71421. this._engine = this._scene.getEngine();
  71422. this._scene.postProcesses.push(this);
  71423. }
  71424. else if (engine) {
  71425. this._engine = engine;
  71426. this._engine.postProcesses.push(this);
  71427. }
  71428. this._options = options;
  71429. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  71430. this._reusable = reusable || false;
  71431. this._textureType = textureType;
  71432. this._samplers = samplers || [];
  71433. this._samplers.push("textureSampler");
  71434. this._fragmentUrl = fragmentUrl;
  71435. this._vertexUrl = vertexUrl;
  71436. this._parameters = parameters || [];
  71437. this._parameters.push("scale");
  71438. this._indexParameters = indexParameters;
  71439. if (!blockCompilation) {
  71440. this.updateEffect(defines);
  71441. }
  71442. }
  71443. Object.defineProperty(PostProcess.prototype, "samples", {
  71444. /**
  71445. * Number of sample textures (default: 1)
  71446. */
  71447. get: function () {
  71448. return this._samples;
  71449. },
  71450. set: function (n) {
  71451. var _this = this;
  71452. this._samples = n;
  71453. this._textures.forEach(function (texture) {
  71454. if (texture.samples !== _this._samples) {
  71455. _this._engine.updateRenderTargetTextureSampleCount(texture, _this._samples);
  71456. }
  71457. });
  71458. },
  71459. enumerable: true,
  71460. configurable: true
  71461. });
  71462. Object.defineProperty(PostProcess.prototype, "onActivate", {
  71463. /**
  71464. * A function that is added to the onActivateObservable
  71465. */
  71466. set: function (callback) {
  71467. if (this._onActivateObserver) {
  71468. this.onActivateObservable.remove(this._onActivateObserver);
  71469. }
  71470. if (callback) {
  71471. this._onActivateObserver = this.onActivateObservable.add(callback);
  71472. }
  71473. },
  71474. enumerable: true,
  71475. configurable: true
  71476. });
  71477. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  71478. /**
  71479. * A function that is added to the onSizeChangedObservable
  71480. */
  71481. set: function (callback) {
  71482. if (this._onSizeChangedObserver) {
  71483. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  71484. }
  71485. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  71486. },
  71487. enumerable: true,
  71488. configurable: true
  71489. });
  71490. Object.defineProperty(PostProcess.prototype, "onApply", {
  71491. /**
  71492. * A function that is added to the onApplyObservable
  71493. */
  71494. set: function (callback) {
  71495. if (this._onApplyObserver) {
  71496. this.onApplyObservable.remove(this._onApplyObserver);
  71497. }
  71498. this._onApplyObserver = this.onApplyObservable.add(callback);
  71499. },
  71500. enumerable: true,
  71501. configurable: true
  71502. });
  71503. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  71504. /**
  71505. * A function that is added to the onBeforeRenderObservable
  71506. */
  71507. set: function (callback) {
  71508. if (this._onBeforeRenderObserver) {
  71509. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  71510. }
  71511. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  71512. },
  71513. enumerable: true,
  71514. configurable: true
  71515. });
  71516. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  71517. /**
  71518. * A function that is added to the onAfterRenderObservable
  71519. */
  71520. set: function (callback) {
  71521. if (this._onAfterRenderObserver) {
  71522. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  71523. }
  71524. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  71525. },
  71526. enumerable: true,
  71527. configurable: true
  71528. });
  71529. Object.defineProperty(PostProcess.prototype, "inputTexture", {
  71530. /**
  71531. * 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
  71532. * render it's output into this texture and this texture will be used as textureSampler in the fragment shader of this post process.
  71533. */
  71534. get: function () {
  71535. return this._textures.data[this._currentRenderTextureInd];
  71536. },
  71537. set: function (value) {
  71538. this._forcedOutputTexture = value;
  71539. },
  71540. enumerable: true,
  71541. configurable: true
  71542. });
  71543. /**
  71544. * Gets the camera which post process is applied to.
  71545. * @returns The camera the post process is applied to.
  71546. */
  71547. PostProcess.prototype.getCamera = function () {
  71548. return this._camera;
  71549. };
  71550. Object.defineProperty(PostProcess.prototype, "texelSize", {
  71551. /**
  71552. * Gets the texel size of the postprocess.
  71553. * See https://en.wikipedia.org/wiki/Texel_(graphics)
  71554. */
  71555. get: function () {
  71556. if (this._shareOutputWithPostProcess) {
  71557. return this._shareOutputWithPostProcess.texelSize;
  71558. }
  71559. if (this._forcedOutputTexture) {
  71560. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  71561. }
  71562. return this._texelSize;
  71563. },
  71564. enumerable: true,
  71565. configurable: true
  71566. });
  71567. /**
  71568. * Gets the engine which this post process belongs to.
  71569. * @returns The engine the post process was enabled with.
  71570. */
  71571. PostProcess.prototype.getEngine = function () {
  71572. return this._engine;
  71573. };
  71574. /**
  71575. * The effect that is created when initializing the post process.
  71576. * @returns The created effect corrisponding the the postprocess.
  71577. */
  71578. PostProcess.prototype.getEffect = function () {
  71579. return this._effect;
  71580. };
  71581. /**
  71582. * To avoid multiple redundant textures for multiple post process, the output the output texture for this post process can be shared with another.
  71583. * @param postProcess The post process to share the output with.
  71584. * @returns This post process.
  71585. */
  71586. PostProcess.prototype.shareOutputWith = function (postProcess) {
  71587. this._disposeTextures();
  71588. this._shareOutputWithPostProcess = postProcess;
  71589. return this;
  71590. };
  71591. /**
  71592. * Reverses the effect of calling shareOutputWith and returns the post process back to its original state.
  71593. * This should be called if the post process that shares output with this post process is disabled/disposed.
  71594. */
  71595. PostProcess.prototype.useOwnOutput = function () {
  71596. if (this._textures.length == 0) {
  71597. this._textures = new BABYLON.SmartArray(2);
  71598. }
  71599. this._shareOutputWithPostProcess = null;
  71600. };
  71601. /**
  71602. * Updates the effect with the current post process compile time values and recompiles the shader.
  71603. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  71604. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  71605. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  71606. * @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
  71607. * @param onCompiled Called when the shader has been compiled.
  71608. * @param onError Called if there is an error when compiling a shader.
  71609. */
  71610. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  71611. if (defines === void 0) { defines = null; }
  71612. if (uniforms === void 0) { uniforms = null; }
  71613. if (samplers === void 0) { samplers = null; }
  71614. 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);
  71615. };
  71616. /**
  71617. * The post process is reusable if it can be used multiple times within one frame.
  71618. * @returns If the post process is reusable
  71619. */
  71620. PostProcess.prototype.isReusable = function () {
  71621. return this._reusable;
  71622. };
  71623. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  71624. PostProcess.prototype.markTextureDirty = function () {
  71625. this.width = -1;
  71626. };
  71627. /**
  71628. * Activates the post process by intializing the textures to be used when executed. Notifies onActivateObservable.
  71629. * 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.
  71630. * @param camera The camera that will be used in the post process. This camera will be used when calling onActivateObservable.
  71631. * @param sourceTexture The source texture to be inspected to get the width and height if not specified in the post process constructor. (default: null)
  71632. * @param forceDepthStencil If true, a depth and stencil buffer will be generated. (default: false)
  71633. * @returns The target texture that was bound to be written to.
  71634. */
  71635. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  71636. var _this = this;
  71637. if (sourceTexture === void 0) { sourceTexture = null; }
  71638. camera = camera || this._camera;
  71639. var scene = camera.getScene();
  71640. var engine = scene.getEngine();
  71641. var maxSize = engine.getCaps().maxTextureSize;
  71642. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0;
  71643. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0;
  71644. // 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
  71645. var webVRCamera = camera.parent;
  71646. if (webVRCamera && (webVRCamera.leftCamera == camera || webVRCamera.rightCamera == camera)) {
  71647. requiredWidth /= 2;
  71648. }
  71649. var desiredWidth = (this._options.width || requiredWidth);
  71650. var desiredHeight = this._options.height || requiredHeight;
  71651. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  71652. if (this.adaptScaleToCurrentViewport) {
  71653. var currentViewport = engine.currentViewport;
  71654. if (currentViewport) {
  71655. desiredWidth *= currentViewport.width;
  71656. desiredHeight *= currentViewport.height;
  71657. }
  71658. }
  71659. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  71660. if (!this._options.width) {
  71661. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  71662. }
  71663. if (!this._options.height) {
  71664. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  71665. }
  71666. }
  71667. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  71668. if (this._textures.length > 0) {
  71669. for (var i = 0; i < this._textures.length; i++) {
  71670. this._engine._releaseTexture(this._textures.data[i]);
  71671. }
  71672. this._textures.reset();
  71673. }
  71674. this.width = desiredWidth;
  71675. this.height = desiredHeight;
  71676. var textureSize = { width: this.width, height: this.height };
  71677. var textureOptions = {
  71678. generateMipMaps: false,
  71679. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  71680. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  71681. samplingMode: this.renderTargetSamplingMode,
  71682. type: this._textureType
  71683. };
  71684. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  71685. if (this._reusable) {
  71686. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  71687. }
  71688. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  71689. this.onSizeChangedObservable.notifyObservers(this);
  71690. }
  71691. this._textures.forEach(function (texture) {
  71692. if (texture.samples !== _this.samples) {
  71693. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  71694. }
  71695. });
  71696. }
  71697. var target;
  71698. if (this._shareOutputWithPostProcess) {
  71699. target = this._shareOutputWithPostProcess.inputTexture;
  71700. }
  71701. else if (this._forcedOutputTexture) {
  71702. target = this._forcedOutputTexture;
  71703. this.width = this._forcedOutputTexture.width;
  71704. this.height = this._forcedOutputTexture.height;
  71705. }
  71706. else {
  71707. target = this.inputTexture;
  71708. }
  71709. // Bind the input of this post process to be used as the output of the previous post process.
  71710. if (this.enablePixelPerfectMode) {
  71711. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  71712. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, this.forceFullscreenViewport);
  71713. }
  71714. else {
  71715. this._scaleRatio.copyFromFloats(1, 1);
  71716. this._engine.bindFramebuffer(target, 0, undefined, undefined, this.forceFullscreenViewport);
  71717. }
  71718. this.onActivateObservable.notifyObservers(camera);
  71719. // Clear
  71720. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  71721. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, scene._allowPostProcessClearColor, true, true);
  71722. }
  71723. if (this._reusable) {
  71724. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  71725. }
  71726. return target;
  71727. };
  71728. Object.defineProperty(PostProcess.prototype, "isSupported", {
  71729. /**
  71730. * If the post process is supported.
  71731. */
  71732. get: function () {
  71733. return this._effect.isSupported;
  71734. },
  71735. enumerable: true,
  71736. configurable: true
  71737. });
  71738. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  71739. /**
  71740. * The aspect ratio of the output texture.
  71741. */
  71742. get: function () {
  71743. if (this._shareOutputWithPostProcess) {
  71744. return this._shareOutputWithPostProcess.aspectRatio;
  71745. }
  71746. if (this._forcedOutputTexture) {
  71747. return this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  71748. }
  71749. return this.width / this.height;
  71750. },
  71751. enumerable: true,
  71752. configurable: true
  71753. });
  71754. /**
  71755. * Get a value indicating if the post-process is ready to be used
  71756. * @returns true if the post-process is ready (shader is compiled)
  71757. */
  71758. PostProcess.prototype.isReady = function () {
  71759. return this._effect && this._effect.isReady();
  71760. };
  71761. /**
  71762. * Binds all textures and uniforms to the shader, this will be run on every pass.
  71763. * @returns the effect corrisponding to this post process. Null if not compiled or not ready.
  71764. */
  71765. PostProcess.prototype.apply = function () {
  71766. // Check
  71767. if (!this._effect || !this._effect.isReady())
  71768. return null;
  71769. // States
  71770. this._engine.enableEffect(this._effect);
  71771. this._engine.setState(false);
  71772. this._engine.setDepthBuffer(false);
  71773. this._engine.setDepthWrite(false);
  71774. // Alpha
  71775. this._engine.setAlphaMode(this.alphaMode);
  71776. if (this.alphaConstants) {
  71777. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  71778. }
  71779. // Bind the output texture of the preivous post process as the input to this post process.
  71780. var source;
  71781. if (this._shareOutputWithPostProcess) {
  71782. source = this._shareOutputWithPostProcess.inputTexture;
  71783. }
  71784. else if (this._forcedOutputTexture) {
  71785. source = this._forcedOutputTexture;
  71786. }
  71787. else {
  71788. source = this.inputTexture;
  71789. }
  71790. this._effect._bindTexture("textureSampler", source);
  71791. // Parameters
  71792. this._effect.setVector2("scale", this._scaleRatio);
  71793. this.onApplyObservable.notifyObservers(this._effect);
  71794. return this._effect;
  71795. };
  71796. PostProcess.prototype._disposeTextures = function () {
  71797. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  71798. return;
  71799. }
  71800. if (this._textures.length > 0) {
  71801. for (var i = 0; i < this._textures.length; i++) {
  71802. this._engine._releaseTexture(this._textures.data[i]);
  71803. }
  71804. }
  71805. this._textures.dispose();
  71806. };
  71807. /**
  71808. * Disposes the post process.
  71809. * @param camera The camera to dispose the post process on.
  71810. */
  71811. PostProcess.prototype.dispose = function (camera) {
  71812. camera = camera || this._camera;
  71813. this._disposeTextures();
  71814. if (this._scene) {
  71815. var index_1 = this._scene.postProcesses.indexOf(this);
  71816. if (index_1 !== -1) {
  71817. this._scene.postProcesses.splice(index_1, 1);
  71818. }
  71819. }
  71820. else {
  71821. var index_2 = this._engine.postProcesses.indexOf(this);
  71822. if (index_2 !== -1) {
  71823. this._engine.postProcesses.splice(index_2, 1);
  71824. }
  71825. }
  71826. if (!camera) {
  71827. return;
  71828. }
  71829. camera.detachPostProcess(this);
  71830. var index = camera._postProcesses.indexOf(this);
  71831. if (index === 0 && camera._postProcesses.length > 0) {
  71832. var firstPostProcess = this._camera._getFirstPostProcess();
  71833. if (firstPostProcess) {
  71834. firstPostProcess.markTextureDirty();
  71835. }
  71836. }
  71837. this.onActivateObservable.clear();
  71838. this.onAfterRenderObservable.clear();
  71839. this.onApplyObservable.clear();
  71840. this.onBeforeRenderObservable.clear();
  71841. this.onSizeChangedObservable.clear();
  71842. };
  71843. return PostProcess;
  71844. }());
  71845. BABYLON.PostProcess = PostProcess;
  71846. })(BABYLON || (BABYLON = {}));
  71847. //# sourceMappingURL=babylon.postProcess.js.map
  71848. var BABYLON;
  71849. (function (BABYLON) {
  71850. var PassPostProcess = /** @class */ (function (_super) {
  71851. __extends(PassPostProcess, _super);
  71852. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  71853. if (camera === void 0) { camera = null; }
  71854. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  71855. if (blockCompilation === void 0) { blockCompilation = false; }
  71856. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, undefined, textureType, undefined, null, blockCompilation) || this;
  71857. }
  71858. return PassPostProcess;
  71859. }(BABYLON.PostProcess));
  71860. BABYLON.PassPostProcess = PassPostProcess;
  71861. })(BABYLON || (BABYLON = {}));
  71862. //# sourceMappingURL=babylon.passPostProcess.js.map
  71863. var __assign = (this && this.__assign) || function () {
  71864. __assign = Object.assign || function(t) {
  71865. for (var s, i = 1, n = arguments.length; i < n; i++) {
  71866. s = arguments[i];
  71867. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  71868. t[p] = s[p];
  71869. }
  71870. return t;
  71871. };
  71872. return __assign.apply(this, arguments);
  71873. };
  71874. var BABYLON;
  71875. (function (BABYLON) {
  71876. /**
  71877. * Default implementation IShadowGenerator.
  71878. * This is the main object responsible of generating shadows in the framework.
  71879. * Documentation: https://doc.babylonjs.com/babylon101/shadows
  71880. */
  71881. var ShadowGenerator = /** @class */ (function () {
  71882. /**
  71883. * Creates a ShadowGenerator object.
  71884. * A ShadowGenerator is the required tool to use the shadows.
  71885. * Each light casting shadows needs to use its own ShadowGenerator.
  71886. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  71887. * @param mapSize The size of the texture what stores the shadows. Example : 1024.
  71888. * @param light The light object generating the shadows.
  71889. * @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.
  71890. */
  71891. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  71892. this._bias = 0.00005;
  71893. this._normalBias = 0;
  71894. this._blurBoxOffset = 1;
  71895. this._blurScale = 2;
  71896. this._blurKernel = 1;
  71897. this._useKernelBlur = false;
  71898. this._filter = ShadowGenerator.FILTER_NONE;
  71899. this._filteringQuality = ShadowGenerator.QUALITY_HIGH;
  71900. this._contactHardeningLightSizeUVRatio = 0.1;
  71901. this._darkness = 0;
  71902. this._transparencyShadow = false;
  71903. /**
  71904. * Controls the extent to which the shadows fade out at the edge of the frustum
  71905. * Used only by directionals and spots
  71906. */
  71907. this.frustumEdgeFalloff = 0;
  71908. /**
  71909. * If true the shadow map is generated by rendering the back face of the mesh instead of the front face.
  71910. * This can help with self-shadowing as the geometry making up the back of objects is slightly offset.
  71911. * It might on the other hand introduce peter panning.
  71912. */
  71913. this.forceBackFacesOnly = false;
  71914. this._lightDirection = BABYLON.Vector3.Zero();
  71915. this._viewMatrix = BABYLON.Matrix.Zero();
  71916. this._projectionMatrix = BABYLON.Matrix.Zero();
  71917. this._transformMatrix = BABYLON.Matrix.Zero();
  71918. this._cachedPosition = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  71919. this._cachedDirection = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  71920. this._currentFaceIndex = 0;
  71921. this._currentFaceIndexCache = 0;
  71922. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  71923. this._mapSize = mapSize;
  71924. this._light = light;
  71925. this._scene = light.getScene();
  71926. light._shadowGenerator = this;
  71927. var component = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_SHADOWGENERATOR);
  71928. if (!component) {
  71929. component = new BABYLON.ShadowGeneratorSceneComponent(this._scene);
  71930. this._scene._addComponent(component);
  71931. }
  71932. // Texture type fallback from float to int if not supported.
  71933. var caps = this._scene.getEngine().getCaps();
  71934. if (!useFullFloatFirst) {
  71935. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  71936. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  71937. }
  71938. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  71939. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  71940. }
  71941. else {
  71942. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  71943. }
  71944. }
  71945. else {
  71946. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  71947. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  71948. }
  71949. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  71950. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  71951. }
  71952. else {
  71953. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  71954. }
  71955. }
  71956. this._initializeGenerator();
  71957. this._applyFilterValues();
  71958. }
  71959. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  71960. /**
  71961. * Gets the bias: offset applied on the depth preventing acnea (in light direction).
  71962. */
  71963. get: function () {
  71964. return this._bias;
  71965. },
  71966. /**
  71967. * Sets the bias: offset applied on the depth preventing acnea (in light direction).
  71968. */
  71969. set: function (bias) {
  71970. this._bias = bias;
  71971. },
  71972. enumerable: true,
  71973. configurable: true
  71974. });
  71975. Object.defineProperty(ShadowGenerator.prototype, "normalBias", {
  71976. /**
  71977. * Gets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  71978. */
  71979. get: function () {
  71980. return this._normalBias;
  71981. },
  71982. /**
  71983. * Sets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  71984. */
  71985. set: function (normalBias) {
  71986. this._normalBias = normalBias;
  71987. },
  71988. enumerable: true,
  71989. configurable: true
  71990. });
  71991. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  71992. /**
  71993. * Gets the blur box offset: offset applied during the blur pass.
  71994. * Only usefull if useKernelBlur = false
  71995. */
  71996. get: function () {
  71997. return this._blurBoxOffset;
  71998. },
  71999. /**
  72000. * Sets the blur box offset: offset applied during the blur pass.
  72001. * Only usefull if useKernelBlur = false
  72002. */
  72003. set: function (value) {
  72004. if (this._blurBoxOffset === value) {
  72005. return;
  72006. }
  72007. this._blurBoxOffset = value;
  72008. this._disposeBlurPostProcesses();
  72009. },
  72010. enumerable: true,
  72011. configurable: true
  72012. });
  72013. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  72014. /**
  72015. * Gets the blur scale: scale of the blurred texture compared to the main shadow map.
  72016. * 2 means half of the size.
  72017. */
  72018. get: function () {
  72019. return this._blurScale;
  72020. },
  72021. /**
  72022. * Sets the blur scale: scale of the blurred texture compared to the main shadow map.
  72023. * 2 means half of the size.
  72024. */
  72025. set: function (value) {
  72026. if (this._blurScale === value) {
  72027. return;
  72028. }
  72029. this._blurScale = value;
  72030. this._disposeBlurPostProcesses();
  72031. },
  72032. enumerable: true,
  72033. configurable: true
  72034. });
  72035. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  72036. /**
  72037. * Gets the blur kernel: kernel size of the blur pass.
  72038. * Only usefull if useKernelBlur = true
  72039. */
  72040. get: function () {
  72041. return this._blurKernel;
  72042. },
  72043. /**
  72044. * Sets the blur kernel: kernel size of the blur pass.
  72045. * Only usefull if useKernelBlur = true
  72046. */
  72047. set: function (value) {
  72048. if (this._blurKernel === value) {
  72049. return;
  72050. }
  72051. this._blurKernel = value;
  72052. this._disposeBlurPostProcesses();
  72053. },
  72054. enumerable: true,
  72055. configurable: true
  72056. });
  72057. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  72058. /**
  72059. * Gets whether the blur pass is a kernel blur (if true) or box blur.
  72060. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  72061. */
  72062. get: function () {
  72063. return this._useKernelBlur;
  72064. },
  72065. /**
  72066. * Sets whether the blur pass is a kernel blur (if true) or box blur.
  72067. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  72068. */
  72069. set: function (value) {
  72070. if (this._useKernelBlur === value) {
  72071. return;
  72072. }
  72073. this._useKernelBlur = value;
  72074. this._disposeBlurPostProcesses();
  72075. },
  72076. enumerable: true,
  72077. configurable: true
  72078. });
  72079. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  72080. /**
  72081. * Gets the depth scale used in ESM mode.
  72082. */
  72083. get: function () {
  72084. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  72085. },
  72086. /**
  72087. * Sets the depth scale used in ESM mode.
  72088. * This can override the scale stored on the light.
  72089. */
  72090. set: function (value) {
  72091. this._depthScale = value;
  72092. },
  72093. enumerable: true,
  72094. configurable: true
  72095. });
  72096. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  72097. /**
  72098. * Gets the current mode of the shadow generator (normal, PCF, ESM...).
  72099. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  72100. */
  72101. get: function () {
  72102. return this._filter;
  72103. },
  72104. /**
  72105. * Sets the current mode of the shadow generator (normal, PCF, ESM...).
  72106. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  72107. */
  72108. set: function (value) {
  72109. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  72110. if (this._light.needCube()) {
  72111. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  72112. this.useExponentialShadowMap = true;
  72113. return;
  72114. }
  72115. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  72116. this.useCloseExponentialShadowMap = true;
  72117. return;
  72118. }
  72119. // PCF on cubemap would also be expensive
  72120. else if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  72121. this.usePoissonSampling = true;
  72122. return;
  72123. }
  72124. }
  72125. // Weblg1 fallback for PCF.
  72126. if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  72127. if (this._scene.getEngine().webGLVersion === 1) {
  72128. this.usePoissonSampling = true;
  72129. return;
  72130. }
  72131. }
  72132. if (this._filter === value) {
  72133. return;
  72134. }
  72135. this._filter = value;
  72136. this._disposeBlurPostProcesses();
  72137. this._applyFilterValues();
  72138. this._light._markMeshesAsLightDirty();
  72139. },
  72140. enumerable: true,
  72141. configurable: true
  72142. });
  72143. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  72144. /**
  72145. * Gets if the current filter is set to Poisson Sampling.
  72146. */
  72147. get: function () {
  72148. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  72149. },
  72150. /**
  72151. * Sets the current filter to Poisson Sampling.
  72152. */
  72153. set: function (value) {
  72154. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  72155. return;
  72156. }
  72157. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  72158. },
  72159. enumerable: true,
  72160. configurable: true
  72161. });
  72162. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  72163. /**
  72164. * Gets if the current filter is set to VSM.
  72165. * DEPRECATED. Should use useExponentialShadowMap instead.
  72166. */
  72167. get: function () {
  72168. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  72169. return this.useExponentialShadowMap;
  72170. },
  72171. /**
  72172. * Sets the current filter is to VSM.
  72173. * DEPRECATED. Should use useExponentialShadowMap instead.
  72174. */
  72175. set: function (value) {
  72176. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  72177. this.useExponentialShadowMap = value;
  72178. },
  72179. enumerable: true,
  72180. configurable: true
  72181. });
  72182. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  72183. /**
  72184. * Gets if the current filter is set to blurred VSM.
  72185. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  72186. */
  72187. get: function () {
  72188. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  72189. return this.useBlurExponentialShadowMap;
  72190. },
  72191. /**
  72192. * Sets the current filter is to blurred VSM.
  72193. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  72194. */
  72195. set: function (value) {
  72196. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  72197. this.useBlurExponentialShadowMap = value;
  72198. },
  72199. enumerable: true,
  72200. configurable: true
  72201. });
  72202. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  72203. /**
  72204. * Gets if the current filter is set to ESM.
  72205. */
  72206. get: function () {
  72207. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  72208. },
  72209. /**
  72210. * Sets the current filter is to ESM.
  72211. */
  72212. set: function (value) {
  72213. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  72214. return;
  72215. }
  72216. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  72217. },
  72218. enumerable: true,
  72219. configurable: true
  72220. });
  72221. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  72222. /**
  72223. * Gets if the current filter is set to filtered ESM.
  72224. */
  72225. get: function () {
  72226. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  72227. },
  72228. /**
  72229. * Gets if the current filter is set to filtered ESM.
  72230. */
  72231. set: function (value) {
  72232. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  72233. return;
  72234. }
  72235. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  72236. },
  72237. enumerable: true,
  72238. configurable: true
  72239. });
  72240. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  72241. /**
  72242. * Gets if the current filter is set to "close ESM" (using the inverse of the
  72243. * exponential to prevent steep falloff artifacts).
  72244. */
  72245. get: function () {
  72246. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  72247. },
  72248. /**
  72249. * Sets the current filter to "close ESM" (using the inverse of the
  72250. * exponential to prevent steep falloff artifacts).
  72251. */
  72252. set: function (value) {
  72253. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  72254. return;
  72255. }
  72256. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  72257. },
  72258. enumerable: true,
  72259. configurable: true
  72260. });
  72261. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  72262. /**
  72263. * Gets if the current filter is set to filtered "close ESM" (using the inverse of the
  72264. * exponential to prevent steep falloff artifacts).
  72265. */
  72266. get: function () {
  72267. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  72268. },
  72269. /**
  72270. * Sets the current filter to filtered "close ESM" (using the inverse of the
  72271. * exponential to prevent steep falloff artifacts).
  72272. */
  72273. set: function (value) {
  72274. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  72275. return;
  72276. }
  72277. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  72278. },
  72279. enumerable: true,
  72280. configurable: true
  72281. });
  72282. Object.defineProperty(ShadowGenerator.prototype, "usePercentageCloserFiltering", {
  72283. /**
  72284. * Gets if the current filter is set to "PCF" (percentage closer filtering).
  72285. */
  72286. get: function () {
  72287. return this.filter === ShadowGenerator.FILTER_PCF;
  72288. },
  72289. /**
  72290. * Sets the current filter to "PCF" (percentage closer filtering).
  72291. */
  72292. set: function (value) {
  72293. if (!value && this.filter !== ShadowGenerator.FILTER_PCF) {
  72294. return;
  72295. }
  72296. this.filter = (value ? ShadowGenerator.FILTER_PCF : ShadowGenerator.FILTER_NONE);
  72297. },
  72298. enumerable: true,
  72299. configurable: true
  72300. });
  72301. Object.defineProperty(ShadowGenerator.prototype, "filteringQuality", {
  72302. /**
  72303. * Gets the PCF or PCSS Quality.
  72304. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  72305. */
  72306. get: function () {
  72307. return this._filteringQuality;
  72308. },
  72309. /**
  72310. * Sets the PCF or PCSS Quality.
  72311. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  72312. */
  72313. set: function (filteringQuality) {
  72314. this._filteringQuality = filteringQuality;
  72315. },
  72316. enumerable: true,
  72317. configurable: true
  72318. });
  72319. Object.defineProperty(ShadowGenerator.prototype, "useContactHardeningShadow", {
  72320. /**
  72321. * Gets if the current filter is set to "PCSS" (contact hardening).
  72322. */
  72323. get: function () {
  72324. return this.filter === ShadowGenerator.FILTER_PCSS;
  72325. },
  72326. /**
  72327. * Sets the current filter to "PCSS" (contact hardening).
  72328. */
  72329. set: function (value) {
  72330. if (!value && this.filter !== ShadowGenerator.FILTER_PCSS) {
  72331. return;
  72332. }
  72333. this.filter = (value ? ShadowGenerator.FILTER_PCSS : ShadowGenerator.FILTER_NONE);
  72334. },
  72335. enumerable: true,
  72336. configurable: true
  72337. });
  72338. Object.defineProperty(ShadowGenerator.prototype, "contactHardeningLightSizeUVRatio", {
  72339. /**
  72340. * Gets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  72341. * Using a ratio helps keeping shape stability independently of the map size.
  72342. *
  72343. * It does not account for the light projection as it was having too much
  72344. * instability during the light setup or during light position changes.
  72345. *
  72346. * Only valid if useContactHardeningShadow is true.
  72347. */
  72348. get: function () {
  72349. return this._contactHardeningLightSizeUVRatio;
  72350. },
  72351. /**
  72352. * Sets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  72353. * Using a ratio helps keeping shape stability independently of the map size.
  72354. *
  72355. * It does not account for the light projection as it was having too much
  72356. * instability during the light setup or during light position changes.
  72357. *
  72358. * Only valid if useContactHardeningShadow is true.
  72359. */
  72360. set: function (contactHardeningLightSizeUVRatio) {
  72361. this._contactHardeningLightSizeUVRatio = contactHardeningLightSizeUVRatio;
  72362. },
  72363. enumerable: true,
  72364. configurable: true
  72365. });
  72366. /**
  72367. * Returns the darkness value (float). This can only decrease the actual darkness of a shadow.
  72368. * 0 means strongest and 1 would means no shadow.
  72369. * @returns the darkness.
  72370. */
  72371. ShadowGenerator.prototype.getDarkness = function () {
  72372. return this._darkness;
  72373. };
  72374. /**
  72375. * Sets the darkness value (float). This can only decrease the actual darkness of a shadow.
  72376. * @param darkness The darkness value 0 means strongest and 1 would means no shadow.
  72377. * @returns the shadow generator allowing fluent coding.
  72378. */
  72379. ShadowGenerator.prototype.setDarkness = function (darkness) {
  72380. if (darkness >= 1.0)
  72381. this._darkness = 1.0;
  72382. else if (darkness <= 0.0)
  72383. this._darkness = 0.0;
  72384. else
  72385. this._darkness = darkness;
  72386. return this;
  72387. };
  72388. /**
  72389. * Sets the ability to have transparent shadow (boolean).
  72390. * @param transparent True if transparent else False
  72391. * @returns the shadow generator allowing fluent coding
  72392. */
  72393. ShadowGenerator.prototype.setTransparencyShadow = function (transparent) {
  72394. this._transparencyShadow = transparent;
  72395. return this;
  72396. };
  72397. /**
  72398. * Gets the main RTT containing the shadow map (usually storing depth from the light point of view).
  72399. * @returns The render target texture if present otherwise, null
  72400. */
  72401. ShadowGenerator.prototype.getShadowMap = function () {
  72402. return this._shadowMap;
  72403. };
  72404. /**
  72405. * Gets the RTT used during rendering (can be a blurred version of the shadow map or the shadow map itself).
  72406. * @returns The render target texture if the shadow map is present otherwise, null
  72407. */
  72408. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  72409. if (this._shadowMap2) {
  72410. return this._shadowMap2;
  72411. }
  72412. return this._shadowMap;
  72413. };
  72414. /**
  72415. * Helper function to add a mesh and its descendants to the list of shadow casters.
  72416. * @param mesh Mesh to add
  72417. * @param includeDescendants boolean indicating if the descendants should be added. Default to true
  72418. * @returns the Shadow Generator itself
  72419. */
  72420. ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) {
  72421. if (includeDescendants === void 0) { includeDescendants = true; }
  72422. var _a;
  72423. if (!this._shadowMap) {
  72424. return this;
  72425. }
  72426. if (!this._shadowMap.renderList) {
  72427. this._shadowMap.renderList = [];
  72428. }
  72429. this._shadowMap.renderList.push(mesh);
  72430. if (includeDescendants) {
  72431. (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes());
  72432. }
  72433. return this;
  72434. };
  72435. /**
  72436. * Helper function to remove a mesh and its descendants from the list of shadow casters
  72437. * @param mesh Mesh to remove
  72438. * @param includeDescendants boolean indicating if the descendants should be removed. Default to true
  72439. * @returns the Shadow Generator itself
  72440. */
  72441. ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) {
  72442. if (includeDescendants === void 0) { includeDescendants = true; }
  72443. if (!this._shadowMap || !this._shadowMap.renderList) {
  72444. return this;
  72445. }
  72446. var index = this._shadowMap.renderList.indexOf(mesh);
  72447. if (index !== -1) {
  72448. this._shadowMap.renderList.splice(index, 1);
  72449. }
  72450. if (includeDescendants) {
  72451. for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) {
  72452. var child = _a[_i];
  72453. this.removeShadowCaster(child);
  72454. }
  72455. }
  72456. return this;
  72457. };
  72458. /**
  72459. * Returns the associated light object.
  72460. * @returns the light generating the shadow
  72461. */
  72462. ShadowGenerator.prototype.getLight = function () {
  72463. return this._light;
  72464. };
  72465. ShadowGenerator.prototype._initializeGenerator = function () {
  72466. this._light._markMeshesAsLightDirty();
  72467. this._initializeShadowMap();
  72468. };
  72469. ShadowGenerator.prototype._initializeShadowMap = function () {
  72470. var _this = this;
  72471. // Render target
  72472. var engine = this._scene.getEngine();
  72473. if (engine.webGLVersion > 1) {
  72474. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube(), undefined, false, false);
  72475. this._shadowMap.createDepthStencilTexture(BABYLON.Engine.LESS, true);
  72476. }
  72477. else {
  72478. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  72479. }
  72480. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  72481. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  72482. this._shadowMap.anisotropicFilteringLevel = 1;
  72483. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  72484. this._shadowMap.renderParticles = false;
  72485. this._shadowMap.ignoreCameraViewport = true;
  72486. // Record Face Index before render.
  72487. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  72488. _this._currentFaceIndex = faceIndex;
  72489. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  72490. engine.setColorWrite(false);
  72491. }
  72492. });
  72493. // Custom render function.
  72494. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  72495. // Blur if required afer render.
  72496. this._shadowMap.onAfterUnbindObservable.add(function () {
  72497. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  72498. engine.setColorWrite(true);
  72499. }
  72500. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  72501. return;
  72502. }
  72503. var shadowMap = _this.getShadowMapForRendering();
  72504. if (shadowMap) {
  72505. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, shadowMap.getInternalTexture(), true);
  72506. }
  72507. });
  72508. // Clear according to the chosen filter.
  72509. var clearZero = new BABYLON.Color4(0, 0, 0, 0);
  72510. var clearOne = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  72511. this._shadowMap.onClearObservable.add(function (engine) {
  72512. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  72513. engine.clear(clearOne, false, true, false);
  72514. }
  72515. else if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  72516. engine.clear(clearZero, true, true, false);
  72517. }
  72518. else {
  72519. engine.clear(clearOne, true, true, false);
  72520. }
  72521. });
  72522. };
  72523. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  72524. var _this = this;
  72525. var engine = this._scene.getEngine();
  72526. var targetSize = this._mapSize / this.blurScale;
  72527. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  72528. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  72529. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  72530. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  72531. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  72532. }
  72533. if (this.useKernelBlur) {
  72534. 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);
  72535. this._kernelBlurXPostprocess.width = targetSize;
  72536. this._kernelBlurXPostprocess.height = targetSize;
  72537. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  72538. effect.setTexture("textureSampler", _this._shadowMap);
  72539. });
  72540. 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);
  72541. this._kernelBlurXPostprocess.autoClear = false;
  72542. this._kernelBlurYPostprocess.autoClear = false;
  72543. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  72544. this._kernelBlurXPostprocess.packedFloat = true;
  72545. this._kernelBlurYPostprocess.packedFloat = true;
  72546. }
  72547. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  72548. }
  72549. else {
  72550. 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);
  72551. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  72552. effect.setFloat2("screenSize", targetSize, targetSize);
  72553. effect.setTexture("textureSampler", _this._shadowMap);
  72554. });
  72555. this._boxBlurPostprocess.autoClear = false;
  72556. this._blurPostProcesses = [this._boxBlurPostprocess];
  72557. }
  72558. };
  72559. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  72560. var index;
  72561. var engine = this._scene.getEngine();
  72562. if (depthOnlySubMeshes.length) {
  72563. engine.setColorWrite(false);
  72564. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  72565. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  72566. }
  72567. engine.setColorWrite(true);
  72568. }
  72569. for (index = 0; index < opaqueSubMeshes.length; index++) {
  72570. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  72571. }
  72572. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  72573. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  72574. }
  72575. if (this._transparencyShadow) {
  72576. for (index = 0; index < transparentSubMeshes.length; index++) {
  72577. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  72578. }
  72579. }
  72580. };
  72581. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  72582. var _this = this;
  72583. var mesh = subMesh.getRenderingMesh();
  72584. var scene = this._scene;
  72585. var engine = scene.getEngine();
  72586. var material = subMesh.getMaterial();
  72587. if (!material) {
  72588. return;
  72589. }
  72590. // Culling
  72591. engine.setState(material.backFaceCulling);
  72592. // Managing instances
  72593. var batch = mesh._getInstancesRenderList(subMesh._id);
  72594. if (batch.mustReturn) {
  72595. return;
  72596. }
  72597. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  72598. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  72599. engine.enableEffect(this._effect);
  72600. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  72601. this._effect.setFloat3("biasAndScale", this.bias, this.normalBias, this.depthScale);
  72602. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  72603. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  72604. this._effect.setVector3("lightData", this._cachedDirection);
  72605. }
  72606. else {
  72607. this._effect.setVector3("lightData", this._cachedPosition);
  72608. }
  72609. if (scene.activeCamera) {
  72610. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  72611. }
  72612. // Alpha test
  72613. if (material && material.needAlphaTesting()) {
  72614. var alphaTexture = material.getAlphaTestTexture();
  72615. if (alphaTexture) {
  72616. this._effect.setTexture("diffuseSampler", alphaTexture);
  72617. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  72618. }
  72619. }
  72620. // Bones
  72621. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  72622. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices((mesh)));
  72623. }
  72624. // Morph targets
  72625. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effect);
  72626. if (this.forceBackFacesOnly) {
  72627. engine.setState(true, 0, false, true);
  72628. }
  72629. // Draw
  72630. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  72631. if (this.forceBackFacesOnly) {
  72632. engine.setState(true, 0, false, false);
  72633. }
  72634. }
  72635. else {
  72636. // Need to reset refresh rate of the shadowMap
  72637. if (this._shadowMap) {
  72638. this._shadowMap.resetRefreshCounter();
  72639. }
  72640. }
  72641. };
  72642. ShadowGenerator.prototype._applyFilterValues = function () {
  72643. if (!this._shadowMap) {
  72644. return;
  72645. }
  72646. if (this.filter === ShadowGenerator.FILTER_NONE || this.filter === ShadowGenerator.FILTER_PCSS) {
  72647. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  72648. }
  72649. else {
  72650. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  72651. }
  72652. };
  72653. /**
  72654. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  72655. * @param onCompiled Callback triggered at the and of the effects compilation
  72656. * @param options Sets of optional options forcing the compilation with different modes
  72657. */
  72658. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  72659. var _this = this;
  72660. var localOptions = __assign({ useInstances: false }, options);
  72661. var shadowMap = this.getShadowMap();
  72662. if (!shadowMap) {
  72663. if (onCompiled) {
  72664. onCompiled(this);
  72665. }
  72666. return;
  72667. }
  72668. var renderList = shadowMap.renderList;
  72669. if (!renderList) {
  72670. if (onCompiled) {
  72671. onCompiled(this);
  72672. }
  72673. return;
  72674. }
  72675. var subMeshes = new Array();
  72676. for (var _i = 0, renderList_1 = renderList; _i < renderList_1.length; _i++) {
  72677. var mesh = renderList_1[_i];
  72678. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  72679. }
  72680. if (subMeshes.length === 0) {
  72681. if (onCompiled) {
  72682. onCompiled(this);
  72683. }
  72684. return;
  72685. }
  72686. var currentIndex = 0;
  72687. var checkReady = function () {
  72688. if (!_this._scene || !_this._scene.getEngine()) {
  72689. return;
  72690. }
  72691. while (_this.isReady(subMeshes[currentIndex], localOptions.useInstances)) {
  72692. currentIndex++;
  72693. if (currentIndex >= subMeshes.length) {
  72694. if (onCompiled) {
  72695. onCompiled(_this);
  72696. }
  72697. return;
  72698. }
  72699. }
  72700. setTimeout(checkReady, 16);
  72701. };
  72702. checkReady();
  72703. };
  72704. /**
  72705. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  72706. * @param options Sets of optional options forcing the compilation with different modes
  72707. * @returns A promise that resolves when the compilation completes
  72708. */
  72709. ShadowGenerator.prototype.forceCompilationAsync = function (options) {
  72710. var _this = this;
  72711. return new Promise(function (resolve) {
  72712. _this.forceCompilation(function () {
  72713. resolve();
  72714. }, options);
  72715. });
  72716. };
  72717. /**
  72718. * Determine wheter the shadow generator is ready or not (mainly all effects and related post processes needs to be ready).
  72719. * @param subMesh The submesh we want to render in the shadow map
  72720. * @param useInstances Defines wether will draw in the map using instances
  72721. * @returns true if ready otherwise, false
  72722. */
  72723. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  72724. var defines = [];
  72725. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  72726. defines.push("#define FLOAT");
  72727. }
  72728. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  72729. defines.push("#define ESM");
  72730. }
  72731. else if (this.usePercentageCloserFiltering || this.useContactHardeningShadow) {
  72732. defines.push("#define DEPTHTEXTURE");
  72733. }
  72734. var attribs = [BABYLON.VertexBuffer.PositionKind];
  72735. var mesh = subMesh.getMesh();
  72736. var material = subMesh.getMaterial();
  72737. // Normal bias.
  72738. if (this.normalBias && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  72739. attribs.push(BABYLON.VertexBuffer.NormalKind);
  72740. defines.push("#define NORMAL");
  72741. if (mesh.nonUniformScaling) {
  72742. defines.push("#define NONUNIFORMSCALING");
  72743. }
  72744. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  72745. defines.push("#define DIRECTIONINLIGHTDATA");
  72746. }
  72747. }
  72748. // Alpha test
  72749. if (material && material.needAlphaTesting()) {
  72750. var alphaTexture = material.getAlphaTestTexture();
  72751. if (alphaTexture) {
  72752. defines.push("#define ALPHATEST");
  72753. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  72754. attribs.push(BABYLON.VertexBuffer.UVKind);
  72755. defines.push("#define UV1");
  72756. }
  72757. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  72758. if (alphaTexture.coordinatesIndex === 1) {
  72759. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  72760. defines.push("#define UV2");
  72761. }
  72762. }
  72763. }
  72764. }
  72765. // Bones
  72766. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  72767. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  72768. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  72769. if (mesh.numBoneInfluencers > 4) {
  72770. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  72771. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  72772. }
  72773. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  72774. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  72775. }
  72776. else {
  72777. defines.push("#define NUM_BONE_INFLUENCERS 0");
  72778. }
  72779. // Morph targets
  72780. var manager = mesh.morphTargetManager;
  72781. var morphInfluencers = 0;
  72782. if (manager) {
  72783. if (manager.numInfluencers > 0) {
  72784. defines.push("#define MORPHTARGETS");
  72785. morphInfluencers = manager.numInfluencers;
  72786. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  72787. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  72788. }
  72789. }
  72790. // Instances
  72791. if (useInstances) {
  72792. defines.push("#define INSTANCES");
  72793. attribs.push("world0");
  72794. attribs.push("world1");
  72795. attribs.push("world2");
  72796. attribs.push("world3");
  72797. }
  72798. // Get correct effect
  72799. var join = defines.join("\n");
  72800. if (this._cachedDefines !== join) {
  72801. this._cachedDefines = join;
  72802. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightData", "depthValues", "biasAndScale", "morphTargetInfluences"], ["diffuseSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  72803. }
  72804. if (!this._effect.isReady()) {
  72805. return false;
  72806. }
  72807. if (this.useBlurExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  72808. if (!this._blurPostProcesses || !this._blurPostProcesses.length) {
  72809. this._initializeBlurRTTAndPostProcesses();
  72810. }
  72811. }
  72812. if (this._kernelBlurXPostprocess && !this._kernelBlurXPostprocess.isReady()) {
  72813. return false;
  72814. }
  72815. if (this._kernelBlurYPostprocess && !this._kernelBlurYPostprocess.isReady()) {
  72816. return false;
  72817. }
  72818. if (this._boxBlurPostprocess && !this._boxBlurPostprocess.isReady()) {
  72819. return false;
  72820. }
  72821. return true;
  72822. };
  72823. /**
  72824. * Prepare all the defines in a material relying on a shadow map at the specified light index.
  72825. * @param defines Defines of the material we want to update
  72826. * @param lightIndex Index of the light in the enabled light list of the material
  72827. */
  72828. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  72829. var scene = this._scene;
  72830. var light = this._light;
  72831. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  72832. return;
  72833. }
  72834. defines["SHADOW" + lightIndex] = true;
  72835. if (this.useContactHardeningShadow) {
  72836. defines["SHADOWPCSS" + lightIndex] = true;
  72837. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  72838. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  72839. }
  72840. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  72841. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  72842. }
  72843. // else default to high.
  72844. }
  72845. if (this.usePercentageCloserFiltering) {
  72846. defines["SHADOWPCF" + lightIndex] = true;
  72847. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  72848. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  72849. }
  72850. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  72851. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  72852. }
  72853. // else default to high.
  72854. }
  72855. else if (this.usePoissonSampling) {
  72856. defines["SHADOWPOISSON" + lightIndex] = true;
  72857. }
  72858. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  72859. defines["SHADOWESM" + lightIndex] = true;
  72860. }
  72861. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  72862. defines["SHADOWCLOSEESM" + lightIndex] = true;
  72863. }
  72864. if (light.needCube()) {
  72865. defines["SHADOWCUBE" + lightIndex] = true;
  72866. }
  72867. };
  72868. /**
  72869. * Binds the shadow related information inside of an effect (information like near, far, darkness...
  72870. * defined in the generator but impacting the effect).
  72871. * @param lightIndex Index of the light in the enabled light list of the material owning the effect
  72872. * @param effect The effect we are binfing the information for
  72873. */
  72874. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  72875. var light = this._light;
  72876. var scene = this._scene;
  72877. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  72878. return;
  72879. }
  72880. var camera = scene.activeCamera;
  72881. if (!camera) {
  72882. return;
  72883. }
  72884. var shadowMap = this.getShadowMap();
  72885. if (!shadowMap) {
  72886. return;
  72887. }
  72888. if (!light.needCube()) {
  72889. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  72890. }
  72891. // Only PCF uses depth stencil texture.
  72892. if (this._filter === ShadowGenerator.FILTER_PCF) {
  72893. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  72894. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), shadowMap.getSize().width, 1 / shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  72895. }
  72896. else if (this._filter === ShadowGenerator.FILTER_PCSS) {
  72897. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  72898. effect.setTexture("depthSampler" + lightIndex, this.getShadowMapForRendering());
  72899. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), 1 / shadowMap.getSize().width, this._contactHardeningLightSizeUVRatio * shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  72900. }
  72901. else {
  72902. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  72903. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  72904. }
  72905. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);
  72906. };
  72907. /**
  72908. * Gets the transformation matrix used to project the meshes into the map from the light point of view.
  72909. * (eq to shadow prjection matrix * light transform matrix)
  72910. * @returns The transform matrix used to create the shadow map
  72911. */
  72912. ShadowGenerator.prototype.getTransformMatrix = function () {
  72913. var scene = this._scene;
  72914. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  72915. return this._transformMatrix;
  72916. }
  72917. this._currentRenderID = scene.getRenderId();
  72918. this._currentFaceIndexCache = this._currentFaceIndex;
  72919. var lightPosition = this._light.position;
  72920. if (this._light.computeTransformedInformation()) {
  72921. lightPosition = this._light.transformedPosition;
  72922. }
  72923. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  72924. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  72925. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  72926. }
  72927. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  72928. this._cachedPosition.copyFrom(lightPosition);
  72929. this._cachedDirection.copyFrom(this._lightDirection);
  72930. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  72931. var shadowMap = this.getShadowMap();
  72932. if (shadowMap) {
  72933. var renderList = shadowMap.renderList;
  72934. if (renderList) {
  72935. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);
  72936. }
  72937. }
  72938. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  72939. }
  72940. return this._transformMatrix;
  72941. };
  72942. /**
  72943. * Recreates the shadow map dependencies like RTT and post processes. This can be used during the switch between
  72944. * Cube and 2D textures for instance.
  72945. */
  72946. ShadowGenerator.prototype.recreateShadowMap = function () {
  72947. var shadowMap = this._shadowMap;
  72948. if (!shadowMap) {
  72949. return;
  72950. }
  72951. // Track render list.
  72952. var renderList = shadowMap.renderList;
  72953. // Clean up existing data.
  72954. this._disposeRTTandPostProcesses();
  72955. // Reinitializes.
  72956. this._initializeGenerator();
  72957. // Reaffect the filter to ensure a correct fallback if necessary.
  72958. this.filter = this.filter;
  72959. // Reaffect the filter.
  72960. this._applyFilterValues();
  72961. // Reaffect Render List.
  72962. this._shadowMap.renderList = renderList;
  72963. };
  72964. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  72965. if (this._shadowMap2) {
  72966. this._shadowMap2.dispose();
  72967. this._shadowMap2 = null;
  72968. }
  72969. if (this._boxBlurPostprocess) {
  72970. this._boxBlurPostprocess.dispose();
  72971. this._boxBlurPostprocess = null;
  72972. }
  72973. if (this._kernelBlurXPostprocess) {
  72974. this._kernelBlurXPostprocess.dispose();
  72975. this._kernelBlurXPostprocess = null;
  72976. }
  72977. if (this._kernelBlurYPostprocess) {
  72978. this._kernelBlurYPostprocess.dispose();
  72979. this._kernelBlurYPostprocess = null;
  72980. }
  72981. this._blurPostProcesses = [];
  72982. };
  72983. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  72984. if (this._shadowMap) {
  72985. this._shadowMap.dispose();
  72986. this._shadowMap = null;
  72987. }
  72988. this._disposeBlurPostProcesses();
  72989. };
  72990. /**
  72991. * Disposes the ShadowGenerator.
  72992. * Returns nothing.
  72993. */
  72994. ShadowGenerator.prototype.dispose = function () {
  72995. this._disposeRTTandPostProcesses();
  72996. if (this._light) {
  72997. this._light._shadowGenerator = null;
  72998. this._light._markMeshesAsLightDirty();
  72999. }
  73000. };
  73001. /**
  73002. * Serializes the shadow generator setup to a json object.
  73003. * @returns The serialized JSON object
  73004. */
  73005. ShadowGenerator.prototype.serialize = function () {
  73006. var serializationObject = {};
  73007. var shadowMap = this.getShadowMap();
  73008. if (!shadowMap) {
  73009. return serializationObject;
  73010. }
  73011. serializationObject.lightId = this._light.id;
  73012. serializationObject.mapSize = shadowMap.getRenderSize();
  73013. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  73014. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  73015. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  73016. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  73017. serializationObject.usePoissonSampling = this.usePoissonSampling;
  73018. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  73019. serializationObject.depthScale = this.depthScale;
  73020. serializationObject.darkness = this.getDarkness();
  73021. serializationObject.blurBoxOffset = this.blurBoxOffset;
  73022. serializationObject.blurKernel = this.blurKernel;
  73023. serializationObject.blurScale = this.blurScale;
  73024. serializationObject.useKernelBlur = this.useKernelBlur;
  73025. serializationObject.transparencyShadow = this._transparencyShadow;
  73026. serializationObject.frustumEdgeFalloff = this.frustumEdgeFalloff;
  73027. serializationObject.bias = this.bias;
  73028. serializationObject.normalBias = this.normalBias;
  73029. serializationObject.usePercentageCloserFiltering = this.usePercentageCloserFiltering;
  73030. serializationObject.useContactHardeningShadow = this.useContactHardeningShadow;
  73031. serializationObject.filteringQuality = this.filteringQuality;
  73032. serializationObject.contactHardeningLightSizeUVRatio = this.contactHardeningLightSizeUVRatio;
  73033. serializationObject.renderList = [];
  73034. if (shadowMap.renderList) {
  73035. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  73036. var mesh = shadowMap.renderList[meshIndex];
  73037. serializationObject.renderList.push(mesh.id);
  73038. }
  73039. }
  73040. return serializationObject;
  73041. };
  73042. /**
  73043. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  73044. * @param parsedShadowGenerator The JSON object to parse
  73045. * @param scene The scene to create the shadow map for
  73046. * @returns The parsed shadow generator
  73047. */
  73048. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  73049. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  73050. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  73051. var shadowMap = shadowGenerator.getShadowMap();
  73052. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  73053. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  73054. meshes.forEach(function (mesh) {
  73055. if (!shadowMap) {
  73056. return;
  73057. }
  73058. if (!shadowMap.renderList) {
  73059. shadowMap.renderList = [];
  73060. }
  73061. shadowMap.renderList.push(mesh);
  73062. });
  73063. }
  73064. if (parsedShadowGenerator.usePoissonSampling) {
  73065. shadowGenerator.usePoissonSampling = true;
  73066. }
  73067. else if (parsedShadowGenerator.useExponentialShadowMap) {
  73068. shadowGenerator.useExponentialShadowMap = true;
  73069. }
  73070. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  73071. shadowGenerator.useBlurExponentialShadowMap = true;
  73072. }
  73073. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  73074. shadowGenerator.useCloseExponentialShadowMap = true;
  73075. }
  73076. else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
  73077. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  73078. }
  73079. else if (parsedShadowGenerator.usePercentageCloserFiltering) {
  73080. shadowGenerator.usePercentageCloserFiltering = true;
  73081. }
  73082. else if (parsedShadowGenerator.useContactHardeningShadow) {
  73083. shadowGenerator.useContactHardeningShadow = true;
  73084. }
  73085. if (parsedShadowGenerator.filteringQuality) {
  73086. shadowGenerator.filteringQuality = parsedShadowGenerator.filteringQuality;
  73087. }
  73088. if (parsedShadowGenerator.contactHardeningLightSizeUVRatio) {
  73089. shadowGenerator.contactHardeningLightSizeUVRatio = parsedShadowGenerator.contactHardeningLightSizeUVRatio;
  73090. }
  73091. // Backward compat
  73092. else if (parsedShadowGenerator.useVarianceShadowMap) {
  73093. shadowGenerator.useExponentialShadowMap = true;
  73094. }
  73095. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  73096. shadowGenerator.useBlurExponentialShadowMap = true;
  73097. }
  73098. if (parsedShadowGenerator.depthScale) {
  73099. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  73100. }
  73101. if (parsedShadowGenerator.blurScale) {
  73102. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  73103. }
  73104. if (parsedShadowGenerator.blurBoxOffset) {
  73105. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  73106. }
  73107. if (parsedShadowGenerator.useKernelBlur) {
  73108. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  73109. }
  73110. if (parsedShadowGenerator.blurKernel) {
  73111. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  73112. }
  73113. if (parsedShadowGenerator.bias !== undefined) {
  73114. shadowGenerator.bias = parsedShadowGenerator.bias;
  73115. }
  73116. if (parsedShadowGenerator.normalBias !== undefined) {
  73117. shadowGenerator.normalBias = parsedShadowGenerator.normalBias;
  73118. }
  73119. if (parsedShadowGenerator.frustumEdgeFalloff !== undefined) {
  73120. shadowGenerator.frustumEdgeFalloff = parsedShadowGenerator.frustumEdgeFalloff;
  73121. }
  73122. if (parsedShadowGenerator.darkness) {
  73123. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  73124. }
  73125. if (parsedShadowGenerator.transparencyShadow) {
  73126. shadowGenerator.setTransparencyShadow(true);
  73127. }
  73128. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  73129. return shadowGenerator;
  73130. };
  73131. /**
  73132. * Shadow generator mode None: no filtering applied.
  73133. */
  73134. ShadowGenerator.FILTER_NONE = 0;
  73135. /**
  73136. * Shadow generator mode ESM: Exponential Shadow Mapping.
  73137. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  73138. */
  73139. ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP = 1;
  73140. /**
  73141. * Shadow generator mode Poisson Sampling: Percentage Closer Filtering.
  73142. * (Multiple Tap around evenly distributed around the pixel are used to evaluate the shadow strength)
  73143. */
  73144. ShadowGenerator.FILTER_POISSONSAMPLING = 2;
  73145. /**
  73146. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping.
  73147. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  73148. */
  73149. ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  73150. /**
  73151. * Shadow generator mode ESM: Exponential Shadow Mapping using the inverse of the exponential preventing
  73152. * edge artifacts on steep falloff.
  73153. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  73154. */
  73155. ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  73156. /**
  73157. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping using the inverse of the exponential preventing
  73158. * edge artifacts on steep falloff.
  73159. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  73160. */
  73161. ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  73162. /**
  73163. * Shadow generator mode PCF: Percentage Closer Filtering
  73164. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  73165. * (https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch11.html)
  73166. */
  73167. ShadowGenerator.FILTER_PCF = 6;
  73168. /**
  73169. * Shadow generator mode PCSS: Percentage Closering Soft Shadow.
  73170. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  73171. * Contact Hardening
  73172. */
  73173. ShadowGenerator.FILTER_PCSS = 7;
  73174. /**
  73175. * Reserved for PCF and PCSS
  73176. * Highest Quality.
  73177. *
  73178. * Execute PCF on a 5*5 kernel improving a lot the shadow aliasing artifacts.
  73179. *
  73180. * Execute PCSS with 32 taps blocker search and 64 taps PCF.
  73181. */
  73182. ShadowGenerator.QUALITY_HIGH = 0;
  73183. /**
  73184. * Reserved for PCF and PCSS
  73185. * Good tradeoff for quality/perf cross devices
  73186. *
  73187. * Execute PCF on a 3*3 kernel.
  73188. *
  73189. * Execute PCSS with 16 taps blocker search and 32 taps PCF.
  73190. */
  73191. ShadowGenerator.QUALITY_MEDIUM = 1;
  73192. /**
  73193. * Reserved for PCF and PCSS
  73194. * The lowest quality but the fastest.
  73195. *
  73196. * Execute PCF on a 1*1 kernel.
  73197. *
  73198. * Execute PCSS with 16 taps blocker search and 16 taps PCF.
  73199. */
  73200. ShadowGenerator.QUALITY_LOW = 2;
  73201. return ShadowGenerator;
  73202. }());
  73203. BABYLON.ShadowGenerator = ShadowGenerator;
  73204. })(BABYLON || (BABYLON = {}));
  73205. //# sourceMappingURL=babylon.shadowGenerator.js.map
  73206. var BABYLON;
  73207. (function (BABYLON) {
  73208. // Adds the parser to the scene parsers.
  73209. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_SHADOWGENERATOR, function (parsedData, scene, container, rootUrl) {
  73210. // Shadows
  73211. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  73212. for (var index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  73213. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  73214. BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  73215. // SG would be available on their associated lights
  73216. }
  73217. }
  73218. });
  73219. /**
  73220. * Defines the shadow generator component responsible to manage any shadow generators
  73221. * in a given scene.
  73222. */
  73223. var ShadowGeneratorSceneComponent = /** @class */ (function () {
  73224. /**
  73225. * Creates a new instance of the component for the given scene
  73226. * @param scene Defines the scene to register the component in
  73227. */
  73228. function ShadowGeneratorSceneComponent(scene) {
  73229. /**
  73230. * The component name helpfull to identify the component in the list of scene components.
  73231. */
  73232. this.name = BABYLON.SceneComponentConstants.NAME_SHADOWGENERATOR;
  73233. this.scene = scene;
  73234. }
  73235. /**
  73236. * Registers the component in a given scene
  73237. */
  73238. ShadowGeneratorSceneComponent.prototype.register = function () {
  73239. this.scene._gatherRenderTargetsStage.registerStep(BABYLON.SceneComponentConstants.STEP_GATHERRENDERTARGETS_SHADOWGENERATOR, this, this._gatherRenderTargets);
  73240. };
  73241. /**
  73242. * Rebuilds the elements related to this component in case of
  73243. * context lost for instance.
  73244. */
  73245. ShadowGeneratorSceneComponent.prototype.rebuild = function () {
  73246. // Nothing To Do Here.
  73247. };
  73248. /**
  73249. * Serializes the component data to the specified json object
  73250. * @param serializationObject The object to serialize to
  73251. */
  73252. ShadowGeneratorSceneComponent.prototype.serialize = function (serializationObject) {
  73253. // Shadows
  73254. serializationObject.shadowGenerators = [];
  73255. var lights = this.scene.lights;
  73256. for (var _i = 0, lights_1 = lights; _i < lights_1.length; _i++) {
  73257. var light = lights_1[_i];
  73258. var shadowGenerator = light.getShadowGenerator();
  73259. if (shadowGenerator) {
  73260. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  73261. }
  73262. }
  73263. };
  73264. /**
  73265. * Adds all the element from the container to the scene
  73266. * @param container the container holding the elements
  73267. */
  73268. ShadowGeneratorSceneComponent.prototype.addFromContainer = function (container) {
  73269. // Nothing To Do Here. (directly attached to a light)
  73270. };
  73271. /**
  73272. * Removes all the elements in the container from the scene
  73273. * @param container contains the elements to remove
  73274. */
  73275. ShadowGeneratorSceneComponent.prototype.removeFromContainer = function (container) {
  73276. // Nothing To Do Here. (directly attached to a light)
  73277. };
  73278. /**
  73279. * Rebuilds the elements related to this component in case of
  73280. * context lost for instance.
  73281. */
  73282. ShadowGeneratorSceneComponent.prototype.dispose = function () {
  73283. // Nothing To Do Here.
  73284. };
  73285. ShadowGeneratorSceneComponent.prototype._gatherRenderTargets = function (renderTargets) {
  73286. // Shadows
  73287. var scene = this.scene;
  73288. if (this.scene.shadowsEnabled) {
  73289. for (var lightIndex = 0; lightIndex < scene.lights.length; lightIndex++) {
  73290. var light = scene.lights[lightIndex];
  73291. var shadowGenerator = light.getShadowGenerator();
  73292. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  73293. var shadowMap = (shadowGenerator.getShadowMap());
  73294. if (scene.textures.indexOf(shadowMap) !== -1) {
  73295. renderTargets.push(shadowMap);
  73296. }
  73297. }
  73298. }
  73299. }
  73300. };
  73301. return ShadowGeneratorSceneComponent;
  73302. }());
  73303. BABYLON.ShadowGeneratorSceneComponent = ShadowGeneratorSceneComponent;
  73304. })(BABYLON || (BABYLON = {}));
  73305. //# sourceMappingURL=babylon.shadowGeneratorSceneComponent.js.map
  73306. var BABYLON;
  73307. (function (BABYLON) {
  73308. var DefaultLoadingScreen = /** @class */ (function () {
  73309. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  73310. if (_loadingText === void 0) { _loadingText = ""; }
  73311. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  73312. var _this = this;
  73313. this._renderingCanvas = _renderingCanvas;
  73314. this._loadingText = _loadingText;
  73315. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  73316. // Resize
  73317. this._resizeLoadingUI = function () {
  73318. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  73319. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  73320. if (!_this._loadingDiv) {
  73321. return;
  73322. }
  73323. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  73324. _this._loadingDiv.style.left = canvasRect.left + "px";
  73325. _this._loadingDiv.style.top = canvasRect.top + "px";
  73326. _this._loadingDiv.style.width = canvasRect.width + "px";
  73327. _this._loadingDiv.style.height = canvasRect.height + "px";
  73328. };
  73329. }
  73330. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  73331. if (this._loadingDiv) {
  73332. // Do not add a loading screen if there is already one
  73333. return;
  73334. }
  73335. this._loadingDiv = document.createElement("div");
  73336. this._loadingDiv.id = "babylonjsLoadingDiv";
  73337. this._loadingDiv.style.opacity = "0";
  73338. this._loadingDiv.style.transition = "opacity 1.5s ease";
  73339. this._loadingDiv.style.pointerEvents = "none";
  73340. // Loading text
  73341. this._loadingTextDiv = document.createElement("div");
  73342. this._loadingTextDiv.style.position = "absolute";
  73343. this._loadingTextDiv.style.left = "0";
  73344. this._loadingTextDiv.style.top = "50%";
  73345. this._loadingTextDiv.style.marginTop = "80px";
  73346. this._loadingTextDiv.style.width = "100%";
  73347. this._loadingTextDiv.style.height = "20px";
  73348. this._loadingTextDiv.style.fontFamily = "Arial";
  73349. this._loadingTextDiv.style.fontSize = "14px";
  73350. this._loadingTextDiv.style.color = "white";
  73351. this._loadingTextDiv.style.textAlign = "center";
  73352. this._loadingTextDiv.innerHTML = "Loading";
  73353. this._loadingDiv.appendChild(this._loadingTextDiv);
  73354. //set the predefined text
  73355. this._loadingTextDiv.innerHTML = this._loadingText;
  73356. // Generating keyframes
  73357. var style = document.createElement('style');
  73358. style.type = 'text/css';
  73359. 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 }";
  73360. style.innerHTML = keyFrames;
  73361. document.getElementsByTagName('head')[0].appendChild(style);
  73362. // Loading img
  73363. var imgBack = new Image();
  73364. 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";
  73365. imgBack.style.position = "absolute";
  73366. imgBack.style.left = "50%";
  73367. imgBack.style.top = "50%";
  73368. imgBack.style.marginLeft = "-60px";
  73369. imgBack.style.marginTop = "-60px";
  73370. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  73371. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  73372. imgBack.style.transformOrigin = "50% 50%";
  73373. imgBack.style.webkitTransformOrigin = "50% 50%";
  73374. this._loadingDiv.appendChild(imgBack);
  73375. this._resizeLoadingUI();
  73376. window.addEventListener("resize", this._resizeLoadingUI);
  73377. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  73378. document.body.appendChild(this._loadingDiv);
  73379. this._loadingDiv.style.opacity = "1";
  73380. };
  73381. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  73382. var _this = this;
  73383. if (!this._loadingDiv) {
  73384. return;
  73385. }
  73386. var onTransitionEnd = function () {
  73387. if (!_this._loadingDiv) {
  73388. return;
  73389. }
  73390. document.body.removeChild(_this._loadingDiv);
  73391. window.removeEventListener("resize", _this._resizeLoadingUI);
  73392. _this._loadingDiv = null;
  73393. };
  73394. this._loadingDiv.style.opacity = "0";
  73395. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  73396. };
  73397. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  73398. set: function (text) {
  73399. this._loadingText = text;
  73400. if (this._loadingTextDiv) {
  73401. this._loadingTextDiv.innerHTML = this._loadingText;
  73402. }
  73403. },
  73404. enumerable: true,
  73405. configurable: true
  73406. });
  73407. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  73408. get: function () {
  73409. return this._loadingDivBackgroundColor;
  73410. },
  73411. set: function (color) {
  73412. this._loadingDivBackgroundColor = color;
  73413. if (!this._loadingDiv) {
  73414. return;
  73415. }
  73416. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  73417. },
  73418. enumerable: true,
  73419. configurable: true
  73420. });
  73421. return DefaultLoadingScreen;
  73422. }());
  73423. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  73424. })(BABYLON || (BABYLON = {}));
  73425. //# sourceMappingURL=babylon.loadingScreen.js.map
  73426. var BABYLON;
  73427. (function (BABYLON) {
  73428. var SceneLoaderProgressEvent = /** @class */ (function () {
  73429. function SceneLoaderProgressEvent(lengthComputable, loaded, total) {
  73430. this.lengthComputable = lengthComputable;
  73431. this.loaded = loaded;
  73432. this.total = total;
  73433. }
  73434. SceneLoaderProgressEvent.FromProgressEvent = function (event) {
  73435. return new SceneLoaderProgressEvent(event.lengthComputable, event.loaded, event.total);
  73436. };
  73437. return SceneLoaderProgressEvent;
  73438. }());
  73439. BABYLON.SceneLoaderProgressEvent = SceneLoaderProgressEvent;
  73440. var SceneLoader = /** @class */ (function () {
  73441. function SceneLoader() {
  73442. }
  73443. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  73444. get: function () {
  73445. return 0;
  73446. },
  73447. enumerable: true,
  73448. configurable: true
  73449. });
  73450. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  73451. get: function () {
  73452. return 1;
  73453. },
  73454. enumerable: true,
  73455. configurable: true
  73456. });
  73457. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  73458. get: function () {
  73459. return 2;
  73460. },
  73461. enumerable: true,
  73462. configurable: true
  73463. });
  73464. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  73465. get: function () {
  73466. return 3;
  73467. },
  73468. enumerable: true,
  73469. configurable: true
  73470. });
  73471. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  73472. get: function () {
  73473. return SceneLoader._ForceFullSceneLoadingForIncremental;
  73474. },
  73475. set: function (value) {
  73476. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  73477. },
  73478. enumerable: true,
  73479. configurable: true
  73480. });
  73481. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  73482. get: function () {
  73483. return SceneLoader._ShowLoadingScreen;
  73484. },
  73485. set: function (value) {
  73486. SceneLoader._ShowLoadingScreen = value;
  73487. },
  73488. enumerable: true,
  73489. configurable: true
  73490. });
  73491. Object.defineProperty(SceneLoader, "loggingLevel", {
  73492. get: function () {
  73493. return SceneLoader._loggingLevel;
  73494. },
  73495. set: function (value) {
  73496. SceneLoader._loggingLevel = value;
  73497. },
  73498. enumerable: true,
  73499. configurable: true
  73500. });
  73501. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  73502. get: function () {
  73503. return SceneLoader._CleanBoneMatrixWeights;
  73504. },
  73505. set: function (value) {
  73506. SceneLoader._CleanBoneMatrixWeights = value;
  73507. },
  73508. enumerable: true,
  73509. configurable: true
  73510. });
  73511. SceneLoader._getDefaultPlugin = function () {
  73512. return SceneLoader._registeredPlugins[".babylon"];
  73513. };
  73514. SceneLoader._getPluginForExtension = function (extension) {
  73515. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  73516. if (registeredPlugin) {
  73517. return registeredPlugin;
  73518. }
  73519. 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");
  73520. return SceneLoader._getDefaultPlugin();
  73521. };
  73522. SceneLoader._getPluginForDirectLoad = function (data) {
  73523. for (var extension in SceneLoader._registeredPlugins) {
  73524. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  73525. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  73526. return SceneLoader._registeredPlugins[extension];
  73527. }
  73528. }
  73529. return SceneLoader._getDefaultPlugin();
  73530. };
  73531. SceneLoader._getPluginForFilename = function (sceneFilename) {
  73532. var queryStringPosition = sceneFilename.indexOf("?");
  73533. if (queryStringPosition !== -1) {
  73534. sceneFilename = sceneFilename.substring(0, queryStringPosition);
  73535. }
  73536. var dotPosition = sceneFilename.lastIndexOf(".");
  73537. var extension = sceneFilename.substring(dotPosition, sceneFilename.length).toLowerCase();
  73538. return SceneLoader._getPluginForExtension(extension);
  73539. };
  73540. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  73541. SceneLoader._getDirectLoad = function (sceneFilename) {
  73542. if (sceneFilename.substr(0, 5) === "data:") {
  73543. return sceneFilename.substr(5);
  73544. }
  73545. return null;
  73546. };
  73547. SceneLoader._loadData = function (fileInfo, scene, onSuccess, onProgress, onError, onDispose, pluginExtension) {
  73548. var directLoad = SceneLoader._getDirectLoad(fileInfo.name);
  73549. var registeredPlugin = pluginExtension ? SceneLoader._getPluginForExtension(pluginExtension) : (directLoad ? SceneLoader._getPluginForDirectLoad(fileInfo.name) : SceneLoader._getPluginForFilename(fileInfo.name));
  73550. var plugin;
  73551. if (registeredPlugin.plugin.createPlugin) {
  73552. plugin = registeredPlugin.plugin.createPlugin();
  73553. }
  73554. else {
  73555. plugin = registeredPlugin.plugin;
  73556. }
  73557. var useArrayBuffer = registeredPlugin.isBinary;
  73558. var database;
  73559. SceneLoader.OnPluginActivatedObservable.notifyObservers(plugin);
  73560. var dataCallback = function (data, responseURL) {
  73561. if (scene.isDisposed) {
  73562. onError("Scene has been disposed");
  73563. return;
  73564. }
  73565. scene.database = database;
  73566. onSuccess(plugin, data, responseURL);
  73567. };
  73568. var request = null;
  73569. var pluginDisposed = false;
  73570. var onDisposeObservable = plugin.onDisposeObservable;
  73571. if (onDisposeObservable) {
  73572. onDisposeObservable.add(function () {
  73573. pluginDisposed = true;
  73574. if (request) {
  73575. request.abort();
  73576. request = null;
  73577. }
  73578. onDispose();
  73579. });
  73580. }
  73581. var manifestChecked = function () {
  73582. if (pluginDisposed) {
  73583. return;
  73584. }
  73585. request = BABYLON.Tools.LoadFile(fileInfo.url, dataCallback, onProgress ? function (event) {
  73586. onProgress(SceneLoaderProgressEvent.FromProgressEvent(event));
  73587. } : undefined, database, useArrayBuffer, function (request, exception) {
  73588. onError("Failed to load scene." + (exception ? " " + exception.message : ""), exception);
  73589. });
  73590. };
  73591. if (directLoad) {
  73592. dataCallback(directLoad);
  73593. return plugin;
  73594. }
  73595. if (fileInfo.rootUrl.indexOf("file:") === -1) {
  73596. var engine = scene.getEngine();
  73597. var canUseOfflineSupport = engine.enableOfflineSupport;
  73598. if (canUseOfflineSupport) {
  73599. // Also check for exceptions
  73600. var exceptionFound = false;
  73601. for (var _i = 0, _a = scene.disableOfflineSupportExceptionRules; _i < _a.length; _i++) {
  73602. var regex = _a[_i];
  73603. if (regex.test(fileInfo.url)) {
  73604. exceptionFound = true;
  73605. break;
  73606. }
  73607. }
  73608. canUseOfflineSupport = !exceptionFound;
  73609. }
  73610. if (canUseOfflineSupport) {
  73611. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  73612. database = new BABYLON.Database(fileInfo.url, manifestChecked, engine.disableManifestCheck);
  73613. }
  73614. else {
  73615. manifestChecked();
  73616. }
  73617. }
  73618. // Loading file from disk via input file or drag'n'drop
  73619. else {
  73620. var file = BABYLON.FilesInput.FilesToLoad[fileInfo.name.toLowerCase()];
  73621. if (file) {
  73622. request = BABYLON.Tools.ReadFile(file, dataCallback, onProgress, useArrayBuffer);
  73623. }
  73624. else {
  73625. onError("Unable to find file named " + fileInfo.name);
  73626. }
  73627. }
  73628. return plugin;
  73629. };
  73630. SceneLoader._getFileInfo = function (rootUrl, sceneFilename) {
  73631. var url;
  73632. var name;
  73633. if (!sceneFilename) {
  73634. url = rootUrl;
  73635. name = BABYLON.Tools.GetFilename(rootUrl);
  73636. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl);
  73637. }
  73638. else {
  73639. if (sceneFilename.substr(0, 1) === "/") {
  73640. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  73641. return null;
  73642. }
  73643. url = rootUrl + sceneFilename;
  73644. name = sceneFilename;
  73645. }
  73646. ;
  73647. return {
  73648. url: url,
  73649. rootUrl: rootUrl,
  73650. name: name
  73651. };
  73652. };
  73653. // Public functions
  73654. SceneLoader.GetPluginForExtension = function (extension) {
  73655. return SceneLoader._getPluginForExtension(extension).plugin;
  73656. };
  73657. SceneLoader.IsPluginForExtensionAvailable = function (extension) {
  73658. return !!SceneLoader._registeredPlugins[extension];
  73659. };
  73660. SceneLoader.RegisterPlugin = function (plugin) {
  73661. if (typeof plugin.extensions === "string") {
  73662. var extension = plugin.extensions;
  73663. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  73664. plugin: plugin,
  73665. isBinary: false
  73666. };
  73667. }
  73668. else {
  73669. var extensions = plugin.extensions;
  73670. Object.keys(extensions).forEach(function (extension) {
  73671. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  73672. plugin: plugin,
  73673. isBinary: extensions[extension].isBinary
  73674. };
  73675. });
  73676. }
  73677. };
  73678. /**
  73679. * Import meshes into a scene
  73680. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  73681. * @param rootUrl a string that defines the root url for the scene and resources or the concatenation of rootURL and filename (e.g. http://example.com/test.glb)
  73682. * @param sceneFilename a string that defines the name of the scene file or starts with "data:" following by the stringified version of the scene (default: empty string)
  73683. * @param scene the instance of BABYLON.Scene to append to
  73684. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  73685. * @param onProgress a callback with a progress event for each file being loaded
  73686. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  73687. * @param pluginExtension the extension used to determine the plugin
  73688. * @returns The loaded plugin
  73689. */
  73690. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  73691. if (sceneFilename === void 0) { sceneFilename = ""; }
  73692. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  73693. if (onSuccess === void 0) { onSuccess = null; }
  73694. if (onProgress === void 0) { onProgress = null; }
  73695. if (onError === void 0) { onError = null; }
  73696. if (pluginExtension === void 0) { pluginExtension = null; }
  73697. if (!scene) {
  73698. BABYLON.Tools.Error("No scene available to import mesh to");
  73699. return null;
  73700. }
  73701. var fileInfo = SceneLoader._getFileInfo(rootUrl, sceneFilename);
  73702. if (!fileInfo) {
  73703. return null;
  73704. }
  73705. var loadingToken = {};
  73706. scene._addPendingData(loadingToken);
  73707. var disposeHandler = function () {
  73708. scene._removePendingData(loadingToken);
  73709. };
  73710. var errorHandler = function (message, exception) {
  73711. var errorMessage = "Unable to import meshes from " + fileInfo.url + ": " + message;
  73712. if (onError) {
  73713. onError(scene, errorMessage, exception);
  73714. }
  73715. else {
  73716. BABYLON.Tools.Error(errorMessage);
  73717. // should the exception be thrown?
  73718. }
  73719. disposeHandler();
  73720. };
  73721. var progressHandler = onProgress ? function (event) {
  73722. try {
  73723. onProgress(event);
  73724. }
  73725. catch (e) {
  73726. errorHandler("Error in onProgress callback", e);
  73727. }
  73728. } : undefined;
  73729. var successHandler = function (meshes, particleSystems, skeletons, animationGroups) {
  73730. scene.importedMeshesFiles.push(fileInfo.url);
  73731. if (onSuccess) {
  73732. try {
  73733. onSuccess(meshes, particleSystems, skeletons, animationGroups);
  73734. }
  73735. catch (e) {
  73736. errorHandler("Error in onSuccess callback", e);
  73737. }
  73738. }
  73739. scene._removePendingData(loadingToken);
  73740. };
  73741. return SceneLoader._loadData(fileInfo, scene, function (plugin, data, responseURL) {
  73742. if (plugin.rewriteRootURL) {
  73743. fileInfo.rootUrl = plugin.rewriteRootURL(fileInfo.rootUrl, responseURL);
  73744. }
  73745. if (plugin.importMesh) {
  73746. var syncedPlugin = plugin;
  73747. var meshes = new Array();
  73748. var particleSystems = new Array();
  73749. var skeletons = new Array();
  73750. if (!syncedPlugin.importMesh(meshNames, scene, data, fileInfo.rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  73751. return;
  73752. }
  73753. scene.loadingPluginName = plugin.name;
  73754. successHandler(meshes, particleSystems, skeletons, []);
  73755. }
  73756. else {
  73757. var asyncedPlugin = plugin;
  73758. asyncedPlugin.importMeshAsync(meshNames, scene, data, fileInfo.rootUrl, progressHandler, fileInfo.name).then(function (result) {
  73759. scene.loadingPluginName = plugin.name;
  73760. successHandler(result.meshes, result.particleSystems, result.skeletons, result.animationGroups);
  73761. }).catch(function (error) {
  73762. errorHandler(error.message, error);
  73763. });
  73764. }
  73765. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  73766. };
  73767. /**
  73768. * Import meshes into a scene
  73769. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  73770. * @param rootUrl a string that defines the root url for the scene and resources or the concatenation of rootURL and filename (e.g. http://example.com/test.glb)
  73771. * @param sceneFilename a string that defines the name of the scene file or starts with "data:" following by the stringified version of the scene (default: empty string)
  73772. * @param scene the instance of BABYLON.Scene to append to
  73773. * @param onProgress a callback with a progress event for each file being loaded
  73774. * @param pluginExtension the extension used to determine the plugin
  73775. * @returns The loaded list of imported meshes, particle systems, skeletons, and animation groups
  73776. */
  73777. SceneLoader.ImportMeshAsync = function (meshNames, rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  73778. if (sceneFilename === void 0) { sceneFilename = ""; }
  73779. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  73780. if (onProgress === void 0) { onProgress = null; }
  73781. if (pluginExtension === void 0) { pluginExtension = null; }
  73782. return new Promise(function (resolve, reject) {
  73783. SceneLoader.ImportMesh(meshNames, rootUrl, sceneFilename, scene, function (meshes, particleSystems, skeletons, animationGroups) {
  73784. resolve({
  73785. meshes: meshes,
  73786. particleSystems: particleSystems,
  73787. skeletons: skeletons,
  73788. animationGroups: animationGroups
  73789. });
  73790. }, onProgress, function (scene, message, exception) {
  73791. reject(exception || new Error(message));
  73792. }, pluginExtension);
  73793. });
  73794. };
  73795. /**
  73796. * Load a scene
  73797. * @param rootUrl a string that defines the root url for the scene and resources or the concatenation of rootURL and filename (e.g. http://example.com/test.glb)
  73798. * @param sceneFilename a string that defines the name of the scene file or starts with "data:" following by the stringified version of the scene (default: empty string)
  73799. * @param engine is the instance of BABYLON.Engine to use to create the scene
  73800. * @param onSuccess a callback with the scene when import succeeds
  73801. * @param onProgress a callback with a progress event for each file being loaded
  73802. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  73803. * @param pluginExtension the extension used to determine the plugin
  73804. * @returns The loaded plugin
  73805. */
  73806. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError, pluginExtension) {
  73807. if (onSuccess === void 0) { onSuccess = null; }
  73808. if (onProgress === void 0) { onProgress = null; }
  73809. if (onError === void 0) { onError = null; }
  73810. if (pluginExtension === void 0) { pluginExtension = null; }
  73811. return SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError, pluginExtension);
  73812. };
  73813. /**
  73814. * Load a scene
  73815. * @param rootUrl a string that defines the root url for the scene and resources or the concatenation of rootURL and filename (e.g. http://example.com/test.glb)
  73816. * @param sceneFilename a string that defines the name of the scene file or starts with "data:" following by the stringified version of the scene (default: empty string)
  73817. * @param engine is the instance of BABYLON.Engine to use to create the scene
  73818. * @param onProgress a callback with a progress event for each file being loaded
  73819. * @param pluginExtension the extension used to determine the plugin
  73820. * @returns The loaded scene
  73821. */
  73822. SceneLoader.LoadAsync = function (rootUrl, sceneFilename, engine, onProgress, pluginExtension) {
  73823. if (onProgress === void 0) { onProgress = null; }
  73824. if (pluginExtension === void 0) { pluginExtension = null; }
  73825. return new Promise(function (resolve, reject) {
  73826. SceneLoader.Load(rootUrl, sceneFilename, engine, function (scene) {
  73827. resolve(scene);
  73828. }, onProgress, function (scene, message, exception) {
  73829. reject(exception || new Error(message));
  73830. }, pluginExtension);
  73831. });
  73832. };
  73833. /**
  73834. * Append a scene
  73835. * @param rootUrl a string that defines the root url for the scene and resources or the concatenation of rootURL and filename (e.g. http://example.com/test.glb)
  73836. * @param sceneFilename a string that defines the name of the scene file or starts with "data:" following by the stringified version of the scene (default: empty string)
  73837. * @param scene is the instance of BABYLON.Scene to append to
  73838. * @param onSuccess a callback with the scene when import succeeds
  73839. * @param onProgress a callback with a progress event for each file being loaded
  73840. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  73841. * @param pluginExtension the extension used to determine the plugin
  73842. * @returns The loaded plugin
  73843. */
  73844. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  73845. if (sceneFilename === void 0) { sceneFilename = ""; }
  73846. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  73847. if (onSuccess === void 0) { onSuccess = null; }
  73848. if (onProgress === void 0) { onProgress = null; }
  73849. if (onError === void 0) { onError = null; }
  73850. if (pluginExtension === void 0) { pluginExtension = null; }
  73851. if (!scene) {
  73852. BABYLON.Tools.Error("No scene available to append to");
  73853. return null;
  73854. }
  73855. var fileInfo = SceneLoader._getFileInfo(rootUrl, sceneFilename);
  73856. if (!fileInfo) {
  73857. return null;
  73858. }
  73859. if (SceneLoader.ShowLoadingScreen) {
  73860. scene.getEngine().displayLoadingUI();
  73861. }
  73862. var loadingToken = {};
  73863. scene._addPendingData(loadingToken);
  73864. var disposeHandler = function () {
  73865. scene._removePendingData(loadingToken);
  73866. scene.getEngine().hideLoadingUI();
  73867. };
  73868. var errorHandler = function (message, exception) {
  73869. var errorMessage = "Unable to load from " + fileInfo.url + (message ? ": " + message : "");
  73870. if (onError) {
  73871. onError(scene, errorMessage, exception);
  73872. }
  73873. else {
  73874. BABYLON.Tools.Error(errorMessage);
  73875. // should the exception be thrown?
  73876. }
  73877. disposeHandler();
  73878. };
  73879. var progressHandler = onProgress ? function (event) {
  73880. try {
  73881. onProgress(event);
  73882. }
  73883. catch (e) {
  73884. errorHandler("Error in onProgress callback", e);
  73885. }
  73886. } : undefined;
  73887. var successHandler = function () {
  73888. if (onSuccess) {
  73889. try {
  73890. onSuccess(scene);
  73891. }
  73892. catch (e) {
  73893. errorHandler("Error in onSuccess callback", e);
  73894. }
  73895. }
  73896. scene._removePendingData(loadingToken);
  73897. };
  73898. return SceneLoader._loadData(fileInfo, scene, function (plugin, data, responseURL) {
  73899. if (plugin.load) {
  73900. var syncedPlugin = plugin;
  73901. if (!syncedPlugin.load(scene, data, fileInfo.rootUrl, errorHandler)) {
  73902. return;
  73903. }
  73904. scene.loadingPluginName = plugin.name;
  73905. successHandler();
  73906. }
  73907. else {
  73908. var asyncedPlugin = plugin;
  73909. asyncedPlugin.loadAsync(scene, data, fileInfo.rootUrl, progressHandler, fileInfo.name).then(function () {
  73910. scene.loadingPluginName = plugin.name;
  73911. successHandler();
  73912. }).catch(function (error) {
  73913. errorHandler(error.message, error);
  73914. });
  73915. }
  73916. if (SceneLoader.ShowLoadingScreen) {
  73917. scene.executeWhenReady(function () {
  73918. scene.getEngine().hideLoadingUI();
  73919. });
  73920. }
  73921. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  73922. };
  73923. /**
  73924. * Append a scene
  73925. * @param rootUrl a string that defines the root url for the scene and resources or the concatenation of rootURL and filename (e.g. http://example.com/test.glb)
  73926. * @param sceneFilename a string that defines the name of the scene file or starts with "data:" following by the stringified version of the scene (default: empty string)
  73927. * @param scene is the instance of BABYLON.Scene to append to
  73928. * @param onProgress a callback with a progress event for each file being loaded
  73929. * @param pluginExtension the extension used to determine the plugin
  73930. * @returns The given scene
  73931. */
  73932. SceneLoader.AppendAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  73933. if (sceneFilename === void 0) { sceneFilename = ""; }
  73934. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  73935. if (onProgress === void 0) { onProgress = null; }
  73936. if (pluginExtension === void 0) { pluginExtension = null; }
  73937. return new Promise(function (resolve, reject) {
  73938. SceneLoader.Append(rootUrl, sceneFilename, scene, function (scene) {
  73939. resolve(scene);
  73940. }, onProgress, function (scene, message, exception) {
  73941. reject(exception || new Error(message));
  73942. }, pluginExtension);
  73943. });
  73944. };
  73945. /**
  73946. * Load a scene into an asset container
  73947. * @param rootUrl a string that defines the root url for the scene and resources or the concatenation of rootURL and filename (e.g. http://example.com/test.glb)
  73948. * @param sceneFilename a string that defines the name of the scene file or starts with "data:" following by the stringified version of the scene (default: empty string)
  73949. * @param scene is the instance of BABYLON.Scene to append to (default: last created scene)
  73950. * @param onSuccess a callback with the scene when import succeeds
  73951. * @param onProgress a callback with a progress event for each file being loaded
  73952. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  73953. * @param pluginExtension the extension used to determine the plugin
  73954. * @returns The loaded plugin
  73955. */
  73956. SceneLoader.LoadAssetContainer = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  73957. if (sceneFilename === void 0) { sceneFilename = ""; }
  73958. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  73959. if (onSuccess === void 0) { onSuccess = null; }
  73960. if (onProgress === void 0) { onProgress = null; }
  73961. if (onError === void 0) { onError = null; }
  73962. if (pluginExtension === void 0) { pluginExtension = null; }
  73963. if (!scene) {
  73964. BABYLON.Tools.Error("No scene available to load asset container to");
  73965. return null;
  73966. }
  73967. var fileInfo = SceneLoader._getFileInfo(rootUrl, sceneFilename);
  73968. if (!fileInfo) {
  73969. return null;
  73970. }
  73971. var loadingToken = {};
  73972. scene._addPendingData(loadingToken);
  73973. var disposeHandler = function () {
  73974. scene._removePendingData(loadingToken);
  73975. };
  73976. var errorHandler = function (message, exception) {
  73977. var errorMessage = "Unable to load assets from " + fileInfo.url + (message ? ": " + message : "");
  73978. if (onError) {
  73979. onError(scene, errorMessage, exception);
  73980. }
  73981. else {
  73982. BABYLON.Tools.Error(errorMessage);
  73983. // should the exception be thrown?
  73984. }
  73985. disposeHandler();
  73986. };
  73987. var progressHandler = onProgress ? function (event) {
  73988. try {
  73989. onProgress(event);
  73990. }
  73991. catch (e) {
  73992. errorHandler("Error in onProgress callback", e);
  73993. }
  73994. } : undefined;
  73995. var successHandler = function (assets) {
  73996. if (onSuccess) {
  73997. try {
  73998. onSuccess(assets);
  73999. }
  74000. catch (e) {
  74001. errorHandler("Error in onSuccess callback", e);
  74002. }
  74003. }
  74004. scene._removePendingData(loadingToken);
  74005. };
  74006. return SceneLoader._loadData(fileInfo, scene, function (plugin, data, responseURL) {
  74007. if (plugin.loadAssetContainer) {
  74008. var syncedPlugin = plugin;
  74009. var assetContainer = syncedPlugin.loadAssetContainer(scene, data, fileInfo.rootUrl, errorHandler);
  74010. if (!assetContainer) {
  74011. return;
  74012. }
  74013. scene.loadingPluginName = plugin.name;
  74014. successHandler(assetContainer);
  74015. }
  74016. else if (plugin.loadAssetContainerAsync) {
  74017. var asyncedPlugin = plugin;
  74018. asyncedPlugin.loadAssetContainerAsync(scene, data, fileInfo.rootUrl, progressHandler, fileInfo.name).then(function (assetContainer) {
  74019. scene.loadingPluginName = plugin.name;
  74020. successHandler(assetContainer);
  74021. }).catch(function (error) {
  74022. errorHandler(error.message, error);
  74023. });
  74024. }
  74025. else {
  74026. errorHandler("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.");
  74027. }
  74028. if (SceneLoader.ShowLoadingScreen) {
  74029. scene.executeWhenReady(function () {
  74030. scene.getEngine().hideLoadingUI();
  74031. });
  74032. }
  74033. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  74034. };
  74035. /**
  74036. * Load a scene into an asset container
  74037. * @param rootUrl a string that defines the root url for the scene and resources or the concatenation of rootURL and filename (e.g. http://example.com/test.glb)
  74038. * @param sceneFilename a string that defines the name of the scene file or starts with "data:" following by the stringified version of the scene (default: empty string)
  74039. * @param scene is the instance of BABYLON.Scene to append to
  74040. * @param onProgress a callback with a progress event for each file being loaded
  74041. * @param pluginExtension the extension used to determine the plugin
  74042. * @returns The loaded asset container
  74043. */
  74044. SceneLoader.LoadAssetContainerAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  74045. if (sceneFilename === void 0) { sceneFilename = ""; }
  74046. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  74047. if (onProgress === void 0) { onProgress = null; }
  74048. if (pluginExtension === void 0) { pluginExtension = null; }
  74049. return new Promise(function (resolve, reject) {
  74050. SceneLoader.LoadAssetContainer(rootUrl, sceneFilename, scene, function (assetContainer) {
  74051. resolve(assetContainer);
  74052. }, onProgress, function (scene, message, exception) {
  74053. reject(exception || new Error(message));
  74054. }, pluginExtension);
  74055. });
  74056. };
  74057. // Flags
  74058. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  74059. SceneLoader._ShowLoadingScreen = true;
  74060. SceneLoader._CleanBoneMatrixWeights = false;
  74061. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  74062. // Members
  74063. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  74064. SceneLoader._registeredPlugins = {};
  74065. return SceneLoader;
  74066. }());
  74067. BABYLON.SceneLoader = SceneLoader;
  74068. ;
  74069. })(BABYLON || (BABYLON = {}));
  74070. //# sourceMappingURL=babylon.sceneLoader.js.map
  74071. var BABYLON;
  74072. (function (BABYLON) {
  74073. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  74074. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  74075. var parsedMaterial = parsedData.materials[index];
  74076. if (parsedMaterial.id === id) {
  74077. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  74078. }
  74079. }
  74080. return null;
  74081. };
  74082. var isDescendantOf = function (mesh, names, hierarchyIds) {
  74083. for (var i in names) {
  74084. if (mesh.name === names[i]) {
  74085. hierarchyIds.push(mesh.id);
  74086. return true;
  74087. }
  74088. }
  74089. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  74090. hierarchyIds.push(mesh.id);
  74091. return true;
  74092. }
  74093. return false;
  74094. };
  74095. var logOperation = function (operation, producer) {
  74096. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  74097. };
  74098. var loadAssetContainer = function (scene, data, rootUrl, onError, addToScene) {
  74099. if (addToScene === void 0) { addToScene = false; }
  74100. var container = new BABYLON.AssetContainer(scene);
  74101. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  74102. // when SceneLoader.debugLogging = true (default), or exception encountered.
  74103. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  74104. // and avoid problems with multiple concurrent .babylon loads.
  74105. var log = "importScene has failed JSON parse";
  74106. try {
  74107. var parsedData = JSON.parse(data);
  74108. log = "";
  74109. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  74110. var index;
  74111. var cache;
  74112. // Lights
  74113. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  74114. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  74115. var parsedLight = parsedData.lights[index];
  74116. var light = BABYLON.Light.Parse(parsedLight, scene);
  74117. if (light) {
  74118. container.lights.push(light);
  74119. log += (index === 0 ? "\n\tLights:" : "");
  74120. log += "\n\t\t" + light.toString(fullDetails);
  74121. }
  74122. }
  74123. }
  74124. // Animations
  74125. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  74126. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  74127. var parsedAnimation = parsedData.animations[index];
  74128. var animation = BABYLON.Animation.Parse(parsedAnimation);
  74129. scene.animations.push(animation);
  74130. container.animations.push(animation);
  74131. log += (index === 0 ? "\n\tAnimations:" : "");
  74132. log += "\n\t\t" + animation.toString(fullDetails);
  74133. }
  74134. }
  74135. // Materials
  74136. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  74137. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  74138. var parsedMaterial = parsedData.materials[index];
  74139. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  74140. container.materials.push(mat);
  74141. log += (index === 0 ? "\n\tMaterials:" : "");
  74142. log += "\n\t\t" + mat.toString(fullDetails);
  74143. }
  74144. }
  74145. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  74146. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  74147. var parsedMultiMaterial = parsedData.multiMaterials[index];
  74148. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  74149. container.multiMaterials.push(mmat);
  74150. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  74151. log += "\n\t\t" + mmat.toString(fullDetails);
  74152. }
  74153. }
  74154. // Morph targets
  74155. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  74156. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  74157. var managerData = _a[_i];
  74158. container.morphTargetManagers.push(BABYLON.MorphTargetManager.Parse(managerData, scene));
  74159. }
  74160. }
  74161. // Skeletons
  74162. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  74163. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  74164. var parsedSkeleton = parsedData.skeletons[index];
  74165. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  74166. container.skeletons.push(skeleton);
  74167. log += (index === 0 ? "\n\tSkeletons:" : "");
  74168. log += "\n\t\t" + skeleton.toString(fullDetails);
  74169. }
  74170. }
  74171. // Geometries
  74172. var geometries = parsedData.geometries;
  74173. if (geometries !== undefined && geometries !== null) {
  74174. var addedGeometry = new Array();
  74175. // Boxes
  74176. var boxes = geometries.boxes;
  74177. if (boxes !== undefined && boxes !== null) {
  74178. for (index = 0, cache = boxes.length; index < cache; index++) {
  74179. var parsedBox = boxes[index];
  74180. addedGeometry.push(BABYLON.BoxGeometry.Parse(parsedBox, scene));
  74181. }
  74182. }
  74183. // Spheres
  74184. var spheres = geometries.spheres;
  74185. if (spheres !== undefined && spheres !== null) {
  74186. for (index = 0, cache = spheres.length; index < cache; index++) {
  74187. var parsedSphere = spheres[index];
  74188. addedGeometry.push(BABYLON.SphereGeometry.Parse(parsedSphere, scene));
  74189. }
  74190. }
  74191. // Cylinders
  74192. var cylinders = geometries.cylinders;
  74193. if (cylinders !== undefined && cylinders !== null) {
  74194. for (index = 0, cache = cylinders.length; index < cache; index++) {
  74195. var parsedCylinder = cylinders[index];
  74196. addedGeometry.push(BABYLON.CylinderGeometry.Parse(parsedCylinder, scene));
  74197. }
  74198. }
  74199. // Toruses
  74200. var toruses = geometries.toruses;
  74201. if (toruses !== undefined && toruses !== null) {
  74202. for (index = 0, cache = toruses.length; index < cache; index++) {
  74203. var parsedTorus = toruses[index];
  74204. addedGeometry.push(BABYLON.TorusGeometry.Parse(parsedTorus, scene));
  74205. }
  74206. }
  74207. // Grounds
  74208. var grounds = geometries.grounds;
  74209. if (grounds !== undefined && grounds !== null) {
  74210. for (index = 0, cache = grounds.length; index < cache; index++) {
  74211. var parsedGround = grounds[index];
  74212. addedGeometry.push(BABYLON.GroundGeometry.Parse(parsedGround, scene));
  74213. }
  74214. }
  74215. // Planes
  74216. var planes = geometries.planes;
  74217. if (planes !== undefined && planes !== null) {
  74218. for (index = 0, cache = planes.length; index < cache; index++) {
  74219. var parsedPlane = planes[index];
  74220. addedGeometry.push(BABYLON.PlaneGeometry.Parse(parsedPlane, scene));
  74221. }
  74222. }
  74223. // TorusKnots
  74224. var torusKnots = geometries.torusKnots;
  74225. if (torusKnots !== undefined && torusKnots !== null) {
  74226. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  74227. var parsedTorusKnot = torusKnots[index];
  74228. addedGeometry.push(BABYLON.TorusKnotGeometry.Parse(parsedTorusKnot, scene));
  74229. }
  74230. }
  74231. // VertexData
  74232. var vertexData = geometries.vertexData;
  74233. if (vertexData !== undefined && vertexData !== null) {
  74234. for (index = 0, cache = vertexData.length; index < cache; index++) {
  74235. var parsedVertexData = vertexData[index];
  74236. addedGeometry.push(BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl));
  74237. }
  74238. }
  74239. addedGeometry.forEach(function (g) {
  74240. if (g) {
  74241. container.geometries.push(g);
  74242. }
  74243. });
  74244. }
  74245. // Transform nodes
  74246. if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) {
  74247. for (index = 0, cache = parsedData.transformNodes.length; index < cache; index++) {
  74248. var parsedTransformNode = parsedData.transformNodes[index];
  74249. var node = BABYLON.TransformNode.Parse(parsedTransformNode, scene, rootUrl);
  74250. container.transformNodes.push(node);
  74251. }
  74252. }
  74253. // Meshes
  74254. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  74255. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  74256. var parsedMesh = parsedData.meshes[index];
  74257. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  74258. container.meshes.push(mesh);
  74259. log += (index === 0 ? "\n\tMeshes:" : "");
  74260. log += "\n\t\t" + mesh.toString(fullDetails);
  74261. }
  74262. }
  74263. // Cameras
  74264. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  74265. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  74266. var parsedCamera = parsedData.cameras[index];
  74267. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  74268. container.cameras.push(camera);
  74269. log += (index === 0 ? "\n\tCameras:" : "");
  74270. log += "\n\t\t" + camera.toString(fullDetails);
  74271. }
  74272. }
  74273. // Animation Groups
  74274. if (parsedData.animationGroups !== undefined && parsedData.animationGroups !== null) {
  74275. for (index = 0, cache = parsedData.animationGroups.length; index < cache; index++) {
  74276. var parsedAnimationGroup = parsedData.animationGroups[index];
  74277. var animationGroup = BABYLON.AnimationGroup.Parse(parsedAnimationGroup, scene);
  74278. container.animationGroups.push(animationGroup);
  74279. log += (index === 0 ? "\n\tAnimationGroups:" : "");
  74280. log += "\n\t\t" + animationGroup.toString(fullDetails);
  74281. }
  74282. }
  74283. // Browsing all the graph to connect the dots
  74284. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  74285. var camera = scene.cameras[index];
  74286. if (camera._waitingParentId) {
  74287. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  74288. camera._waitingParentId = null;
  74289. }
  74290. }
  74291. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  74292. var light_1 = scene.lights[index];
  74293. if (light_1 && light_1._waitingParentId) {
  74294. light_1.parent = scene.getLastEntryByID(light_1._waitingParentId);
  74295. light_1._waitingParentId = null;
  74296. }
  74297. }
  74298. // Connect parents & children and parse actions
  74299. for (index = 0, cache = scene.transformNodes.length; index < cache; index++) {
  74300. var transformNode = scene.transformNodes[index];
  74301. if (transformNode._waitingParentId) {
  74302. transformNode.parent = scene.getLastEntryByID(transformNode._waitingParentId);
  74303. transformNode._waitingParentId = null;
  74304. }
  74305. }
  74306. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  74307. var mesh = scene.meshes[index];
  74308. if (mesh._waitingParentId) {
  74309. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  74310. mesh._waitingParentId = null;
  74311. }
  74312. }
  74313. // freeze world matrix application
  74314. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  74315. var currentMesh = scene.meshes[index];
  74316. if (currentMesh._waitingFreezeWorldMatrix) {
  74317. currentMesh.freezeWorldMatrix();
  74318. currentMesh._waitingFreezeWorldMatrix = null;
  74319. }
  74320. else {
  74321. currentMesh.computeWorldMatrix(true);
  74322. }
  74323. }
  74324. // Lights exclusions / inclusions
  74325. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  74326. var light_2 = scene.lights[index];
  74327. // Excluded check
  74328. if (light_2._excludedMeshesIds.length > 0) {
  74329. for (var excludedIndex = 0; excludedIndex < light_2._excludedMeshesIds.length; excludedIndex++) {
  74330. var excludedMesh = scene.getMeshByID(light_2._excludedMeshesIds[excludedIndex]);
  74331. if (excludedMesh) {
  74332. light_2.excludedMeshes.push(excludedMesh);
  74333. }
  74334. }
  74335. light_2._excludedMeshesIds = [];
  74336. }
  74337. // Included check
  74338. if (light_2._includedOnlyMeshesIds.length > 0) {
  74339. for (var includedOnlyIndex = 0; includedOnlyIndex < light_2._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  74340. var includedOnlyMesh = scene.getMeshByID(light_2._includedOnlyMeshesIds[includedOnlyIndex]);
  74341. if (includedOnlyMesh) {
  74342. light_2.includedOnlyMeshes.push(includedOnlyMesh);
  74343. }
  74344. }
  74345. light_2._includedOnlyMeshesIds = [];
  74346. }
  74347. }
  74348. BABYLON.AbstractScene.Parse(parsedData, scene, container, rootUrl);
  74349. // Actions (scene) Done last as it can access other objects.
  74350. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  74351. var mesh = scene.meshes[index];
  74352. if (mesh._waitingActions) {
  74353. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  74354. mesh._waitingActions = null;
  74355. }
  74356. }
  74357. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  74358. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  74359. }
  74360. if (!addToScene) {
  74361. container.removeAllFromScene();
  74362. }
  74363. }
  74364. catch (err) {
  74365. var msg = logOperation("loadAssets", parsedData ? parsedData.producer : "Unknown") + log;
  74366. if (onError) {
  74367. onError(msg, err);
  74368. }
  74369. else {
  74370. BABYLON.Tools.Log(msg);
  74371. throw err;
  74372. }
  74373. }
  74374. finally {
  74375. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  74376. BABYLON.Tools.Log(logOperation("loadAssets", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  74377. }
  74378. }
  74379. return container;
  74380. };
  74381. BABYLON.SceneLoader.RegisterPlugin({
  74382. name: "babylon.js",
  74383. extensions: ".babylon",
  74384. canDirectLoad: function (data) {
  74385. if (data.indexOf("babylon") !== -1) { // We consider that the producer string is filled
  74386. return true;
  74387. }
  74388. return false;
  74389. },
  74390. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {
  74391. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  74392. // when SceneLoader.debugLogging = true (default), or exception encountered.
  74393. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  74394. // and avoid problems with multiple concurrent .babylon loads.
  74395. var log = "importMesh has failed JSON parse";
  74396. try {
  74397. var parsedData = JSON.parse(data);
  74398. log = "";
  74399. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  74400. if (!meshesNames) {
  74401. meshesNames = null;
  74402. }
  74403. else if (!Array.isArray(meshesNames)) {
  74404. meshesNames = [meshesNames];
  74405. }
  74406. var hierarchyIds = new Array();
  74407. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  74408. var loadedSkeletonsIds = [];
  74409. var loadedMaterialsIds = [];
  74410. var index;
  74411. var cache;
  74412. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  74413. var parsedMesh = parsedData.meshes[index];
  74414. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  74415. if (meshesNames !== null) {
  74416. // Remove found mesh name from list.
  74417. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  74418. }
  74419. //Geometry?
  74420. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  74421. //does the file contain geometries?
  74422. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  74423. //find the correct geometry and add it to the scene
  74424. var found = false;
  74425. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  74426. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  74427. return;
  74428. }
  74429. else {
  74430. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  74431. if (parsedGeometryData.id === parsedMesh.geometryId) {
  74432. switch (geometryType) {
  74433. case "boxes":
  74434. BABYLON.BoxGeometry.Parse(parsedGeometryData, scene);
  74435. break;
  74436. case "spheres":
  74437. BABYLON.SphereGeometry.Parse(parsedGeometryData, scene);
  74438. break;
  74439. case "cylinders":
  74440. BABYLON.CylinderGeometry.Parse(parsedGeometryData, scene);
  74441. break;
  74442. case "toruses":
  74443. BABYLON.TorusGeometry.Parse(parsedGeometryData, scene);
  74444. break;
  74445. case "grounds":
  74446. BABYLON.GroundGeometry.Parse(parsedGeometryData, scene);
  74447. break;
  74448. case "planes":
  74449. BABYLON.PlaneGeometry.Parse(parsedGeometryData, scene);
  74450. break;
  74451. case "torusKnots":
  74452. BABYLON.TorusKnotGeometry.Parse(parsedGeometryData, scene);
  74453. break;
  74454. case "vertexData":
  74455. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  74456. break;
  74457. }
  74458. found = true;
  74459. }
  74460. });
  74461. }
  74462. });
  74463. if (found === false) {
  74464. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  74465. }
  74466. }
  74467. }
  74468. // Material ?
  74469. if (parsedMesh.materialId) {
  74470. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  74471. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  74472. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  74473. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  74474. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  74475. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  74476. var subMatId = parsedMultiMaterial.materials[matIndex];
  74477. loadedMaterialsIds.push(subMatId);
  74478. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  74479. if (mat) {
  74480. log += "\n\tMaterial " + mat.toString(fullDetails);
  74481. }
  74482. }
  74483. loadedMaterialsIds.push(parsedMultiMaterial.id);
  74484. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  74485. if (mmat) {
  74486. materialFound = true;
  74487. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  74488. }
  74489. break;
  74490. }
  74491. }
  74492. }
  74493. if (materialFound === false) {
  74494. loadedMaterialsIds.push(parsedMesh.materialId);
  74495. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  74496. if (!mat) {
  74497. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  74498. }
  74499. else {
  74500. log += "\n\tMaterial " + mat.toString(fullDetails);
  74501. }
  74502. }
  74503. }
  74504. // Skeleton ?
  74505. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  74506. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  74507. if (skeletonAlreadyLoaded === false) {
  74508. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  74509. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  74510. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  74511. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  74512. skeletons.push(skeleton);
  74513. loadedSkeletonsIds.push(parsedSkeleton.id);
  74514. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  74515. }
  74516. }
  74517. }
  74518. }
  74519. // Morph targets ?
  74520. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  74521. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  74522. var managerData = _a[_i];
  74523. BABYLON.MorphTargetManager.Parse(managerData, scene);
  74524. }
  74525. }
  74526. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  74527. meshes.push(mesh);
  74528. log += "\n\tMesh " + mesh.toString(fullDetails);
  74529. }
  74530. }
  74531. // Connecting parents
  74532. var currentMesh;
  74533. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  74534. currentMesh = scene.meshes[index];
  74535. if (currentMesh._waitingParentId) {
  74536. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  74537. currentMesh._waitingParentId = null;
  74538. }
  74539. }
  74540. // freeze and compute world matrix application
  74541. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  74542. currentMesh = scene.meshes[index];
  74543. if (currentMesh._waitingFreezeWorldMatrix) {
  74544. currentMesh.freezeWorldMatrix();
  74545. currentMesh._waitingFreezeWorldMatrix = null;
  74546. }
  74547. else {
  74548. currentMesh.computeWorldMatrix(true);
  74549. }
  74550. }
  74551. }
  74552. // Particles
  74553. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  74554. var parser = BABYLON.AbstractScene.GetIndividualParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM);
  74555. if (parser) {
  74556. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  74557. var parsedParticleSystem = parsedData.particleSystems[index];
  74558. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  74559. particleSystems.push(parser(parsedParticleSystem, scene, rootUrl));
  74560. }
  74561. }
  74562. }
  74563. }
  74564. return true;
  74565. }
  74566. catch (err) {
  74567. var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
  74568. if (onError) {
  74569. onError(msg, err);
  74570. }
  74571. else {
  74572. BABYLON.Tools.Log(msg);
  74573. throw err;
  74574. }
  74575. }
  74576. finally {
  74577. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  74578. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  74579. }
  74580. }
  74581. return false;
  74582. },
  74583. load: function (scene, data, rootUrl, onError) {
  74584. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  74585. // when SceneLoader.debugLogging = true (default), or exception encountered.
  74586. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  74587. // and avoid problems with multiple concurrent .babylon loads.
  74588. var log = "importScene has failed JSON parse";
  74589. try {
  74590. var parsedData = JSON.parse(data);
  74591. log = "";
  74592. // Scene
  74593. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  74594. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  74595. }
  74596. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  74597. scene.autoClear = parsedData.autoClear;
  74598. }
  74599. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  74600. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  74601. }
  74602. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  74603. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  74604. }
  74605. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  74606. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  74607. }
  74608. // Fog
  74609. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  74610. scene.fogMode = parsedData.fogMode;
  74611. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  74612. scene.fogStart = parsedData.fogStart;
  74613. scene.fogEnd = parsedData.fogEnd;
  74614. scene.fogDensity = parsedData.fogDensity;
  74615. log += "\tFog mode for scene: ";
  74616. switch (scene.fogMode) {
  74617. // getters not compiling, so using hardcoded
  74618. case 1:
  74619. log += "exp\n";
  74620. break;
  74621. case 2:
  74622. log += "exp2\n";
  74623. break;
  74624. case 3:
  74625. log += "linear\n";
  74626. break;
  74627. }
  74628. }
  74629. //Physics
  74630. if (parsedData.physicsEnabled) {
  74631. var physicsPlugin;
  74632. if (parsedData.physicsEngine === "cannon") {
  74633. physicsPlugin = new BABYLON.CannonJSPlugin();
  74634. }
  74635. else if (parsedData.physicsEngine === "oimo") {
  74636. physicsPlugin = new BABYLON.OimoJSPlugin();
  74637. }
  74638. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  74639. //else - default engine, which is currently oimo
  74640. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  74641. scene.enablePhysics(physicsGravity, physicsPlugin);
  74642. }
  74643. // Metadata
  74644. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  74645. scene.metadata = parsedData.metadata;
  74646. }
  74647. //collisions, if defined. otherwise, default is true
  74648. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  74649. scene.collisionsEnabled = parsedData.collisionsEnabled;
  74650. }
  74651. scene.workerCollisions = !!parsedData.workerCollisions;
  74652. var container = loadAssetContainer(scene, data, rootUrl, onError, true);
  74653. if (!container) {
  74654. return false;
  74655. }
  74656. if (parsedData.autoAnimate) {
  74657. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  74658. }
  74659. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  74660. scene.setActiveCameraByID(parsedData.activeCameraID);
  74661. }
  74662. // Environment texture
  74663. if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {
  74664. if (parsedData.environmentTextureType && parsedData.environmentTextureType === "BABYLON.HDRCubeTexture") {
  74665. var hdrSize = (parsedData.environmentTextureSize) ? parsedData.environmentTextureSize : 128;
  74666. var hdrTexture = new BABYLON.HDRCubeTexture(rootUrl + parsedData.environmentTexture, scene, hdrSize);
  74667. if (parsedData.environmentTextureRotationY) {
  74668. hdrTexture.rotationY = parsedData.environmentTextureRotationY;
  74669. }
  74670. scene.environmentTexture = hdrTexture;
  74671. }
  74672. else {
  74673. var cubeTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene);
  74674. if (parsedData.environmentTextureRotationY) {
  74675. cubeTexture.rotationY = parsedData.environmentTextureRotationY;
  74676. }
  74677. scene.environmentTexture = cubeTexture;
  74678. }
  74679. if (parsedData.createDefaultSkybox === true) {
  74680. var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;
  74681. var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;
  74682. scene.createDefaultSkybox(undefined, true, skyboxScale, skyboxBlurLevel);
  74683. }
  74684. }
  74685. // Finish
  74686. return true;
  74687. }
  74688. catch (err) {
  74689. var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
  74690. if (onError) {
  74691. onError(msg, err);
  74692. }
  74693. else {
  74694. BABYLON.Tools.Log(msg);
  74695. throw err;
  74696. }
  74697. }
  74698. finally {
  74699. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  74700. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  74701. }
  74702. }
  74703. return false;
  74704. },
  74705. loadAssetContainer: function (scene, data, rootUrl, onError) {
  74706. var container = loadAssetContainer(scene, data, rootUrl, onError);
  74707. return container;
  74708. }
  74709. });
  74710. })(BABYLON || (BABYLON = {}));
  74711. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  74712. var BABYLON;
  74713. (function (BABYLON) {
  74714. var FilesInput = /** @class */ (function () {
  74715. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) {
  74716. this.onProcessFileCallback = function () { return true; };
  74717. this._engine = engine;
  74718. this._currentScene = scene;
  74719. this._sceneLoadedCallback = sceneLoadedCallback;
  74720. this._progressCallback = progressCallback;
  74721. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  74722. this._textureLoadingCallback = textureLoadingCallback;
  74723. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  74724. this._onReloadCallback = onReloadCallback;
  74725. this._errorCallback = errorCallback;
  74726. }
  74727. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  74728. var _this = this;
  74729. if (elementToMonitor) {
  74730. this._elementToMonitor = elementToMonitor;
  74731. this._dragEnterHandler = function (e) { _this.drag(e); };
  74732. this._dragOverHandler = function (e) { _this.drag(e); };
  74733. this._dropHandler = function (e) { _this.drop(e); };
  74734. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  74735. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  74736. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  74737. }
  74738. };
  74739. FilesInput.prototype.dispose = function () {
  74740. if (!this._elementToMonitor) {
  74741. return;
  74742. }
  74743. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  74744. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  74745. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  74746. };
  74747. FilesInput.prototype.renderFunction = function () {
  74748. if (this._additionalRenderLoopLogicCallback) {
  74749. this._additionalRenderLoopLogicCallback();
  74750. }
  74751. if (this._currentScene) {
  74752. if (this._textureLoadingCallback) {
  74753. var remaining = this._currentScene.getWaitingItemsCount();
  74754. if (remaining > 0) {
  74755. this._textureLoadingCallback(remaining);
  74756. }
  74757. }
  74758. this._currentScene.render();
  74759. }
  74760. };
  74761. FilesInput.prototype.drag = function (e) {
  74762. e.stopPropagation();
  74763. e.preventDefault();
  74764. };
  74765. FilesInput.prototype.drop = function (eventDrop) {
  74766. eventDrop.stopPropagation();
  74767. eventDrop.preventDefault();
  74768. this.loadFiles(eventDrop);
  74769. };
  74770. FilesInput.prototype._traverseFolder = function (folder, files, remaining, callback) {
  74771. var _this = this;
  74772. var reader = folder.createReader();
  74773. var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  74774. reader.readEntries(function (entries) {
  74775. remaining.count += entries.length;
  74776. for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
  74777. var entry = entries_1[_i];
  74778. if (entry.isFile) {
  74779. entry.file(function (file) {
  74780. file.correctName = relativePath + file.name;
  74781. files.push(file);
  74782. if (--remaining.count === 0) {
  74783. callback();
  74784. }
  74785. });
  74786. }
  74787. else if (entry.isDirectory) {
  74788. _this._traverseFolder(entry, files, remaining, callback);
  74789. }
  74790. }
  74791. if (--remaining.count) {
  74792. callback();
  74793. }
  74794. });
  74795. };
  74796. FilesInput.prototype._processFiles = function (files) {
  74797. for (var i = 0; i < files.length; i++) {
  74798. var name = files[i].correctName.toLowerCase();
  74799. var extension = name.split('.').pop();
  74800. if (!this.onProcessFileCallback(files[i], name, extension)) {
  74801. continue;
  74802. }
  74803. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  74804. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  74805. this._sceneFileToLoad = files[i];
  74806. }
  74807. FilesInput.FilesToLoad[name] = files[i];
  74808. }
  74809. };
  74810. FilesInput.prototype.loadFiles = function (event) {
  74811. var _this = this;
  74812. // Handling data transfer via drag'n'drop
  74813. if (event && event.dataTransfer && event.dataTransfer.files) {
  74814. this._filesToLoad = event.dataTransfer.files;
  74815. }
  74816. // Handling files from input files
  74817. if (event && event.target && event.target.files) {
  74818. this._filesToLoad = event.target.files;
  74819. }
  74820. if (!this._filesToLoad || this._filesToLoad.length === 0) {
  74821. return;
  74822. }
  74823. if (this._startingProcessingFilesCallback) {
  74824. this._startingProcessingFilesCallback(this._filesToLoad);
  74825. }
  74826. if (this._filesToLoad && this._filesToLoad.length > 0) {
  74827. var files_1 = new Array();
  74828. var folders = [];
  74829. var items = event.dataTransfer ? event.dataTransfer.items : null;
  74830. for (var i = 0; i < this._filesToLoad.length; i++) {
  74831. var fileToLoad = this._filesToLoad[i];
  74832. var name_1 = fileToLoad.name.toLowerCase();
  74833. var entry = void 0;
  74834. fileToLoad.correctName = name_1;
  74835. if (items) {
  74836. var item = items[i];
  74837. if (item.getAsEntry) {
  74838. entry = item.getAsEntry();
  74839. }
  74840. else if (item.webkitGetAsEntry) {
  74841. entry = item.webkitGetAsEntry();
  74842. }
  74843. }
  74844. if (!entry) {
  74845. files_1.push(fileToLoad);
  74846. }
  74847. else {
  74848. if (entry.isDirectory) {
  74849. folders.push(entry);
  74850. }
  74851. else {
  74852. files_1.push(fileToLoad);
  74853. }
  74854. }
  74855. }
  74856. if (folders.length === 0) {
  74857. this._processFiles(files_1);
  74858. this._processReload();
  74859. }
  74860. else {
  74861. var remaining = { count: folders.length };
  74862. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  74863. var folder = folders_1[_i];
  74864. this._traverseFolder(folder, files_1, remaining, function () {
  74865. _this._processFiles(files_1);
  74866. if (remaining.count === 0) {
  74867. _this._processReload();
  74868. }
  74869. });
  74870. }
  74871. }
  74872. }
  74873. };
  74874. FilesInput.prototype._processReload = function () {
  74875. if (this._onReloadCallback) {
  74876. this._onReloadCallback(this._sceneFileToLoad);
  74877. }
  74878. else {
  74879. this.reload();
  74880. }
  74881. };
  74882. FilesInput.prototype.reload = function () {
  74883. var _this = this;
  74884. // If a scene file has been provided
  74885. if (this._sceneFileToLoad) {
  74886. if (this._currentScene) {
  74887. if (BABYLON.Tools.errorsCount > 0) {
  74888. BABYLON.Tools.ClearLogCache();
  74889. }
  74890. this._engine.stopRenderLoop();
  74891. }
  74892. BABYLON.SceneLoader.LoadAsync("file:", this._sceneFileToLoad.name, this._engine, function (progress) {
  74893. if (_this._progressCallback) {
  74894. _this._progressCallback(progress);
  74895. }
  74896. }).then(function (scene) {
  74897. if (_this._currentScene) {
  74898. _this._currentScene.dispose();
  74899. }
  74900. _this._currentScene = scene;
  74901. if (_this._sceneLoadedCallback) {
  74902. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  74903. }
  74904. // Wait for textures and shaders to be ready
  74905. _this._currentScene.executeWhenReady(function () {
  74906. _this._engine.runRenderLoop(function () {
  74907. _this.renderFunction();
  74908. });
  74909. });
  74910. }).catch(function (error) {
  74911. if (_this._errorCallback) {
  74912. _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, error.message);
  74913. }
  74914. });
  74915. }
  74916. else {
  74917. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  74918. }
  74919. };
  74920. FilesInput.FilesToLoad = {};
  74921. return FilesInput;
  74922. }());
  74923. BABYLON.FilesInput = FilesInput;
  74924. })(BABYLON || (BABYLON = {}));
  74925. //# sourceMappingURL=babylon.filesInput.js.map
  74926. var BABYLON;
  74927. (function (BABYLON) {
  74928. var Tags = /** @class */ (function () {
  74929. function Tags() {
  74930. }
  74931. Tags.EnableFor = function (obj) {
  74932. obj._tags = obj._tags || {};
  74933. obj.hasTags = function () {
  74934. return Tags.HasTags(obj);
  74935. };
  74936. obj.addTags = function (tagsString) {
  74937. return Tags.AddTagsTo(obj, tagsString);
  74938. };
  74939. obj.removeTags = function (tagsString) {
  74940. return Tags.RemoveTagsFrom(obj, tagsString);
  74941. };
  74942. obj.matchesTagsQuery = function (tagsQuery) {
  74943. return Tags.MatchesQuery(obj, tagsQuery);
  74944. };
  74945. };
  74946. Tags.DisableFor = function (obj) {
  74947. delete obj._tags;
  74948. delete obj.hasTags;
  74949. delete obj.addTags;
  74950. delete obj.removeTags;
  74951. delete obj.matchesTagsQuery;
  74952. };
  74953. Tags.HasTags = function (obj) {
  74954. if (!obj._tags) {
  74955. return false;
  74956. }
  74957. return !BABYLON.Tools.IsEmpty(obj._tags);
  74958. };
  74959. Tags.GetTags = function (obj, asString) {
  74960. if (asString === void 0) { asString = true; }
  74961. if (!obj._tags) {
  74962. return null;
  74963. }
  74964. if (asString) {
  74965. var tagsArray = [];
  74966. for (var tag in obj._tags) {
  74967. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  74968. tagsArray.push(tag);
  74969. }
  74970. }
  74971. return tagsArray.join(" ");
  74972. }
  74973. else {
  74974. return obj._tags;
  74975. }
  74976. };
  74977. // the tags 'true' and 'false' are reserved and cannot be used as tags
  74978. // a tag cannot start with '||', '&&', and '!'
  74979. // it cannot contain whitespaces
  74980. Tags.AddTagsTo = function (obj, tagsString) {
  74981. if (!tagsString) {
  74982. return;
  74983. }
  74984. if (typeof tagsString !== "string") {
  74985. return;
  74986. }
  74987. var tags = tagsString.split(" ");
  74988. tags.forEach(function (tag, index, array) {
  74989. Tags._AddTagTo(obj, tag);
  74990. });
  74991. };
  74992. Tags._AddTagTo = function (obj, tag) {
  74993. tag = tag.trim();
  74994. if (tag === "" || tag === "true" || tag === "false") {
  74995. return;
  74996. }
  74997. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  74998. return;
  74999. }
  75000. Tags.EnableFor(obj);
  75001. obj._tags[tag] = true;
  75002. };
  75003. Tags.RemoveTagsFrom = function (obj, tagsString) {
  75004. if (!Tags.HasTags(obj)) {
  75005. return;
  75006. }
  75007. var tags = tagsString.split(" ");
  75008. for (var t in tags) {
  75009. Tags._RemoveTagFrom(obj, tags[t]);
  75010. }
  75011. };
  75012. Tags._RemoveTagFrom = function (obj, tag) {
  75013. delete obj._tags[tag];
  75014. };
  75015. Tags.MatchesQuery = function (obj, tagsQuery) {
  75016. if (tagsQuery === undefined) {
  75017. return true;
  75018. }
  75019. if (tagsQuery === "") {
  75020. return Tags.HasTags(obj);
  75021. }
  75022. return BABYLON.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  75023. };
  75024. return Tags;
  75025. }());
  75026. BABYLON.Tags = Tags;
  75027. })(BABYLON || (BABYLON = {}));
  75028. //# sourceMappingURL=babylon.tags.js.map
  75029. var BABYLON;
  75030. (function (BABYLON) {
  75031. /**
  75032. * Class used to evalaute queries containing `and` and `or` operators
  75033. */
  75034. var AndOrNotEvaluator = /** @class */ (function () {
  75035. function AndOrNotEvaluator() {
  75036. }
  75037. /**
  75038. * Evaluate a query
  75039. * @param query defines the query to evaluate
  75040. * @param evaluateCallback defines the callback used to filter result
  75041. * @returns true if the query matches
  75042. */
  75043. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  75044. if (!query.match(/\([^\(\)]*\)/g)) {
  75045. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  75046. }
  75047. else {
  75048. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  75049. // remove parenthesis
  75050. r = r.slice(1, r.length - 1);
  75051. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  75052. });
  75053. }
  75054. if (query === "true") {
  75055. return true;
  75056. }
  75057. if (query === "false") {
  75058. return false;
  75059. }
  75060. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  75061. };
  75062. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  75063. evaluateCallback = evaluateCallback || (function (r) {
  75064. return r === "true" ? true : false;
  75065. });
  75066. var result;
  75067. var or = parenthesisContent.split("||");
  75068. for (var i in or) {
  75069. if (or.hasOwnProperty(i)) {
  75070. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  75071. var and = ori.split("&&");
  75072. if (and.length > 1) {
  75073. for (var j = 0; j < and.length; ++j) {
  75074. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  75075. if (andj !== "true" && andj !== "false") {
  75076. if (andj[0] === "!") {
  75077. result = !evaluateCallback(andj.substring(1));
  75078. }
  75079. else {
  75080. result = evaluateCallback(andj);
  75081. }
  75082. }
  75083. else {
  75084. result = andj === "true" ? true : false;
  75085. }
  75086. if (!result) { // no need to continue since 'false && ... && ...' will always return false
  75087. ori = "false";
  75088. break;
  75089. }
  75090. }
  75091. }
  75092. if (result || ori === "true") { // no need to continue since 'true || ... || ...' will always return true
  75093. result = true;
  75094. break;
  75095. }
  75096. // result equals false (or undefined)
  75097. if (ori !== "true" && ori !== "false") {
  75098. if (ori[0] === "!") {
  75099. result = !evaluateCallback(ori.substring(1));
  75100. }
  75101. else {
  75102. result = evaluateCallback(ori);
  75103. }
  75104. }
  75105. else {
  75106. result = ori === "true" ? true : false;
  75107. }
  75108. }
  75109. }
  75110. // the whole parenthesis scope is replaced by 'true' or 'false'
  75111. return result ? "true" : "false";
  75112. };
  75113. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  75114. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  75115. // remove whitespaces
  75116. r = r.replace(/[\s]/g, function () { return ""; });
  75117. return r.length % 2 ? "!" : "";
  75118. });
  75119. booleanString = booleanString.trim();
  75120. if (booleanString === "!true") {
  75121. booleanString = "false";
  75122. }
  75123. else if (booleanString === "!false") {
  75124. booleanString = "true";
  75125. }
  75126. return booleanString;
  75127. };
  75128. return AndOrNotEvaluator;
  75129. }());
  75130. BABYLON.AndOrNotEvaluator = AndOrNotEvaluator;
  75131. })(BABYLON || (BABYLON = {}));
  75132. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  75133. var BABYLON;
  75134. (function (BABYLON) {
  75135. /**
  75136. * Class used to enable access to IndexedDB
  75137. * @see @https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API
  75138. */
  75139. var Database = /** @class */ (function () {
  75140. /**
  75141. * Creates a new Database
  75142. * @param urlToScene defines the url to load the scene
  75143. * @param callbackManifestChecked defines the callback to use when manifest is checked
  75144. * @param disableManifestCheck defines a boolean indicating that we want to skip the manifest validation (it will be considered validated and up to date)
  75145. */
  75146. function Database(urlToScene, callbackManifestChecked, disableManifestCheck) {
  75147. if (disableManifestCheck === void 0) { disableManifestCheck = false; }
  75148. var _this = this;
  75149. // Handling various flavors of prefixed version of IndexedDB
  75150. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  75151. this.callbackManifestChecked = callbackManifestChecked;
  75152. this.currentSceneUrl = Database._ReturnFullUrlLocation(urlToScene);
  75153. this.db = null;
  75154. this._enableSceneOffline = false;
  75155. this._enableTexturesOffline = false;
  75156. this.manifestVersionFound = 0;
  75157. this.mustUpdateRessources = false;
  75158. this.hasReachedQuota = false;
  75159. if (!Database.IDBStorageEnabled) {
  75160. this.callbackManifestChecked(true);
  75161. }
  75162. else {
  75163. if (disableManifestCheck) {
  75164. this._enableSceneOffline = true;
  75165. this._enableTexturesOffline = true;
  75166. this.manifestVersionFound = 1;
  75167. BABYLON.Tools.SetImmediate(function () {
  75168. _this.callbackManifestChecked(true);
  75169. });
  75170. }
  75171. else {
  75172. this._checkManifestFile();
  75173. }
  75174. }
  75175. }
  75176. Object.defineProperty(Database.prototype, "enableSceneOffline", {
  75177. /**
  75178. * Gets a boolean indicating if scene must be saved in the database
  75179. */
  75180. get: function () {
  75181. return this._enableSceneOffline;
  75182. },
  75183. enumerable: true,
  75184. configurable: true
  75185. });
  75186. Object.defineProperty(Database.prototype, "enableTexturesOffline", {
  75187. /**
  75188. * Gets a boolean indicating if textures must be saved in the database
  75189. */
  75190. get: function () {
  75191. return this._enableTexturesOffline;
  75192. },
  75193. enumerable: true,
  75194. configurable: true
  75195. });
  75196. Database.prototype._checkManifestFile = function () {
  75197. var _this = this;
  75198. var noManifestFile = function () {
  75199. _this._enableSceneOffline = false;
  75200. _this._enableTexturesOffline = false;
  75201. _this.callbackManifestChecked(false);
  75202. };
  75203. var timeStampUsed = false;
  75204. var manifestURL = this.currentSceneUrl + ".manifest";
  75205. var xhr = new XMLHttpRequest();
  75206. if (navigator.onLine) {
  75207. // Adding a timestamp to by-pass browsers' cache
  75208. timeStampUsed = true;
  75209. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + Date.now();
  75210. }
  75211. xhr.open("GET", manifestURL, true);
  75212. xhr.addEventListener("load", function () {
  75213. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  75214. try {
  75215. var manifestFile = JSON.parse(xhr.response);
  75216. _this._enableSceneOffline = manifestFile.enableSceneOffline;
  75217. _this._enableTexturesOffline = manifestFile.enableTexturesOffline;
  75218. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  75219. _this.manifestVersionFound = manifestFile.version;
  75220. }
  75221. if (_this.callbackManifestChecked) {
  75222. _this.callbackManifestChecked(true);
  75223. }
  75224. }
  75225. catch (ex) {
  75226. noManifestFile();
  75227. }
  75228. }
  75229. else {
  75230. noManifestFile();
  75231. }
  75232. }, false);
  75233. xhr.addEventListener("error", function (event) {
  75234. if (timeStampUsed) {
  75235. timeStampUsed = false;
  75236. // Let's retry without the timeStamp
  75237. // It could fail when coupled with HTML5 Offline API
  75238. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  75239. xhr.open("GET", retryManifestURL, true);
  75240. xhr.send();
  75241. }
  75242. else {
  75243. noManifestFile();
  75244. }
  75245. }, false);
  75246. try {
  75247. xhr.send();
  75248. }
  75249. catch (ex) {
  75250. BABYLON.Tools.Error("Error on XHR send request.");
  75251. this.callbackManifestChecked(false);
  75252. }
  75253. };
  75254. /**
  75255. * Open the database and make it available
  75256. * @param successCallback defines the callback to call on success
  75257. * @param errorCallback defines the callback to call on error
  75258. */
  75259. Database.prototype.openAsync = function (successCallback, errorCallback) {
  75260. var _this = this;
  75261. var handleError = function () {
  75262. _this.isSupported = false;
  75263. if (errorCallback)
  75264. errorCallback();
  75265. };
  75266. if (!this.idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) {
  75267. // Your browser doesn't support IndexedDB
  75268. this.isSupported = false;
  75269. if (errorCallback)
  75270. errorCallback();
  75271. }
  75272. else {
  75273. // If the DB hasn't been opened or created yet
  75274. if (!this.db) {
  75275. this.hasReachedQuota = false;
  75276. this.isSupported = true;
  75277. var request = this.idbFactory.open("babylonjs", 1);
  75278. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  75279. request.onerror = function (event) {
  75280. handleError();
  75281. };
  75282. // executes when a version change transaction cannot complete due to other active transactions
  75283. request.onblocked = function (event) {
  75284. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  75285. handleError();
  75286. };
  75287. // DB has been opened successfully
  75288. request.onsuccess = function (event) {
  75289. _this.db = request.result;
  75290. successCallback();
  75291. };
  75292. // Initialization of the DB. Creating Scenes & Textures stores
  75293. request.onupgradeneeded = function (event) {
  75294. _this.db = (event.target).result;
  75295. if (_this.db) {
  75296. try {
  75297. _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  75298. _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  75299. _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  75300. }
  75301. catch (ex) {
  75302. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  75303. handleError();
  75304. }
  75305. }
  75306. };
  75307. }
  75308. // DB has already been created and opened
  75309. else {
  75310. if (successCallback)
  75311. successCallback();
  75312. }
  75313. }
  75314. };
  75315. /**
  75316. * Loads an image from the database
  75317. * @param url defines the url to load from
  75318. * @param image defines the target DOM image
  75319. */
  75320. Database.prototype.loadImageFromDB = function (url, image) {
  75321. var _this = this;
  75322. var completeURL = Database._ReturnFullUrlLocation(url);
  75323. var saveAndLoadImage = function () {
  75324. if (!_this.hasReachedQuota && _this.db !== null) {
  75325. // the texture is not yet in the DB, let's try to save it
  75326. _this._saveImageIntoDBAsync(completeURL, image);
  75327. }
  75328. // If the texture is not in the DB and we've reached the DB quota limit
  75329. // let's load it directly from the web
  75330. else {
  75331. image.src = url;
  75332. }
  75333. };
  75334. if (!this.mustUpdateRessources) {
  75335. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  75336. }
  75337. // First time we're download the images or update requested in the manifest file by a version change
  75338. else {
  75339. saveAndLoadImage();
  75340. }
  75341. };
  75342. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  75343. if (this.isSupported && this.db !== null) {
  75344. var texture;
  75345. var transaction = this.db.transaction(["textures"]);
  75346. transaction.onabort = function (event) {
  75347. image.src = url;
  75348. };
  75349. transaction.oncomplete = function (event) {
  75350. var blobTextureURL;
  75351. if (texture) {
  75352. var URL = window.URL || window.webkitURL;
  75353. blobTextureURL = URL.createObjectURL(texture.data);
  75354. image.onerror = function () {
  75355. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  75356. image.src = url;
  75357. };
  75358. image.src = blobTextureURL;
  75359. }
  75360. else {
  75361. notInDBCallback();
  75362. }
  75363. };
  75364. var getRequest = transaction.objectStore("textures").get(url);
  75365. getRequest.onsuccess = function (event) {
  75366. texture = (event.target).result;
  75367. };
  75368. getRequest.onerror = function (event) {
  75369. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  75370. image.src = url;
  75371. };
  75372. }
  75373. else {
  75374. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  75375. image.src = url;
  75376. }
  75377. };
  75378. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  75379. var _this = this;
  75380. if (this.isSupported) {
  75381. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  75382. var generateBlobUrl = function () {
  75383. var blobTextureURL;
  75384. if (blob) {
  75385. var URL = window.URL || window.webkitURL;
  75386. try {
  75387. blobTextureURL = URL.createObjectURL(blob);
  75388. }
  75389. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  75390. catch (ex) {
  75391. blobTextureURL = URL.createObjectURL(blob);
  75392. }
  75393. }
  75394. if (blobTextureURL) {
  75395. image.src = blobTextureURL;
  75396. }
  75397. };
  75398. if (Database.IsUASupportingBlobStorage) { // Create XHR
  75399. var xhr = new XMLHttpRequest(), blob;
  75400. xhr.open("GET", url, true);
  75401. xhr.responseType = "blob";
  75402. xhr.addEventListener("load", function () {
  75403. if (xhr.status === 200 && _this.db) {
  75404. // Blob as response (XHR2)
  75405. blob = xhr.response;
  75406. var transaction = _this.db.transaction(["textures"], "readwrite");
  75407. // the transaction could abort because of a QuotaExceededError error
  75408. transaction.onabort = function (event) {
  75409. try {
  75410. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  75411. var srcElement = (event.srcElement || event.target);
  75412. var error = srcElement.error;
  75413. if (error && error.name === "QuotaExceededError") {
  75414. _this.hasReachedQuota = true;
  75415. }
  75416. }
  75417. catch (ex) { }
  75418. generateBlobUrl();
  75419. };
  75420. transaction.oncomplete = function (event) {
  75421. generateBlobUrl();
  75422. };
  75423. var newTexture = { textureUrl: url, data: blob };
  75424. try {
  75425. // Put the blob into the dabase
  75426. var addRequest = transaction.objectStore("textures").put(newTexture);
  75427. addRequest.onsuccess = function (event) {
  75428. };
  75429. addRequest.onerror = function (event) {
  75430. generateBlobUrl();
  75431. };
  75432. }
  75433. catch (ex) {
  75434. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  75435. if (ex.code === 25) {
  75436. Database.IsUASupportingBlobStorage = false;
  75437. }
  75438. image.src = url;
  75439. }
  75440. }
  75441. else {
  75442. image.src = url;
  75443. }
  75444. }, false);
  75445. xhr.addEventListener("error", function (event) {
  75446. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  75447. image.src = url;
  75448. }, false);
  75449. xhr.send();
  75450. }
  75451. else {
  75452. image.src = url;
  75453. }
  75454. }
  75455. else {
  75456. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  75457. image.src = url;
  75458. }
  75459. };
  75460. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  75461. var _this = this;
  75462. var updateVersion = function () {
  75463. // the version is not yet in the DB or we need to update it
  75464. _this._saveVersionIntoDBAsync(url, versionLoaded);
  75465. };
  75466. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  75467. };
  75468. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  75469. var _this = this;
  75470. if (this.isSupported && this.db) {
  75471. var version;
  75472. try {
  75473. var transaction = this.db.transaction(["versions"]);
  75474. transaction.oncomplete = function (event) {
  75475. if (version) {
  75476. // If the version in the JSON file is different from the version in DB
  75477. if (_this.manifestVersionFound !== version.data) {
  75478. _this.mustUpdateRessources = true;
  75479. updateInDBCallback();
  75480. }
  75481. else {
  75482. callback(version.data);
  75483. }
  75484. }
  75485. // version was not found in DB
  75486. else {
  75487. _this.mustUpdateRessources = true;
  75488. updateInDBCallback();
  75489. }
  75490. };
  75491. transaction.onabort = function (event) {
  75492. callback(-1);
  75493. };
  75494. var getRequest = transaction.objectStore("versions").get(url);
  75495. getRequest.onsuccess = function (event) {
  75496. version = (event.target).result;
  75497. };
  75498. getRequest.onerror = function (event) {
  75499. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  75500. callback(-1);
  75501. };
  75502. }
  75503. catch (ex) {
  75504. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  75505. callback(-1);
  75506. }
  75507. }
  75508. else {
  75509. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  75510. callback(-1);
  75511. }
  75512. };
  75513. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  75514. var _this = this;
  75515. if (this.isSupported && !this.hasReachedQuota && this.db) {
  75516. try {
  75517. // Open a transaction to the database
  75518. var transaction = this.db.transaction(["versions"], "readwrite");
  75519. // the transaction could abort because of a QuotaExceededError error
  75520. transaction.onabort = function (event) {
  75521. try { //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  75522. var error = event.srcElement['error'];
  75523. if (error && error.name === "QuotaExceededError") {
  75524. _this.hasReachedQuota = true;
  75525. }
  75526. }
  75527. catch (ex) { }
  75528. callback(-1);
  75529. };
  75530. transaction.oncomplete = function (event) {
  75531. callback(_this.manifestVersionFound);
  75532. };
  75533. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  75534. // Put the scene into the database
  75535. var addRequest = transaction.objectStore("versions").put(newVersion);
  75536. addRequest.onsuccess = function (event) {
  75537. };
  75538. addRequest.onerror = function (event) {
  75539. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  75540. };
  75541. }
  75542. catch (ex) {
  75543. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  75544. callback(-1);
  75545. }
  75546. }
  75547. else {
  75548. callback(-1);
  75549. }
  75550. };
  75551. /**
  75552. * Loads a file from database
  75553. * @param url defines the URL to load from
  75554. * @param sceneLoaded defines a callback to call on success
  75555. * @param progressCallBack defines a callback to call when progress changed
  75556. * @param errorCallback defines a callback to call on error
  75557. * @param useArrayBuffer defines a boolean to use array buffer instead of text string
  75558. */
  75559. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  75560. var _this = this;
  75561. var completeUrl = Database._ReturnFullUrlLocation(url);
  75562. var saveAndLoadFile = function () {
  75563. // the scene is not yet in the DB, let's try to save it
  75564. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer, errorCallback);
  75565. };
  75566. this._checkVersionFromDB(completeUrl, function (version) {
  75567. if (version !== -1) {
  75568. if (!_this.mustUpdateRessources) {
  75569. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  75570. }
  75571. else {
  75572. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer, errorCallback);
  75573. }
  75574. }
  75575. else {
  75576. if (errorCallback) {
  75577. errorCallback();
  75578. }
  75579. }
  75580. });
  75581. };
  75582. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  75583. if (this.isSupported && this.db) {
  75584. var targetStore;
  75585. if (url.indexOf(".babylon") !== -1) {
  75586. targetStore = "scenes";
  75587. }
  75588. else {
  75589. targetStore = "textures";
  75590. }
  75591. var file;
  75592. var transaction = this.db.transaction([targetStore]);
  75593. transaction.oncomplete = function (event) {
  75594. if (file) {
  75595. callback(file.data);
  75596. }
  75597. // file was not found in DB
  75598. else {
  75599. notInDBCallback();
  75600. }
  75601. };
  75602. transaction.onabort = function (event) {
  75603. notInDBCallback();
  75604. };
  75605. var getRequest = transaction.objectStore(targetStore).get(url);
  75606. getRequest.onsuccess = function (event) {
  75607. file = (event.target).result;
  75608. };
  75609. getRequest.onerror = function (event) {
  75610. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  75611. notInDBCallback();
  75612. };
  75613. }
  75614. else {
  75615. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  75616. callback();
  75617. }
  75618. };
  75619. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer, errorCallback) {
  75620. var _this = this;
  75621. if (this.isSupported) {
  75622. var targetStore;
  75623. if (url.indexOf(".babylon") !== -1) {
  75624. targetStore = "scenes";
  75625. }
  75626. else {
  75627. targetStore = "textures";
  75628. }
  75629. // Create XHR
  75630. var xhr = new XMLHttpRequest();
  75631. var fileData;
  75632. xhr.open("GET", url + "?" + Date.now(), true);
  75633. if (useArrayBuffer) {
  75634. xhr.responseType = "arraybuffer";
  75635. }
  75636. if (progressCallback) {
  75637. xhr.onprogress = progressCallback;
  75638. }
  75639. xhr.addEventListener("load", function () {
  75640. if (xhr.status === 200 || (xhr.status < 400 && BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6))) {
  75641. // Blob as response (XHR2)
  75642. //fileData = xhr.responseText;
  75643. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  75644. if (!_this.hasReachedQuota && _this.db) {
  75645. // Open a transaction to the database
  75646. var transaction = _this.db.transaction([targetStore], "readwrite");
  75647. // the transaction could abort because of a QuotaExceededError error
  75648. transaction.onabort = function (event) {
  75649. try {
  75650. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  75651. var error = event.srcElement['error'];
  75652. if (error && error.name === "QuotaExceededError") {
  75653. _this.hasReachedQuota = true;
  75654. }
  75655. }
  75656. catch (ex) { }
  75657. callback(fileData);
  75658. };
  75659. transaction.oncomplete = function (event) {
  75660. callback(fileData);
  75661. };
  75662. var newFile;
  75663. if (targetStore === "scenes") {
  75664. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  75665. }
  75666. else {
  75667. newFile = { textureUrl: url, data: fileData };
  75668. }
  75669. try {
  75670. // Put the scene into the database
  75671. var addRequest = transaction.objectStore(targetStore).put(newFile);
  75672. addRequest.onsuccess = function (event) {
  75673. };
  75674. addRequest.onerror = function (event) {
  75675. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  75676. };
  75677. }
  75678. catch (ex) {
  75679. callback(fileData);
  75680. }
  75681. }
  75682. else {
  75683. callback(fileData);
  75684. }
  75685. }
  75686. else {
  75687. if (xhr.status >= 400 && errorCallback) {
  75688. errorCallback(xhr);
  75689. }
  75690. else {
  75691. callback();
  75692. }
  75693. }
  75694. }, false);
  75695. xhr.addEventListener("error", function (event) {
  75696. BABYLON.Tools.Error("error on XHR request.");
  75697. callback();
  75698. }, false);
  75699. xhr.send();
  75700. }
  75701. else {
  75702. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  75703. callback();
  75704. }
  75705. };
  75706. /** Gets a boolean indicating if the user agent supports blob storage (this value will be updated after creating the first Database object) */
  75707. Database.IsUASupportingBlobStorage = true;
  75708. /** Gets a boolean indicating if Database storate is enabled */
  75709. Database.IDBStorageEnabled = true;
  75710. Database._ParseURL = function (url) {
  75711. var a = document.createElement('a');
  75712. a.href = url;
  75713. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  75714. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  75715. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  75716. return absLocation;
  75717. };
  75718. Database._ReturnFullUrlLocation = function (url) {
  75719. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  75720. return (Database._ParseURL(window.location.href) + url);
  75721. }
  75722. else {
  75723. return url;
  75724. }
  75725. };
  75726. return Database;
  75727. }());
  75728. BABYLON.Database = Database;
  75729. })(BABYLON || (BABYLON = {}));
  75730. //# sourceMappingURL=babylon.database.js.map
  75731. var BABYLON;
  75732. (function (BABYLON) {
  75733. var FresnelParameters = /** @class */ (function () {
  75734. function FresnelParameters() {
  75735. this._isEnabled = true;
  75736. this.leftColor = BABYLON.Color3.White();
  75737. this.rightColor = BABYLON.Color3.Black();
  75738. this.bias = 0;
  75739. this.power = 1;
  75740. }
  75741. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  75742. get: function () {
  75743. return this._isEnabled;
  75744. },
  75745. set: function (value) {
  75746. if (this._isEnabled === value) {
  75747. return;
  75748. }
  75749. this._isEnabled = value;
  75750. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  75751. },
  75752. enumerable: true,
  75753. configurable: true
  75754. });
  75755. FresnelParameters.prototype.clone = function () {
  75756. var newFresnelParameters = new FresnelParameters();
  75757. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  75758. return newFresnelParameters;
  75759. };
  75760. FresnelParameters.prototype.serialize = function () {
  75761. var serializationObject = {};
  75762. serializationObject.isEnabled = this.isEnabled;
  75763. serializationObject.leftColor = this.leftColor.asArray();
  75764. serializationObject.rightColor = this.rightColor.asArray();
  75765. serializationObject.bias = this.bias;
  75766. serializationObject.power = this.power;
  75767. return serializationObject;
  75768. };
  75769. FresnelParameters.Parse = function (parsedFresnelParameters) {
  75770. var fresnelParameters = new FresnelParameters();
  75771. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  75772. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  75773. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  75774. fresnelParameters.bias = parsedFresnelParameters.bias;
  75775. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  75776. return fresnelParameters;
  75777. };
  75778. return FresnelParameters;
  75779. }());
  75780. BABYLON.FresnelParameters = FresnelParameters;
  75781. })(BABYLON || (BABYLON = {}));
  75782. //# sourceMappingURL=babylon.fresnelParameters.js.map
  75783. var BABYLON;
  75784. (function (BABYLON) {
  75785. var MultiMaterial = /** @class */ (function (_super) {
  75786. __extends(MultiMaterial, _super);
  75787. function MultiMaterial(name, scene) {
  75788. var _this = _super.call(this, name, scene, true) || this;
  75789. scene.multiMaterials.push(_this);
  75790. _this.subMaterials = new Array();
  75791. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  75792. return _this;
  75793. }
  75794. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  75795. get: function () {
  75796. return this._subMaterials;
  75797. },
  75798. set: function (value) {
  75799. this._subMaterials = value;
  75800. this._hookArray(value);
  75801. },
  75802. enumerable: true,
  75803. configurable: true
  75804. });
  75805. MultiMaterial.prototype._hookArray = function (array) {
  75806. var _this = this;
  75807. var oldPush = array.push;
  75808. array.push = function () {
  75809. var items = [];
  75810. for (var _i = 0; _i < arguments.length; _i++) {
  75811. items[_i] = arguments[_i];
  75812. }
  75813. var result = oldPush.apply(array, items);
  75814. _this._markAllSubMeshesAsTexturesDirty();
  75815. return result;
  75816. };
  75817. var oldSplice = array.splice;
  75818. array.splice = function (index, deleteCount) {
  75819. var deleted = oldSplice.apply(array, [index, deleteCount]);
  75820. _this._markAllSubMeshesAsTexturesDirty();
  75821. return deleted;
  75822. };
  75823. };
  75824. // Properties
  75825. MultiMaterial.prototype.getSubMaterial = function (index) {
  75826. if (index < 0 || index >= this.subMaterials.length) {
  75827. return this.getScene().defaultMaterial;
  75828. }
  75829. return this.subMaterials[index];
  75830. };
  75831. MultiMaterial.prototype.getActiveTextures = function () {
  75832. var _a;
  75833. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) {
  75834. if (subMaterial) {
  75835. return subMaterial.getActiveTextures();
  75836. }
  75837. else {
  75838. return [];
  75839. }
  75840. }));
  75841. };
  75842. // Methods
  75843. MultiMaterial.prototype.getClassName = function () {
  75844. return "MultiMaterial";
  75845. };
  75846. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  75847. for (var index = 0; index < this.subMaterials.length; index++) {
  75848. var subMaterial = this.subMaterials[index];
  75849. if (subMaterial) {
  75850. if (subMaterial.storeEffectOnSubMeshes) {
  75851. if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) {
  75852. return false;
  75853. }
  75854. continue;
  75855. }
  75856. if (!subMaterial.isReady(mesh)) {
  75857. return false;
  75858. }
  75859. }
  75860. }
  75861. return true;
  75862. };
  75863. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  75864. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  75865. for (var index = 0; index < this.subMaterials.length; index++) {
  75866. var subMaterial = null;
  75867. var current = this.subMaterials[index];
  75868. if (cloneChildren && current) {
  75869. subMaterial = current.clone(name + "-" + current.name);
  75870. }
  75871. else {
  75872. subMaterial = this.subMaterials[index];
  75873. }
  75874. newMultiMaterial.subMaterials.push(subMaterial);
  75875. }
  75876. return newMultiMaterial;
  75877. };
  75878. MultiMaterial.prototype.serialize = function () {
  75879. var serializationObject = {};
  75880. serializationObject.name = this.name;
  75881. serializationObject.id = this.id;
  75882. if (BABYLON.Tags) {
  75883. serializationObject.tags = BABYLON.Tags.GetTags(this);
  75884. }
  75885. serializationObject.materials = [];
  75886. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  75887. var subMat = this.subMaterials[matIndex];
  75888. if (subMat) {
  75889. serializationObject.materials.push(subMat.id);
  75890. }
  75891. else {
  75892. serializationObject.materials.push(null);
  75893. }
  75894. }
  75895. return serializationObject;
  75896. };
  75897. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  75898. var scene = this.getScene();
  75899. if (!scene) {
  75900. return;
  75901. }
  75902. var index = scene.multiMaterials.indexOf(this);
  75903. if (index >= 0) {
  75904. scene.multiMaterials.splice(index, 1);
  75905. }
  75906. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  75907. };
  75908. return MultiMaterial;
  75909. }(BABYLON.Material));
  75910. BABYLON.MultiMaterial = MultiMaterial;
  75911. })(BABYLON || (BABYLON = {}));
  75912. //# sourceMappingURL=babylon.multiMaterial.js.map
  75913. var BABYLON;
  75914. (function (BABYLON) {
  75915. /**
  75916. * Manage the touch inputs to control the movement of a free camera.
  75917. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  75918. */
  75919. var FreeCameraTouchInput = /** @class */ (function () {
  75920. function FreeCameraTouchInput() {
  75921. /**
  75922. * Defines the touch sensibility for rotation.
  75923. * The higher the faster.
  75924. */
  75925. this.touchAngularSensibility = 200000.0;
  75926. /**
  75927. * Defines the touch sensibility for move.
  75928. * The higher the faster.
  75929. */
  75930. this.touchMoveSensibility = 250.0;
  75931. this._offsetX = null;
  75932. this._offsetY = null;
  75933. this._pointerPressed = new Array();
  75934. }
  75935. /**
  75936. * Attach the input controls to a specific dom element to get the input from.
  75937. * @param element Defines the element the controls should be listened from
  75938. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  75939. */
  75940. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  75941. var _this = this;
  75942. var previousPosition = null;
  75943. if (this._pointerInput === undefined) {
  75944. this._onLostFocus = function (evt) {
  75945. _this._offsetX = null;
  75946. _this._offsetY = null;
  75947. };
  75948. this._pointerInput = function (p, s) {
  75949. var evt = p.event;
  75950. if (evt.pointerType === "mouse") {
  75951. return;
  75952. }
  75953. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  75954. if (!noPreventDefault) {
  75955. evt.preventDefault();
  75956. }
  75957. _this._pointerPressed.push(evt.pointerId);
  75958. if (_this._pointerPressed.length !== 1) {
  75959. return;
  75960. }
  75961. previousPosition = {
  75962. x: evt.clientX,
  75963. y: evt.clientY
  75964. };
  75965. }
  75966. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  75967. if (!noPreventDefault) {
  75968. evt.preventDefault();
  75969. }
  75970. var index = _this._pointerPressed.indexOf(evt.pointerId);
  75971. if (index === -1) {
  75972. return;
  75973. }
  75974. _this._pointerPressed.splice(index, 1);
  75975. if (index != 0) {
  75976. return;
  75977. }
  75978. previousPosition = null;
  75979. _this._offsetX = null;
  75980. _this._offsetY = null;
  75981. }
  75982. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  75983. if (!noPreventDefault) {
  75984. evt.preventDefault();
  75985. }
  75986. if (!previousPosition) {
  75987. return;
  75988. }
  75989. var index = _this._pointerPressed.indexOf(evt.pointerId);
  75990. if (index != 0) {
  75991. return;
  75992. }
  75993. _this._offsetX = evt.clientX - previousPosition.x;
  75994. _this._offsetY = -(evt.clientY - previousPosition.y);
  75995. }
  75996. };
  75997. }
  75998. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  75999. if (this._onLostFocus) {
  76000. element.addEventListener("blur", this._onLostFocus);
  76001. }
  76002. };
  76003. /**
  76004. * Detach the current controls from the specified dom element.
  76005. * @param element Defines the element to stop listening the inputs from
  76006. */
  76007. FreeCameraTouchInput.prototype.detachControl = function (element) {
  76008. if (this._pointerInput && element) {
  76009. if (this._observer) {
  76010. this.camera.getScene().onPointerObservable.remove(this._observer);
  76011. this._observer = null;
  76012. }
  76013. if (this._onLostFocus) {
  76014. element.removeEventListener("blur", this._onLostFocus);
  76015. this._onLostFocus = null;
  76016. }
  76017. this._pointerPressed = [];
  76018. this._offsetX = null;
  76019. this._offsetY = null;
  76020. }
  76021. };
  76022. /**
  76023. * Update the current camera state depending on the inputs that have been used this frame.
  76024. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
  76025. */
  76026. FreeCameraTouchInput.prototype.checkInputs = function () {
  76027. if (this._offsetX && this._offsetY) {
  76028. var camera = this.camera;
  76029. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  76030. if (this._pointerPressed.length > 1) {
  76031. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  76032. }
  76033. else {
  76034. var speed = camera._computeLocalCameraSpeed();
  76035. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  76036. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  76037. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  76038. }
  76039. }
  76040. };
  76041. /**
  76042. * Gets the class name of the current intput.
  76043. * @returns the class name
  76044. */
  76045. FreeCameraTouchInput.prototype.getClassName = function () {
  76046. return "FreeCameraTouchInput";
  76047. };
  76048. /**
  76049. * Get the friendly name associated with the input class.
  76050. * @returns the input friendly name
  76051. */
  76052. FreeCameraTouchInput.prototype.getSimpleName = function () {
  76053. return "touch";
  76054. };
  76055. __decorate([
  76056. BABYLON.serialize()
  76057. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  76058. __decorate([
  76059. BABYLON.serialize()
  76060. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  76061. return FreeCameraTouchInput;
  76062. }());
  76063. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  76064. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  76065. })(BABYLON || (BABYLON = {}));
  76066. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  76067. var BABYLON;
  76068. (function (BABYLON) {
  76069. BABYLON.Node.AddNodeConstructor("TouchCamera", function (name, scene) {
  76070. return function () { return new TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  76071. });
  76072. /**
  76073. * This represents a FPS type of camera controlled by touch.
  76074. * This is like a universal camera minus the Gamepad controls.
  76075. * @see http://doc.babylonjs.com/features/cameras#universal-camera
  76076. */
  76077. var TouchCamera = /** @class */ (function (_super) {
  76078. __extends(TouchCamera, _super);
  76079. /**
  76080. * Instantiates a new touch camera.
  76081. * This represents a FPS type of camera controlled by touch.
  76082. * This is like a universal camera minus the Gamepad controls.
  76083. * @see http://doc.babylonjs.com/features/cameras#universal-camera
  76084. * @param name Define the name of the camera in the scene
  76085. * @param position Define the start position of the camera in the scene
  76086. * @param scene Define the scene the camera belongs to
  76087. */
  76088. function TouchCamera(name, position, scene) {
  76089. var _this = _super.call(this, name, position, scene) || this;
  76090. _this.inputs.addTouch();
  76091. _this._setupInputs();
  76092. return _this;
  76093. }
  76094. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  76095. /**
  76096. * Defines the touch sensibility for rotation.
  76097. * The higher the faster.
  76098. */
  76099. get: function () {
  76100. var touch = this.inputs.attached["touch"];
  76101. if (touch)
  76102. return touch.touchAngularSensibility;
  76103. return 0;
  76104. },
  76105. set: function (value) {
  76106. var touch = this.inputs.attached["touch"];
  76107. if (touch)
  76108. touch.touchAngularSensibility = value;
  76109. },
  76110. enumerable: true,
  76111. configurable: true
  76112. });
  76113. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  76114. /**
  76115. * Defines the touch sensibility for move.
  76116. * The higher the faster.
  76117. */
  76118. get: function () {
  76119. var touch = this.inputs.attached["touch"];
  76120. if (touch)
  76121. return touch.touchMoveSensibility;
  76122. return 0;
  76123. },
  76124. set: function (value) {
  76125. var touch = this.inputs.attached["touch"];
  76126. if (touch)
  76127. touch.touchMoveSensibility = value;
  76128. },
  76129. enumerable: true,
  76130. configurable: true
  76131. });
  76132. /**
  76133. * Gets the current object class name.
  76134. * @return the class name
  76135. */
  76136. TouchCamera.prototype.getClassName = function () {
  76137. return "TouchCamera";
  76138. };
  76139. /** @hidden */
  76140. TouchCamera.prototype._setupInputs = function () {
  76141. var mouse = this.inputs.attached["mouse"];
  76142. if (mouse) {
  76143. mouse.touchEnabled = false;
  76144. }
  76145. };
  76146. return TouchCamera;
  76147. }(BABYLON.FreeCamera));
  76148. BABYLON.TouchCamera = TouchCamera;
  76149. })(BABYLON || (BABYLON = {}));
  76150. //# sourceMappingURL=babylon.touchCamera.js.map
  76151. var BABYLON;
  76152. (function (BABYLON) {
  76153. var ProceduralTexture = /** @class */ (function (_super) {
  76154. __extends(ProceduralTexture, _super);
  76155. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  76156. if (fallbackTexture === void 0) { fallbackTexture = null; }
  76157. if (generateMipMaps === void 0) { generateMipMaps = true; }
  76158. if (isCube === void 0) { isCube = false; }
  76159. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  76160. _this.isCube = isCube;
  76161. _this.isEnabled = true;
  76162. _this._currentRefreshId = -1;
  76163. _this._refreshRate = 1;
  76164. /**
  76165. * Event raised when the texture is generated
  76166. */
  76167. _this.onGeneratedObservable = new BABYLON.Observable();
  76168. _this._vertexBuffers = {};
  76169. _this._uniforms = new Array();
  76170. _this._samplers = new Array();
  76171. /** @hidden */
  76172. _this._textures = {};
  76173. _this._floats = {};
  76174. _this._ints = {};
  76175. _this._floatsArrays = {};
  76176. _this._colors3 = {};
  76177. _this._colors4 = {};
  76178. _this._vectors2 = {};
  76179. _this._vectors3 = {};
  76180. _this._matrices = {};
  76181. _this._fallbackTextureUsed = false;
  76182. _this._cachedDefines = "";
  76183. _this._contentUpdateId = -1;
  76184. scene = _this.getScene();
  76185. var component = scene._getComponent(BABYLON.SceneComponentConstants.NAME_PROCEDURALTEXTURE);
  76186. if (!component) {
  76187. component = new BABYLON.ProceduralTextureSceneComponent(scene);
  76188. scene._addComponent(component);
  76189. }
  76190. scene.proceduralTextures.push(_this);
  76191. _this._engine = scene.getEngine();
  76192. _this.name = name;
  76193. _this.isRenderTarget = true;
  76194. _this._size = size;
  76195. _this._generateMipMaps = generateMipMaps;
  76196. _this.setFragment(fragment);
  76197. _this._fallbackTexture = fallbackTexture;
  76198. if (isCube) {
  76199. _this._texture = _this._engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  76200. _this.setFloat("face", 0);
  76201. }
  76202. else {
  76203. _this._texture = _this._engine.createRenderTargetTexture(size, generateMipMaps);
  76204. }
  76205. // VBO
  76206. var vertices = [];
  76207. vertices.push(1, 1);
  76208. vertices.push(-1, 1);
  76209. vertices.push(-1, -1);
  76210. vertices.push(1, -1);
  76211. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(_this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  76212. _this._createIndexBuffer();
  76213. return _this;
  76214. }
  76215. /**
  76216. * Gets texture content (Use this function wisely as reading from a texture can be slow)
  76217. * @returns an ArrayBufferView (Uint8Array or Float32Array)
  76218. */
  76219. ProceduralTexture.prototype.getContent = function () {
  76220. if (this._contentData && this._currentRefreshId == this._contentUpdateId) {
  76221. return this._contentData;
  76222. }
  76223. this._contentData = this.readPixels(0, 0, this._contentData);
  76224. this._contentUpdateId = this._currentRefreshId;
  76225. return this._contentData;
  76226. };
  76227. ProceduralTexture.prototype._createIndexBuffer = function () {
  76228. var engine = this._engine;
  76229. // Indices
  76230. var indices = [];
  76231. indices.push(0);
  76232. indices.push(1);
  76233. indices.push(2);
  76234. indices.push(0);
  76235. indices.push(2);
  76236. indices.push(3);
  76237. this._indexBuffer = engine.createIndexBuffer(indices);
  76238. };
  76239. /** @hidden */
  76240. ProceduralTexture.prototype._rebuild = function () {
  76241. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  76242. if (vb) {
  76243. vb._rebuild();
  76244. }
  76245. this._createIndexBuffer();
  76246. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  76247. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  76248. }
  76249. };
  76250. ProceduralTexture.prototype.reset = function () {
  76251. if (this._effect === undefined) {
  76252. return;
  76253. }
  76254. var engine = this._engine;
  76255. engine._releaseEffect(this._effect);
  76256. };
  76257. ProceduralTexture.prototype._getDefines = function () {
  76258. return "";
  76259. };
  76260. ProceduralTexture.prototype.isReady = function () {
  76261. var _this = this;
  76262. var engine = this._engine;
  76263. var shaders;
  76264. if (!this._fragment) {
  76265. return false;
  76266. }
  76267. if (this._fallbackTextureUsed) {
  76268. return true;
  76269. }
  76270. var defines = this._getDefines();
  76271. if (this._effect && defines === this._cachedDefines && this._effect.isReady()) {
  76272. return true;
  76273. }
  76274. if (this._fragment.fragmentElement !== undefined) {
  76275. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  76276. }
  76277. else {
  76278. shaders = { vertex: "procedural", fragment: this._fragment };
  76279. }
  76280. this._cachedDefines = defines;
  76281. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, defines, undefined, undefined, function () {
  76282. _this.releaseInternalTexture();
  76283. if (_this._fallbackTexture) {
  76284. _this._texture = _this._fallbackTexture._texture;
  76285. if (_this._texture) {
  76286. _this._texture.incrementReferences();
  76287. }
  76288. }
  76289. _this._fallbackTextureUsed = true;
  76290. });
  76291. return this._effect.isReady();
  76292. };
  76293. ProceduralTexture.prototype.resetRefreshCounter = function () {
  76294. this._currentRefreshId = -1;
  76295. };
  76296. ProceduralTexture.prototype.setFragment = function (fragment) {
  76297. this._fragment = fragment;
  76298. };
  76299. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  76300. get: function () {
  76301. return this._refreshRate;
  76302. },
  76303. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  76304. set: function (value) {
  76305. this._refreshRate = value;
  76306. this.resetRefreshCounter();
  76307. },
  76308. enumerable: true,
  76309. configurable: true
  76310. });
  76311. /** @hidden */
  76312. ProceduralTexture.prototype._shouldRender = function () {
  76313. if (!this.isEnabled || !this.isReady() || !this._texture) {
  76314. if (this._texture) {
  76315. this._texture.isReady = false;
  76316. }
  76317. return false;
  76318. }
  76319. if (this._fallbackTextureUsed) {
  76320. return false;
  76321. }
  76322. if (this._currentRefreshId === -1) { // At least render once
  76323. this._currentRefreshId = 1;
  76324. return true;
  76325. }
  76326. if (this.refreshRate === this._currentRefreshId) {
  76327. this._currentRefreshId = 1;
  76328. return true;
  76329. }
  76330. this._currentRefreshId++;
  76331. return false;
  76332. };
  76333. ProceduralTexture.prototype.getRenderSize = function () {
  76334. return this._size;
  76335. };
  76336. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  76337. if (this._fallbackTextureUsed) {
  76338. return;
  76339. }
  76340. this.releaseInternalTexture();
  76341. this._texture = this._engine.createRenderTargetTexture(size, generateMipMaps);
  76342. // Update properties
  76343. this._size = size;
  76344. this._generateMipMaps = generateMipMaps;
  76345. };
  76346. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  76347. if (this._uniforms.indexOf(uniformName) === -1) {
  76348. this._uniforms.push(uniformName);
  76349. }
  76350. };
  76351. ProceduralTexture.prototype.setTexture = function (name, texture) {
  76352. if (this._samplers.indexOf(name) === -1) {
  76353. this._samplers.push(name);
  76354. }
  76355. this._textures[name] = texture;
  76356. return this;
  76357. };
  76358. ProceduralTexture.prototype.setFloat = function (name, value) {
  76359. this._checkUniform(name);
  76360. this._floats[name] = value;
  76361. return this;
  76362. };
  76363. /**
  76364. * Set the value of an uniform to an integer value
  76365. * @param name defines the name of the uniform
  76366. * @param value defines the value to set
  76367. * @returns the current procedural texture
  76368. */
  76369. ProceduralTexture.prototype.setInt = function (name, value) {
  76370. this._checkUniform(name);
  76371. this._ints[name] = value;
  76372. return this;
  76373. };
  76374. ProceduralTexture.prototype.setFloats = function (name, value) {
  76375. this._checkUniform(name);
  76376. this._floatsArrays[name] = value;
  76377. return this;
  76378. };
  76379. ProceduralTexture.prototype.setColor3 = function (name, value) {
  76380. this._checkUniform(name);
  76381. this._colors3[name] = value;
  76382. return this;
  76383. };
  76384. ProceduralTexture.prototype.setColor4 = function (name, value) {
  76385. this._checkUniform(name);
  76386. this._colors4[name] = value;
  76387. return this;
  76388. };
  76389. ProceduralTexture.prototype.setVector2 = function (name, value) {
  76390. this._checkUniform(name);
  76391. this._vectors2[name] = value;
  76392. return this;
  76393. };
  76394. ProceduralTexture.prototype.setVector3 = function (name, value) {
  76395. this._checkUniform(name);
  76396. this._vectors3[name] = value;
  76397. return this;
  76398. };
  76399. ProceduralTexture.prototype.setMatrix = function (name, value) {
  76400. this._checkUniform(name);
  76401. this._matrices[name] = value;
  76402. return this;
  76403. };
  76404. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  76405. var scene = this.getScene();
  76406. if (!scene) {
  76407. return;
  76408. }
  76409. var engine = this._engine;
  76410. // Render
  76411. engine.enableEffect(this._effect);
  76412. engine.setState(false);
  76413. // Texture
  76414. for (var name in this._textures) {
  76415. this._effect.setTexture(name, this._textures[name]);
  76416. }
  76417. // Float
  76418. for (name in this._ints) {
  76419. this._effect.setInt(name, this._ints[name]);
  76420. }
  76421. // Float
  76422. for (name in this._floats) {
  76423. this._effect.setFloat(name, this._floats[name]);
  76424. }
  76425. // Floats
  76426. for (name in this._floatsArrays) {
  76427. this._effect.setArray(name, this._floatsArrays[name]);
  76428. }
  76429. // Color3
  76430. for (name in this._colors3) {
  76431. this._effect.setColor3(name, this._colors3[name]);
  76432. }
  76433. // Color4
  76434. for (name in this._colors4) {
  76435. var color = this._colors4[name];
  76436. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  76437. }
  76438. // Vector2
  76439. for (name in this._vectors2) {
  76440. this._effect.setVector2(name, this._vectors2[name]);
  76441. }
  76442. // Vector3
  76443. for (name in this._vectors3) {
  76444. this._effect.setVector3(name, this._vectors3[name]);
  76445. }
  76446. // Matrix
  76447. for (name in this._matrices) {
  76448. this._effect.setMatrix(name, this._matrices[name]);
  76449. }
  76450. if (!this._texture) {
  76451. return;
  76452. }
  76453. if (this.isCube) {
  76454. for (var face = 0; face < 6; face++) {
  76455. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  76456. // VBOs
  76457. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  76458. this._effect.setFloat("face", face);
  76459. // Clear
  76460. engine.clear(scene.clearColor, true, true, true);
  76461. // Draw order
  76462. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  76463. // Mipmaps
  76464. if (face === 5) {
  76465. engine.generateMipMapsForCubemap(this._texture);
  76466. }
  76467. }
  76468. }
  76469. else {
  76470. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  76471. // VBOs
  76472. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  76473. // Clear
  76474. engine.clear(scene.clearColor, true, true, true);
  76475. // Draw order
  76476. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  76477. }
  76478. // Unbind
  76479. engine.unBindFramebuffer(this._texture, this.isCube);
  76480. if (this.onGenerated) {
  76481. this.onGenerated();
  76482. }
  76483. this.onGeneratedObservable.notifyObservers(this);
  76484. };
  76485. ProceduralTexture.prototype.clone = function () {
  76486. var textureSize = this.getSize();
  76487. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  76488. // Base texture
  76489. newTexture.hasAlpha = this.hasAlpha;
  76490. newTexture.level = this.level;
  76491. // RenderTarget Texture
  76492. newTexture.coordinatesMode = this.coordinatesMode;
  76493. return newTexture;
  76494. };
  76495. ProceduralTexture.prototype.dispose = function () {
  76496. var scene = this.getScene();
  76497. if (!scene) {
  76498. return;
  76499. }
  76500. var index = scene.proceduralTextures.indexOf(this);
  76501. if (index >= 0) {
  76502. scene.proceduralTextures.splice(index, 1);
  76503. }
  76504. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  76505. if (vertexBuffer) {
  76506. vertexBuffer.dispose();
  76507. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  76508. }
  76509. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  76510. this._indexBuffer = null;
  76511. }
  76512. _super.prototype.dispose.call(this);
  76513. };
  76514. __decorate([
  76515. BABYLON.serialize()
  76516. ], ProceduralTexture.prototype, "_size", void 0);
  76517. __decorate([
  76518. BABYLON.serialize()
  76519. ], ProceduralTexture.prototype, "_generateMipMaps", void 0);
  76520. __decorate([
  76521. BABYLON.serialize()
  76522. ], ProceduralTexture.prototype, "isEnabled", void 0);
  76523. __decorate([
  76524. BABYLON.serialize()
  76525. ], ProceduralTexture.prototype, "refreshRate", null);
  76526. return ProceduralTexture;
  76527. }(BABYLON.Texture));
  76528. BABYLON.ProceduralTexture = ProceduralTexture;
  76529. })(BABYLON || (BABYLON = {}));
  76530. //# sourceMappingURL=babylon.proceduralTexture.js.map
  76531. var BABYLON;
  76532. (function (BABYLON) {
  76533. /**
  76534. * Defines the Procedural Texture scene component responsible to manage any Procedural Texture
  76535. * in a given scene.
  76536. */
  76537. var ProceduralTextureSceneComponent = /** @class */ (function () {
  76538. /**
  76539. * Creates a new instance of the component for the given scene
  76540. * @param scene Defines the scene to register the component in
  76541. */
  76542. function ProceduralTextureSceneComponent(scene) {
  76543. /**
  76544. * The component name helpfull to identify the component in the list of scene components.
  76545. */
  76546. this.name = BABYLON.SceneComponentConstants.NAME_PROCEDURALTEXTURE;
  76547. this.scene = scene;
  76548. this.scene.proceduralTextures = new Array();
  76549. scene.layers = new Array();
  76550. }
  76551. /**
  76552. * Registers the component in a given scene
  76553. */
  76554. ProceduralTextureSceneComponent.prototype.register = function () {
  76555. this.scene._beforeClearStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECLEAR_PROCEDURALTEXTURE, this, this._beforeClear);
  76556. };
  76557. /**
  76558. * Rebuilds the elements related to this component in case of
  76559. * context lost for instance.
  76560. */
  76561. ProceduralTextureSceneComponent.prototype.rebuild = function () {
  76562. // Nothing to do here.
  76563. };
  76564. /**
  76565. * Disposes the component and the associated ressources.
  76566. */
  76567. ProceduralTextureSceneComponent.prototype.dispose = function () {
  76568. // Nothing to do here.
  76569. };
  76570. ProceduralTextureSceneComponent.prototype._beforeClear = function () {
  76571. if (this.scene.proceduralTexturesEnabled) {
  76572. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this.scene.proceduralTextures.length > 0);
  76573. for (var proceduralIndex = 0; proceduralIndex < this.scene.proceduralTextures.length; proceduralIndex++) {
  76574. var proceduralTexture = this.scene.proceduralTextures[proceduralIndex];
  76575. if (proceduralTexture._shouldRender()) {
  76576. proceduralTexture.render();
  76577. }
  76578. }
  76579. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this.scene.proceduralTextures.length > 0);
  76580. }
  76581. };
  76582. return ProceduralTextureSceneComponent;
  76583. }());
  76584. BABYLON.ProceduralTextureSceneComponent = ProceduralTextureSceneComponent;
  76585. })(BABYLON || (BABYLON = {}));
  76586. //# sourceMappingURL=babylon.proceduralTextureSceneComponent.js.map
  76587. var BABYLON;
  76588. (function (BABYLON) {
  76589. var CustomProceduralTexture = /** @class */ (function (_super) {
  76590. __extends(CustomProceduralTexture, _super);
  76591. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  76592. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  76593. _this._animate = true;
  76594. _this._time = 0;
  76595. _this._texturePath = texturePath;
  76596. //Try to load json
  76597. _this.loadJson(texturePath);
  76598. _this.refreshRate = 1;
  76599. return _this;
  76600. }
  76601. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  76602. var _this = this;
  76603. var noConfigFile = function () {
  76604. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  76605. try {
  76606. _this.setFragment(_this._texturePath);
  76607. }
  76608. catch (ex) {
  76609. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  76610. }
  76611. };
  76612. var configFileUrl = jsonUrl + "/config.json";
  76613. var xhr = new XMLHttpRequest();
  76614. xhr.open("GET", configFileUrl, true);
  76615. xhr.addEventListener("load", function () {
  76616. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  76617. try {
  76618. _this._config = JSON.parse(xhr.response);
  76619. _this.updateShaderUniforms();
  76620. _this.updateTextures();
  76621. _this.setFragment(_this._texturePath + "/custom");
  76622. _this._animate = _this._config.animate;
  76623. _this.refreshRate = _this._config.refreshrate;
  76624. }
  76625. catch (ex) {
  76626. noConfigFile();
  76627. }
  76628. }
  76629. else {
  76630. noConfigFile();
  76631. }
  76632. }, false);
  76633. xhr.addEventListener("error", function () {
  76634. noConfigFile();
  76635. }, false);
  76636. try {
  76637. xhr.send();
  76638. }
  76639. catch (ex) {
  76640. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  76641. }
  76642. };
  76643. CustomProceduralTexture.prototype.isReady = function () {
  76644. if (!_super.prototype.isReady.call(this)) {
  76645. return false;
  76646. }
  76647. for (var name in this._textures) {
  76648. var texture = this._textures[name];
  76649. if (!texture.isReady()) {
  76650. return false;
  76651. }
  76652. }
  76653. return true;
  76654. };
  76655. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  76656. var scene = this.getScene();
  76657. if (this._animate && scene) {
  76658. this._time += scene.getAnimationRatio() * 0.03;
  76659. this.updateShaderUniforms();
  76660. }
  76661. _super.prototype.render.call(this, useCameraPostProcess);
  76662. };
  76663. CustomProceduralTexture.prototype.updateTextures = function () {
  76664. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  76665. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  76666. }
  76667. };
  76668. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  76669. if (this._config) {
  76670. for (var j = 0; j < this._config.uniforms.length; j++) {
  76671. var uniform = this._config.uniforms[j];
  76672. switch (uniform.type) {
  76673. case "float":
  76674. this.setFloat(uniform.name, uniform.value);
  76675. break;
  76676. case "color3":
  76677. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  76678. break;
  76679. case "color4":
  76680. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  76681. break;
  76682. case "vector2":
  76683. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  76684. break;
  76685. case "vector3":
  76686. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  76687. break;
  76688. }
  76689. }
  76690. }
  76691. this.setFloat("time", this._time);
  76692. };
  76693. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  76694. get: function () {
  76695. return this._animate;
  76696. },
  76697. set: function (value) {
  76698. this._animate = value;
  76699. },
  76700. enumerable: true,
  76701. configurable: true
  76702. });
  76703. return CustomProceduralTexture;
  76704. }(BABYLON.ProceduralTexture));
  76705. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  76706. })(BABYLON || (BABYLON = {}));
  76707. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  76708. var BABYLON;
  76709. (function (BABYLON) {
  76710. /**
  76711. * Manage the gamepad inputs to control a free camera.
  76712. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  76713. */
  76714. var FreeCameraGamepadInput = /** @class */ (function () {
  76715. function FreeCameraGamepadInput() {
  76716. /**
  76717. * Defines the gamepad rotation sensiblity.
  76718. * This is the threshold from when rotation starts to be accounted for to prevent jittering.
  76719. */
  76720. this.gamepadAngularSensibility = 200;
  76721. /**
  76722. * Defines the gamepad move sensiblity.
  76723. * This is the threshold from when moving starts to be accounted for for to prevent jittering.
  76724. */
  76725. this.gamepadMoveSensibility = 40;
  76726. this._cameraTransform = BABYLON.Matrix.Identity();
  76727. this._deltaTransform = BABYLON.Vector3.Zero();
  76728. this._vector3 = BABYLON.Vector3.Zero();
  76729. this._vector2 = BABYLON.Vector2.Zero();
  76730. }
  76731. /**
  76732. * Attach the input controls to a specific dom element to get the input from.
  76733. * @param element Defines the element the controls should be listened from
  76734. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  76735. */
  76736. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  76737. var _this = this;
  76738. var manager = this.camera.getScene().gamepadManager;
  76739. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  76740. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  76741. // prioritize XBOX gamepads.
  76742. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  76743. _this.gamepad = gamepad;
  76744. }
  76745. }
  76746. });
  76747. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  76748. if (_this.gamepad === gamepad) {
  76749. _this.gamepad = null;
  76750. }
  76751. });
  76752. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  76753. };
  76754. /**
  76755. * Detach the current controls from the specified dom element.
  76756. * @param element Defines the element to stop listening the inputs from
  76757. */
  76758. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  76759. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  76760. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  76761. this.gamepad = null;
  76762. };
  76763. /**
  76764. * Update the current camera state depending on the inputs that have been used this frame.
  76765. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
  76766. */
  76767. FreeCameraGamepadInput.prototype.checkInputs = function () {
  76768. if (this.gamepad && this.gamepad.leftStick) {
  76769. var camera = this.camera;
  76770. var LSValues = this.gamepad.leftStick;
  76771. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  76772. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  76773. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  76774. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  76775. var RSValues = this.gamepad.rightStick;
  76776. if (RSValues) {
  76777. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  76778. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  76779. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  76780. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  76781. }
  76782. else {
  76783. RSValues = { x: 0, y: 0 };
  76784. }
  76785. if (!camera.rotationQuaternion) {
  76786. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  76787. }
  76788. else {
  76789. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  76790. }
  76791. var speed = camera._computeLocalCameraSpeed() * 50.0;
  76792. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  76793. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  76794. camera.cameraDirection.addInPlace(this._deltaTransform);
  76795. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  76796. camera.cameraRotation.addInPlace(this._vector2);
  76797. }
  76798. };
  76799. /**
  76800. * Gets the class name of the current intput.
  76801. * @returns the class name
  76802. */
  76803. FreeCameraGamepadInput.prototype.getClassName = function () {
  76804. return "FreeCameraGamepadInput";
  76805. };
  76806. /**
  76807. * Get the friendly name associated with the input class.
  76808. * @returns the input friendly name
  76809. */
  76810. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  76811. return "gamepad";
  76812. };
  76813. __decorate([
  76814. BABYLON.serialize()
  76815. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  76816. __decorate([
  76817. BABYLON.serialize()
  76818. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  76819. return FreeCameraGamepadInput;
  76820. }());
  76821. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  76822. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  76823. })(BABYLON || (BABYLON = {}));
  76824. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  76825. var BABYLON;
  76826. (function (BABYLON) {
  76827. /**
  76828. * Manage the gamepad inputs to control an arc rotate camera.
  76829. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  76830. */
  76831. var ArcRotateCameraGamepadInput = /** @class */ (function () {
  76832. function ArcRotateCameraGamepadInput() {
  76833. /**
  76834. * Defines the gamepad rotation sensiblity.
  76835. * This is the threshold from when rotation starts to be accounted for to prevent jittering.
  76836. */
  76837. this.gamepadRotationSensibility = 80;
  76838. /**
  76839. * Defines the gamepad move sensiblity.
  76840. * This is the threshold from when moving starts to be accounted for for to prevent jittering.
  76841. */
  76842. this.gamepadMoveSensibility = 40;
  76843. }
  76844. /**
  76845. * Attach the input controls to a specific dom element to get the input from.
  76846. * @param element Defines the element the controls should be listened from
  76847. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  76848. */
  76849. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  76850. var _this = this;
  76851. var manager = this.camera.getScene().gamepadManager;
  76852. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  76853. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  76854. // prioritize XBOX gamepads.
  76855. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  76856. _this.gamepad = gamepad;
  76857. }
  76858. }
  76859. });
  76860. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  76861. if (_this.gamepad === gamepad) {
  76862. _this.gamepad = null;
  76863. }
  76864. });
  76865. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  76866. };
  76867. /**
  76868. * Detach the current controls from the specified dom element.
  76869. * @param element Defines the element to stop listening the inputs from
  76870. */
  76871. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  76872. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  76873. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  76874. this.gamepad = null;
  76875. };
  76876. /**
  76877. * Update the current camera state depending on the inputs that have been used this frame.
  76878. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
  76879. */
  76880. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  76881. if (this.gamepad) {
  76882. var camera = this.camera;
  76883. var RSValues = this.gamepad.rightStick;
  76884. if (RSValues) {
  76885. if (RSValues.x != 0) {
  76886. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  76887. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  76888. camera.inertialAlphaOffset += normalizedRX;
  76889. }
  76890. }
  76891. if (RSValues.y != 0) {
  76892. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  76893. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  76894. camera.inertialBetaOffset += normalizedRY;
  76895. }
  76896. }
  76897. }
  76898. var LSValues = this.gamepad.leftStick;
  76899. if (LSValues && LSValues.y != 0) {
  76900. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  76901. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  76902. this.camera.inertialRadiusOffset -= normalizedLY;
  76903. }
  76904. }
  76905. }
  76906. };
  76907. /**
  76908. * Gets the class name of the current intput.
  76909. * @returns the class name
  76910. */
  76911. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  76912. return "ArcRotateCameraGamepadInput";
  76913. };
  76914. /**
  76915. * Get the friendly name associated with the input class.
  76916. * @returns the input friendly name
  76917. */
  76918. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  76919. return "gamepad";
  76920. };
  76921. __decorate([
  76922. BABYLON.serialize()
  76923. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  76924. __decorate([
  76925. BABYLON.serialize()
  76926. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  76927. return ArcRotateCameraGamepadInput;
  76928. }());
  76929. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  76930. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  76931. })(BABYLON || (BABYLON = {}));
  76932. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  76933. var BABYLON;
  76934. (function (BABYLON) {
  76935. var GamepadManager = /** @class */ (function () {
  76936. function GamepadManager(_scene) {
  76937. var _this = this;
  76938. this._scene = _scene;
  76939. this._babylonGamepads = [];
  76940. this._oneGamepadConnected = false;
  76941. /** @hidden */
  76942. this._isMonitoring = false;
  76943. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  76944. if (!BABYLON.Tools.IsWindowObjectExist()) {
  76945. this._gamepadEventSupported = false;
  76946. }
  76947. else {
  76948. this._gamepadEventSupported = 'GamepadEvent' in window;
  76949. this._gamepadSupport = (navigator.getGamepads ||
  76950. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  76951. }
  76952. this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {
  76953. // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected
  76954. for (var i in _this._babylonGamepads) {
  76955. var gamepad = _this._babylonGamepads[i];
  76956. if (gamepad && gamepad._isConnected) {
  76957. _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
  76958. }
  76959. }
  76960. });
  76961. this._onGamepadConnectedEvent = function (evt) {
  76962. var gamepad = evt.gamepad;
  76963. if (gamepad.index in _this._babylonGamepads) {
  76964. if (_this._babylonGamepads[gamepad.index].isConnected) {
  76965. return;
  76966. }
  76967. }
  76968. var newGamepad;
  76969. if (_this._babylonGamepads[gamepad.index]) {
  76970. newGamepad = _this._babylonGamepads[gamepad.index];
  76971. newGamepad.browserGamepad = gamepad;
  76972. newGamepad._isConnected = true;
  76973. }
  76974. else {
  76975. newGamepad = _this._addNewGamepad(gamepad);
  76976. }
  76977. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  76978. _this._startMonitoringGamepads();
  76979. };
  76980. this._onGamepadDisconnectedEvent = function (evt) {
  76981. var gamepad = evt.gamepad;
  76982. // Remove the gamepad from the list of gamepads to monitor.
  76983. for (var i in _this._babylonGamepads) {
  76984. if (_this._babylonGamepads[i].index === gamepad.index) {
  76985. var disconnectedGamepad = _this._babylonGamepads[i];
  76986. disconnectedGamepad._isConnected = false;
  76987. _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
  76988. break;
  76989. }
  76990. }
  76991. };
  76992. if (this._gamepadSupport) {
  76993. //first add already-connected gamepads
  76994. this._updateGamepadObjects();
  76995. if (this._babylonGamepads.length) {
  76996. this._startMonitoringGamepads();
  76997. }
  76998. // Checking if the gamepad connected event is supported (like in Firefox)
  76999. if (this._gamepadEventSupported) {
  77000. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  77001. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  77002. }
  77003. else {
  77004. this._startMonitoringGamepads();
  77005. }
  77006. }
  77007. }
  77008. Object.defineProperty(GamepadManager.prototype, "gamepads", {
  77009. get: function () {
  77010. return this._babylonGamepads;
  77011. },
  77012. enumerable: true,
  77013. configurable: true
  77014. });
  77015. GamepadManager.prototype.getGamepadByType = function (type) {
  77016. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  77017. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  77018. var gamepad = _a[_i];
  77019. if (gamepad && gamepad.type === type) {
  77020. return gamepad;
  77021. }
  77022. }
  77023. return null;
  77024. };
  77025. GamepadManager.prototype.dispose = function () {
  77026. if (this._gamepadEventSupported) {
  77027. if (this._onGamepadConnectedEvent) {
  77028. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  77029. }
  77030. if (this._onGamepadDisconnectedEvent) {
  77031. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  77032. }
  77033. this._onGamepadConnectedEvent = null;
  77034. this._onGamepadDisconnectedEvent = null;
  77035. }
  77036. this._babylonGamepads.forEach(function (gamepad) {
  77037. gamepad.dispose();
  77038. });
  77039. this.onGamepadConnectedObservable.clear();
  77040. this.onGamepadDisconnectedObservable.clear();
  77041. this._oneGamepadConnected = false;
  77042. this._stopMonitoringGamepads();
  77043. this._babylonGamepads = [];
  77044. };
  77045. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  77046. if (!this._oneGamepadConnected) {
  77047. this._oneGamepadConnected = true;
  77048. }
  77049. var newGamepad;
  77050. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  77051. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  77052. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  77053. }
  77054. // if pose is supported, use the (WebVR) pose enabled controller
  77055. else if (gamepad.pose) {
  77056. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  77057. }
  77058. else {
  77059. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  77060. }
  77061. this._babylonGamepads[newGamepad.index] = newGamepad;
  77062. return newGamepad;
  77063. };
  77064. GamepadManager.prototype._startMonitoringGamepads = function () {
  77065. if (!this._isMonitoring) {
  77066. this._isMonitoring = true;
  77067. //back-comp
  77068. if (!this._scene) {
  77069. this._checkGamepadsStatus();
  77070. }
  77071. }
  77072. };
  77073. GamepadManager.prototype._stopMonitoringGamepads = function () {
  77074. this._isMonitoring = false;
  77075. };
  77076. /** @hidden */
  77077. GamepadManager.prototype._checkGamepadsStatus = function () {
  77078. var _this = this;
  77079. // Hack to be compatible Chrome
  77080. this._updateGamepadObjects();
  77081. for (var i in this._babylonGamepads) {
  77082. var gamepad = this._babylonGamepads[i];
  77083. if (!gamepad || !gamepad.isConnected) {
  77084. continue;
  77085. }
  77086. gamepad.update();
  77087. }
  77088. if (this._isMonitoring && !this._scene) {
  77089. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  77090. }
  77091. };
  77092. // This function is called only on Chrome, which does not properly support
  77093. // connection/disconnection events and forces you to recopy again the gamepad object
  77094. GamepadManager.prototype._updateGamepadObjects = function () {
  77095. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  77096. for (var i = 0; i < gamepads.length; i++) {
  77097. var gamepad = gamepads[i];
  77098. if (gamepad) {
  77099. if (!this._babylonGamepads[gamepad.index]) {
  77100. var newGamepad = this._addNewGamepad(gamepad);
  77101. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  77102. }
  77103. else {
  77104. // Forced to copy again this object for Chrome for unknown reason
  77105. this._babylonGamepads[i].browserGamepad = gamepad;
  77106. if (!this._babylonGamepads[i].isConnected) {
  77107. this._babylonGamepads[i]._isConnected = true;
  77108. this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
  77109. }
  77110. }
  77111. }
  77112. }
  77113. };
  77114. return GamepadManager;
  77115. }());
  77116. BABYLON.GamepadManager = GamepadManager;
  77117. })(BABYLON || (BABYLON = {}));
  77118. //# sourceMappingURL=babylon.gamepadManager.js.map
  77119. var BABYLON;
  77120. (function (BABYLON) {
  77121. var StickValues = /** @class */ (function () {
  77122. function StickValues(x, y) {
  77123. this.x = x;
  77124. this.y = y;
  77125. }
  77126. return StickValues;
  77127. }());
  77128. BABYLON.StickValues = StickValues;
  77129. var Gamepad = /** @class */ (function () {
  77130. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  77131. if (leftStickX === void 0) { leftStickX = 0; }
  77132. if (leftStickY === void 0) { leftStickY = 1; }
  77133. if (rightStickX === void 0) { rightStickX = 2; }
  77134. if (rightStickY === void 0) { rightStickY = 3; }
  77135. this.id = id;
  77136. this.index = index;
  77137. this.browserGamepad = browserGamepad;
  77138. this._leftStick = { x: 0, y: 0 };
  77139. this._rightStick = { x: 0, y: 0 };
  77140. /** @hidden */
  77141. this._isConnected = true;
  77142. this._invertLeftStickY = false;
  77143. this.type = Gamepad.GAMEPAD;
  77144. this._leftStickAxisX = leftStickX;
  77145. this._leftStickAxisY = leftStickY;
  77146. this._rightStickAxisX = rightStickX;
  77147. this._rightStickAxisY = rightStickY;
  77148. if (this.browserGamepad.axes.length >= 2) {
  77149. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  77150. }
  77151. if (this.browserGamepad.axes.length >= 4) {
  77152. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  77153. }
  77154. }
  77155. Object.defineProperty(Gamepad.prototype, "isConnected", {
  77156. get: function () {
  77157. return this._isConnected;
  77158. },
  77159. enumerable: true,
  77160. configurable: true
  77161. });
  77162. Gamepad.prototype.onleftstickchanged = function (callback) {
  77163. this._onleftstickchanged = callback;
  77164. };
  77165. Gamepad.prototype.onrightstickchanged = function (callback) {
  77166. this._onrightstickchanged = callback;
  77167. };
  77168. Object.defineProperty(Gamepad.prototype, "leftStick", {
  77169. get: function () {
  77170. return this._leftStick;
  77171. },
  77172. set: function (newValues) {
  77173. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  77174. this._onleftstickchanged(newValues);
  77175. }
  77176. this._leftStick = newValues;
  77177. },
  77178. enumerable: true,
  77179. configurable: true
  77180. });
  77181. Object.defineProperty(Gamepad.prototype, "rightStick", {
  77182. get: function () {
  77183. return this._rightStick;
  77184. },
  77185. set: function (newValues) {
  77186. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  77187. this._onrightstickchanged(newValues);
  77188. }
  77189. this._rightStick = newValues;
  77190. },
  77191. enumerable: true,
  77192. configurable: true
  77193. });
  77194. Gamepad.prototype.update = function () {
  77195. if (this._leftStick) {
  77196. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  77197. if (this._invertLeftStickY) {
  77198. this.leftStick.y *= -1;
  77199. }
  77200. }
  77201. if (this._rightStick) {
  77202. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  77203. }
  77204. };
  77205. Gamepad.prototype.dispose = function () {
  77206. };
  77207. Gamepad.GAMEPAD = 0;
  77208. Gamepad.GENERIC = 1;
  77209. Gamepad.XBOX = 2;
  77210. Gamepad.POSE_ENABLED = 3;
  77211. return Gamepad;
  77212. }());
  77213. BABYLON.Gamepad = Gamepad;
  77214. var GenericPad = /** @class */ (function (_super) {
  77215. __extends(GenericPad, _super);
  77216. function GenericPad(id, index, browserGamepad) {
  77217. var _this = _super.call(this, id, index, browserGamepad) || this;
  77218. _this.onButtonDownObservable = new BABYLON.Observable();
  77219. _this.onButtonUpObservable = new BABYLON.Observable();
  77220. _this.type = Gamepad.GENERIC;
  77221. _this._buttons = new Array(browserGamepad.buttons.length);
  77222. return _this;
  77223. }
  77224. GenericPad.prototype.onbuttondown = function (callback) {
  77225. this._onbuttondown = callback;
  77226. };
  77227. GenericPad.prototype.onbuttonup = function (callback) {
  77228. this._onbuttonup = callback;
  77229. };
  77230. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  77231. if (newValue !== currentValue) {
  77232. if (newValue === 1) {
  77233. if (this._onbuttondown) {
  77234. this._onbuttondown(buttonIndex);
  77235. }
  77236. this.onButtonDownObservable.notifyObservers(buttonIndex);
  77237. }
  77238. if (newValue === 0) {
  77239. if (this._onbuttonup) {
  77240. this._onbuttonup(buttonIndex);
  77241. }
  77242. this.onButtonUpObservable.notifyObservers(buttonIndex);
  77243. }
  77244. }
  77245. return newValue;
  77246. };
  77247. GenericPad.prototype.update = function () {
  77248. _super.prototype.update.call(this);
  77249. for (var index = 0; index < this._buttons.length; index++) {
  77250. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  77251. }
  77252. };
  77253. GenericPad.prototype.dispose = function () {
  77254. _super.prototype.dispose.call(this);
  77255. this.onButtonDownObservable.clear();
  77256. this.onButtonUpObservable.clear();
  77257. };
  77258. return GenericPad;
  77259. }(Gamepad));
  77260. BABYLON.GenericPad = GenericPad;
  77261. })(BABYLON || (BABYLON = {}));
  77262. //# sourceMappingURL=babylon.gamepad.js.map
  77263. var BABYLON;
  77264. (function (BABYLON) {
  77265. /**
  77266. * Defines supported buttons for XBox360 compatible gamepads
  77267. */
  77268. var Xbox360Button;
  77269. (function (Xbox360Button) {
  77270. /** A */
  77271. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  77272. /** B */
  77273. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  77274. /** X */
  77275. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  77276. /** Y */
  77277. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  77278. /** Start */
  77279. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  77280. /** Back */
  77281. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  77282. /** Left button */
  77283. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  77284. /** Right button */
  77285. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  77286. /** Left stick */
  77287. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  77288. /** Right stick */
  77289. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  77290. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  77291. /** Defines values for XBox360 DPad */
  77292. var Xbox360Dpad;
  77293. (function (Xbox360Dpad) {
  77294. /** Up */
  77295. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  77296. /** Down */
  77297. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  77298. /** Left */
  77299. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  77300. /** Right */
  77301. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  77302. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  77303. /**
  77304. * Defines a XBox360 gamepad
  77305. */
  77306. var Xbox360Pad = /** @class */ (function (_super) {
  77307. __extends(Xbox360Pad, _super);
  77308. /**
  77309. * Creates a new XBox360 gamepad object
  77310. * @param id defines the id of this gamepad
  77311. * @param index defines its index
  77312. * @param gamepad defines the internal HTML gamepad object
  77313. * @param xboxOne defines if it is a XBox One gamepad
  77314. */
  77315. function Xbox360Pad(id, index, gamepad, xboxOne) {
  77316. if (xboxOne === void 0) { xboxOne = false; }
  77317. var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;
  77318. _this._leftTrigger = 0;
  77319. _this._rightTrigger = 0;
  77320. /** Observable raised when a button is pressed */
  77321. _this.onButtonDownObservable = new BABYLON.Observable();
  77322. /** Observable raised when a button is released */
  77323. _this.onButtonUpObservable = new BABYLON.Observable();
  77324. /** Observable raised when a pad is pressed */
  77325. _this.onPadDownObservable = new BABYLON.Observable();
  77326. /** Observable raised when a pad is released */
  77327. _this.onPadUpObservable = new BABYLON.Observable();
  77328. _this._buttonA = 0;
  77329. _this._buttonB = 0;
  77330. _this._buttonX = 0;
  77331. _this._buttonY = 0;
  77332. _this._buttonBack = 0;
  77333. _this._buttonStart = 0;
  77334. _this._buttonLB = 0;
  77335. _this._buttonRB = 0;
  77336. _this._buttonLeftStick = 0;
  77337. _this._buttonRightStick = 0;
  77338. _this._dPadUp = 0;
  77339. _this._dPadDown = 0;
  77340. _this._dPadLeft = 0;
  77341. _this._dPadRight = 0;
  77342. _this._isXboxOnePad = false;
  77343. _this.type = BABYLON.Gamepad.XBOX;
  77344. _this._isXboxOnePad = xboxOne;
  77345. return _this;
  77346. }
  77347. /**
  77348. * Defines the callback to call when left trigger is pressed
  77349. * @param callback defines the callback to use
  77350. */
  77351. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  77352. this._onlefttriggerchanged = callback;
  77353. };
  77354. /**
  77355. * Defines the callback to call when right trigger is pressed
  77356. * @param callback defines the callback to use
  77357. */
  77358. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  77359. this._onrighttriggerchanged = callback;
  77360. };
  77361. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  77362. /**
  77363. * Gets or sets left trigger value
  77364. */
  77365. get: function () {
  77366. return this._leftTrigger;
  77367. },
  77368. set: function (newValue) {
  77369. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  77370. this._onlefttriggerchanged(newValue);
  77371. }
  77372. this._leftTrigger = newValue;
  77373. },
  77374. enumerable: true,
  77375. configurable: true
  77376. });
  77377. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  77378. /**
  77379. * Gets or sets right trigger value
  77380. */
  77381. get: function () {
  77382. return this._rightTrigger;
  77383. },
  77384. set: function (newValue) {
  77385. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  77386. this._onrighttriggerchanged(newValue);
  77387. }
  77388. this._rightTrigger = newValue;
  77389. },
  77390. enumerable: true,
  77391. configurable: true
  77392. });
  77393. /**
  77394. * Defines the callback to call when a button is pressed
  77395. * @param callback defines the callback to use
  77396. */
  77397. Xbox360Pad.prototype.onbuttondown = function (callback) {
  77398. this._onbuttondown = callback;
  77399. };
  77400. /**
  77401. * Defines the callback to call when a button is released
  77402. * @param callback defines the callback to use
  77403. */
  77404. Xbox360Pad.prototype.onbuttonup = function (callback) {
  77405. this._onbuttonup = callback;
  77406. };
  77407. /**
  77408. * Defines the callback to call when a pad is pressed
  77409. * @param callback defines the callback to use
  77410. */
  77411. Xbox360Pad.prototype.ondpaddown = function (callback) {
  77412. this._ondpaddown = callback;
  77413. };
  77414. /**
  77415. * Defines the callback to call when a pad is released
  77416. * @param callback defines the callback to use
  77417. */
  77418. Xbox360Pad.prototype.ondpadup = function (callback) {
  77419. this._ondpadup = callback;
  77420. };
  77421. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  77422. if (newValue !== currentValue) {
  77423. if (newValue === 1) {
  77424. if (this._onbuttondown) {
  77425. this._onbuttondown(buttonType);
  77426. }
  77427. this.onButtonDownObservable.notifyObservers(buttonType);
  77428. }
  77429. if (newValue === 0) {
  77430. if (this._onbuttonup) {
  77431. this._onbuttonup(buttonType);
  77432. }
  77433. this.onButtonUpObservable.notifyObservers(buttonType);
  77434. }
  77435. }
  77436. return newValue;
  77437. };
  77438. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  77439. if (newValue !== currentValue) {
  77440. if (newValue === 1) {
  77441. if (this._ondpaddown) {
  77442. this._ondpaddown(buttonType);
  77443. }
  77444. this.onPadDownObservable.notifyObservers(buttonType);
  77445. }
  77446. if (newValue === 0) {
  77447. if (this._ondpadup) {
  77448. this._ondpadup(buttonType);
  77449. }
  77450. this.onPadUpObservable.notifyObservers(buttonType);
  77451. }
  77452. }
  77453. return newValue;
  77454. };
  77455. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  77456. /** Gets or sets value of A button */
  77457. get: function () {
  77458. return this._buttonA;
  77459. },
  77460. set: function (value) {
  77461. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  77462. },
  77463. enumerable: true,
  77464. configurable: true
  77465. });
  77466. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  77467. /** Gets or sets value of B button */
  77468. get: function () {
  77469. return this._buttonB;
  77470. },
  77471. set: function (value) {
  77472. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  77473. },
  77474. enumerable: true,
  77475. configurable: true
  77476. });
  77477. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  77478. /** Gets or sets value of X button */
  77479. get: function () {
  77480. return this._buttonX;
  77481. },
  77482. set: function (value) {
  77483. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  77484. },
  77485. enumerable: true,
  77486. configurable: true
  77487. });
  77488. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  77489. /** Gets or sets value of Y button */
  77490. get: function () {
  77491. return this._buttonY;
  77492. },
  77493. set: function (value) {
  77494. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  77495. },
  77496. enumerable: true,
  77497. configurable: true
  77498. });
  77499. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  77500. /** Gets or sets value of Start button */
  77501. get: function () {
  77502. return this._buttonStart;
  77503. },
  77504. set: function (value) {
  77505. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  77506. },
  77507. enumerable: true,
  77508. configurable: true
  77509. });
  77510. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  77511. /** Gets or sets value of Back button */
  77512. get: function () {
  77513. return this._buttonBack;
  77514. },
  77515. set: function (value) {
  77516. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  77517. },
  77518. enumerable: true,
  77519. configurable: true
  77520. });
  77521. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  77522. /** Gets or sets value of Left button */
  77523. get: function () {
  77524. return this._buttonLB;
  77525. },
  77526. set: function (value) {
  77527. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  77528. },
  77529. enumerable: true,
  77530. configurable: true
  77531. });
  77532. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  77533. /** Gets or sets value of Right button */
  77534. get: function () {
  77535. return this._buttonRB;
  77536. },
  77537. set: function (value) {
  77538. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  77539. },
  77540. enumerable: true,
  77541. configurable: true
  77542. });
  77543. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  77544. /** Gets or sets value of left stick */
  77545. get: function () {
  77546. return this._buttonLeftStick;
  77547. },
  77548. set: function (value) {
  77549. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  77550. },
  77551. enumerable: true,
  77552. configurable: true
  77553. });
  77554. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  77555. /** Gets or sets value of right stick */
  77556. get: function () {
  77557. return this._buttonRightStick;
  77558. },
  77559. set: function (value) {
  77560. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  77561. },
  77562. enumerable: true,
  77563. configurable: true
  77564. });
  77565. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  77566. /** Gets or sets value of DPad up */
  77567. get: function () {
  77568. return this._dPadUp;
  77569. },
  77570. set: function (value) {
  77571. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  77572. },
  77573. enumerable: true,
  77574. configurable: true
  77575. });
  77576. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  77577. /** Gets or sets value of DPad down */
  77578. get: function () {
  77579. return this._dPadDown;
  77580. },
  77581. set: function (value) {
  77582. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  77583. },
  77584. enumerable: true,
  77585. configurable: true
  77586. });
  77587. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  77588. /** Gets or sets value of DPad left */
  77589. get: function () {
  77590. return this._dPadLeft;
  77591. },
  77592. set: function (value) {
  77593. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  77594. },
  77595. enumerable: true,
  77596. configurable: true
  77597. });
  77598. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  77599. /** Gets or sets value of DPad right */
  77600. get: function () {
  77601. return this._dPadRight;
  77602. },
  77603. set: function (value) {
  77604. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  77605. },
  77606. enumerable: true,
  77607. configurable: true
  77608. });
  77609. /**
  77610. * Force the gamepad to synchronize with device values
  77611. */
  77612. Xbox360Pad.prototype.update = function () {
  77613. _super.prototype.update.call(this);
  77614. if (this._isXboxOnePad) {
  77615. this.buttonA = this.browserGamepad.buttons[0].value;
  77616. this.buttonB = this.browserGamepad.buttons[1].value;
  77617. this.buttonX = this.browserGamepad.buttons[2].value;
  77618. this.buttonY = this.browserGamepad.buttons[3].value;
  77619. this.buttonLB = this.browserGamepad.buttons[4].value;
  77620. this.buttonRB = this.browserGamepad.buttons[5].value;
  77621. this.leftTrigger = this.browserGamepad.axes[2];
  77622. this.rightTrigger = this.browserGamepad.axes[5];
  77623. this.buttonBack = this.browserGamepad.buttons[9].value;
  77624. this.buttonStart = this.browserGamepad.buttons[8].value;
  77625. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  77626. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  77627. this.dPadUp = this.browserGamepad.buttons[11].value;
  77628. this.dPadDown = this.browserGamepad.buttons[12].value;
  77629. this.dPadLeft = this.browserGamepad.buttons[13].value;
  77630. this.dPadRight = this.browserGamepad.buttons[14].value;
  77631. }
  77632. else {
  77633. this.buttonA = this.browserGamepad.buttons[0].value;
  77634. this.buttonB = this.browserGamepad.buttons[1].value;
  77635. this.buttonX = this.browserGamepad.buttons[2].value;
  77636. this.buttonY = this.browserGamepad.buttons[3].value;
  77637. this.buttonLB = this.browserGamepad.buttons[4].value;
  77638. this.buttonRB = this.browserGamepad.buttons[5].value;
  77639. this.leftTrigger = this.browserGamepad.buttons[6].value;
  77640. this.rightTrigger = this.browserGamepad.buttons[7].value;
  77641. this.buttonBack = this.browserGamepad.buttons[8].value;
  77642. this.buttonStart = this.browserGamepad.buttons[9].value;
  77643. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  77644. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  77645. this.dPadUp = this.browserGamepad.buttons[12].value;
  77646. this.dPadDown = this.browserGamepad.buttons[13].value;
  77647. this.dPadLeft = this.browserGamepad.buttons[14].value;
  77648. this.dPadRight = this.browserGamepad.buttons[15].value;
  77649. }
  77650. };
  77651. Xbox360Pad.prototype.dispose = function () {
  77652. _super.prototype.dispose.call(this);
  77653. this.onButtonDownObservable.clear();
  77654. this.onButtonUpObservable.clear();
  77655. this.onPadDownObservable.clear();
  77656. this.onPadUpObservable.clear();
  77657. };
  77658. return Xbox360Pad;
  77659. }(BABYLON.Gamepad));
  77660. BABYLON.Xbox360Pad = Xbox360Pad;
  77661. })(BABYLON || (BABYLON = {}));
  77662. //# sourceMappingURL=babylon.xboxGamepad.js.map
  77663. var BABYLON;
  77664. (function (BABYLON) {
  77665. /**
  77666. * Defines the types of pose enabled controllers that are supported
  77667. */
  77668. var PoseEnabledControllerType;
  77669. (function (PoseEnabledControllerType) {
  77670. /**
  77671. * HTC Vive
  77672. */
  77673. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  77674. /**
  77675. * Oculus Rift
  77676. */
  77677. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  77678. /**
  77679. * Windows mixed reality
  77680. */
  77681. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  77682. /**
  77683. * Samsung gear VR
  77684. */
  77685. PoseEnabledControllerType[PoseEnabledControllerType["GEAR_VR"] = 3] = "GEAR_VR";
  77686. /**
  77687. * Google Daydream
  77688. */
  77689. PoseEnabledControllerType[PoseEnabledControllerType["DAYDREAM"] = 4] = "DAYDREAM";
  77690. /**
  77691. * Generic
  77692. */
  77693. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 5] = "GENERIC";
  77694. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  77695. /**
  77696. * Defines the PoseEnabledControllerHelper object that is used initialize a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  77697. */
  77698. var PoseEnabledControllerHelper = /** @class */ (function () {
  77699. function PoseEnabledControllerHelper() {
  77700. }
  77701. /**
  77702. * Initializes a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  77703. * @param vrGamepad the gamepad to initialized
  77704. * @returns a vr controller of the type the gamepad identified as
  77705. */
  77706. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  77707. // Oculus Touch
  77708. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  77709. return new BABYLON.OculusTouchController(vrGamepad);
  77710. }
  77711. // Windows Mixed Reality controllers
  77712. else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  77713. return new BABYLON.WindowsMotionController(vrGamepad);
  77714. }
  77715. // HTC Vive
  77716. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  77717. return new BABYLON.ViveController(vrGamepad);
  77718. }
  77719. // Samsung/Oculus Gear VR or Oculus Go
  77720. else if (vrGamepad.id.indexOf(BABYLON.GearVRController.GAMEPAD_ID_PREFIX) === 0 || vrGamepad.id.indexOf('Oculus Go') !== -1) {
  77721. return new BABYLON.GearVRController(vrGamepad);
  77722. }
  77723. // Google Daydream
  77724. else if (vrGamepad.id.indexOf(BABYLON.DaydreamController.GAMEPAD_ID_PREFIX) === 0) {
  77725. return new BABYLON.DaydreamController(vrGamepad);
  77726. }
  77727. // Generic
  77728. else {
  77729. return new BABYLON.GenericController(vrGamepad);
  77730. }
  77731. };
  77732. return PoseEnabledControllerHelper;
  77733. }());
  77734. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  77735. /**
  77736. * Defines the PoseEnabledController object that contains state of a vr capable controller
  77737. */
  77738. var PoseEnabledController = /** @class */ (function (_super) {
  77739. __extends(PoseEnabledController, _super);
  77740. /**
  77741. * Creates a new PoseEnabledController from a gamepad
  77742. * @param browserGamepad the gamepad that the PoseEnabledController should be created from
  77743. */
  77744. function PoseEnabledController(browserGamepad) {
  77745. var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
  77746. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  77747. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  77748. _this._deviceRoomRotationQuaternion = new BABYLON.Quaternion();
  77749. /**
  77750. * The device position in babylon space
  77751. */
  77752. _this.devicePosition = BABYLON.Vector3.Zero();
  77753. /**
  77754. * The device rotation in babylon space
  77755. */
  77756. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  77757. /**
  77758. * The scale factor of the device in babylon space
  77759. */
  77760. _this.deviceScaleFactor = 1;
  77761. // Used to convert 6dof controllers to 3dof
  77762. _this._trackPosition = true;
  77763. _this._maxRotationDistFromHeadset = Math.PI / 5;
  77764. _this._draggedRoomRotation = 0;
  77765. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  77766. /**
  77767. * Internal, matrix used to convert room space to babylon space
  77768. * @hidden
  77769. */
  77770. _this._deviceToWorld = BABYLON.Matrix.Identity();
  77771. /**
  77772. * Node to be used when casting a ray from the controller
  77773. * @hidden
  77774. */
  77775. _this._pointingPoseNode = null;
  77776. _this._workingMatrix = BABYLON.Matrix.Identity();
  77777. /**
  77778. * @hidden
  77779. */
  77780. _this._meshAttachedObservable = new BABYLON.Observable();
  77781. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  77782. _this.controllerType = PoseEnabledControllerType.GENERIC;
  77783. _this.position = BABYLON.Vector3.Zero();
  77784. _this.rotationQuaternion = new BABYLON.Quaternion();
  77785. _this._calculatedPosition = BABYLON.Vector3.Zero();
  77786. _this._calculatedRotation = new BABYLON.Quaternion();
  77787. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  77788. return _this;
  77789. }
  77790. /**
  77791. * @hidden
  77792. */
  77793. PoseEnabledController.prototype._disableTrackPosition = function (fixedPosition) {
  77794. if (this._trackPosition) {
  77795. this._calculatedPosition.copyFrom(fixedPosition);
  77796. this._trackPosition = false;
  77797. }
  77798. };
  77799. /**
  77800. * Updates the state of the pose enbaled controller and mesh based on the current position and rotation of the controller
  77801. */
  77802. PoseEnabledController.prototype.update = function () {
  77803. _super.prototype.update.call(this);
  77804. this._updatePoseAndMesh();
  77805. };
  77806. /**
  77807. * Updates only the pose device and mesh without doing any button event checking
  77808. */
  77809. PoseEnabledController.prototype._updatePoseAndMesh = function () {
  77810. var pose = this.browserGamepad.pose;
  77811. this.updateFromDevice(pose);
  77812. if (!this._trackPosition && BABYLON.Engine.LastCreatedScene && BABYLON.Engine.LastCreatedScene.activeCamera && BABYLON.Engine.LastCreatedScene.activeCamera.devicePosition) {
  77813. var camera = BABYLON.Engine.LastCreatedScene.activeCamera;
  77814. camera._computeDevicePosition();
  77815. this._deviceToWorld.setTranslation(camera.devicePosition);
  77816. if (camera.deviceRotationQuaternion) {
  77817. var camera = camera;
  77818. camera._deviceRoomRotationQuaternion.toEulerAnglesToRef(BABYLON.Tmp.Vector3[0]);
  77819. // Find the radian distance away that the headset is from the controllers rotation
  77820. var distanceAway = Math.atan2(Math.sin(BABYLON.Tmp.Vector3[0].y - this._draggedRoomRotation), Math.cos(BABYLON.Tmp.Vector3[0].y - this._draggedRoomRotation));
  77821. if (Math.abs(distanceAway) > this._maxRotationDistFromHeadset) {
  77822. // Only rotate enouph to be within the _maxRotationDistFromHeadset
  77823. var rotationAmount = distanceAway - (distanceAway < 0 ? -this._maxRotationDistFromHeadset : this._maxRotationDistFromHeadset);
  77824. this._draggedRoomRotation += rotationAmount;
  77825. // Rotate controller around headset
  77826. var sin = Math.sin(-rotationAmount);
  77827. var cos = Math.cos(-rotationAmount);
  77828. this._calculatedPosition.x = this._calculatedPosition.x * cos - this._calculatedPosition.z * sin;
  77829. this._calculatedPosition.z = this._calculatedPosition.x * sin + this._calculatedPosition.z * cos;
  77830. }
  77831. }
  77832. }
  77833. BABYLON.Vector3.TransformCoordinatesToRef(this._calculatedPosition, this._deviceToWorld, this.devicePosition);
  77834. this._deviceToWorld.getRotationMatrixToRef(this._workingMatrix);
  77835. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  77836. this.deviceRotationQuaternion.multiplyInPlace(this._calculatedRotation);
  77837. if (this._mesh) {
  77838. this._mesh.position.copyFrom(this.devicePosition);
  77839. if (this._mesh.rotationQuaternion) {
  77840. this._mesh.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  77841. }
  77842. }
  77843. };
  77844. /**
  77845. * Updates the state of the pose enbaled controller based on the raw pose data from the device
  77846. * @param poseData raw pose fromthe device
  77847. */
  77848. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  77849. if (poseData) {
  77850. this.rawPose = poseData;
  77851. if (poseData.position) {
  77852. this._deviceRoomPosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  77853. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  77854. this._deviceRoomPosition.z *= -1;
  77855. }
  77856. if (this._trackPosition) {
  77857. this._deviceRoomPosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  77858. }
  77859. this._calculatedPosition.addInPlace(this.position);
  77860. }
  77861. var pose = this.rawPose;
  77862. if (poseData.orientation && pose.orientation) {
  77863. this._deviceRoomRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);
  77864. if (this._mesh) {
  77865. if (this._mesh.getScene().useRightHandedSystem) {
  77866. this._deviceRoomRotationQuaternion.z *= -1;
  77867. this._deviceRoomRotationQuaternion.w *= -1;
  77868. }
  77869. else {
  77870. this._deviceRoomRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this._deviceRoomRotationQuaternion);
  77871. }
  77872. }
  77873. // if the camera is set, rotate to the camera's rotation
  77874. this._deviceRoomRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  77875. }
  77876. }
  77877. };
  77878. /**
  77879. * Attaches a mesh to the controller
  77880. * @param mesh the mesh to be attached
  77881. */
  77882. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  77883. if (this._mesh) {
  77884. this._mesh.parent = null;
  77885. }
  77886. this._mesh = mesh;
  77887. if (this._poseControlledCamera) {
  77888. this._mesh.parent = this._poseControlledCamera;
  77889. }
  77890. if (!this._mesh.rotationQuaternion) {
  77891. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  77892. }
  77893. // Sync controller mesh and pointing pose node's state with controller, this is done to avoid a frame where position is 0,0,0 when attaching mesh
  77894. this._updatePoseAndMesh();
  77895. if (this._pointingPoseNode) {
  77896. var parents = [];
  77897. var obj = this._pointingPoseNode;
  77898. while (obj.parent) {
  77899. parents.push(obj.parent);
  77900. obj = obj.parent;
  77901. }
  77902. parents.reverse().forEach(function (p) { p.computeWorldMatrix(true); });
  77903. }
  77904. this._meshAttachedObservable.notifyObservers(mesh);
  77905. };
  77906. /**
  77907. * Attaches the controllers mesh to a camera
  77908. * @param camera the camera the mesh should be attached to
  77909. */
  77910. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  77911. this._poseControlledCamera = camera;
  77912. if (this._mesh) {
  77913. this._mesh.parent = this._poseControlledCamera;
  77914. }
  77915. };
  77916. /**
  77917. * Disposes of the controller
  77918. */
  77919. PoseEnabledController.prototype.dispose = function () {
  77920. if (this._mesh) {
  77921. this._mesh.dispose();
  77922. }
  77923. this._mesh = null;
  77924. _super.prototype.dispose.call(this);
  77925. };
  77926. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  77927. /**
  77928. * The mesh that is attached to the controller
  77929. */
  77930. get: function () {
  77931. return this._mesh;
  77932. },
  77933. enumerable: true,
  77934. configurable: true
  77935. });
  77936. /**
  77937. * Gets the ray of the controller in the direction the controller is pointing
  77938. * @param length the length the resulting ray should be
  77939. * @returns a ray in the direction the controller is pointing
  77940. */
  77941. PoseEnabledController.prototype.getForwardRay = function (length) {
  77942. if (length === void 0) { length = 100; }
  77943. if (!this.mesh) {
  77944. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  77945. }
  77946. var m = this._pointingPoseNode ? this._pointingPoseNode.getWorldMatrix() : this.mesh.getWorldMatrix();
  77947. var origin = m.getTranslation();
  77948. var forward = new BABYLON.Vector3(0, 0, -1);
  77949. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  77950. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  77951. return new BABYLON.Ray(origin, direction, length);
  77952. };
  77953. /**
  77954. * Name of the child mesh that can be used to cast a ray from the controller
  77955. */
  77956. PoseEnabledController.POINTING_POSE = "POINTING_POSE";
  77957. return PoseEnabledController;
  77958. }(BABYLON.Gamepad));
  77959. BABYLON.PoseEnabledController = PoseEnabledController;
  77960. })(BABYLON || (BABYLON = {}));
  77961. //# sourceMappingURL=babylon.poseEnabledController.js.map
  77962. var BABYLON;
  77963. (function (BABYLON) {
  77964. /**
  77965. * Defines the WebVRController object that represents controllers tracked in 3D space
  77966. */
  77967. var WebVRController = /** @class */ (function (_super) {
  77968. __extends(WebVRController, _super);
  77969. /**
  77970. * Creates a new WebVRController from a gamepad
  77971. * @param vrGamepad the gamepad that the WebVRController should be created from
  77972. */
  77973. function WebVRController(vrGamepad) {
  77974. var _this = _super.call(this, vrGamepad) || this;
  77975. // Observables
  77976. /**
  77977. * Fired when the trigger state has changed
  77978. */
  77979. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  77980. /**
  77981. * Fired when the main button state has changed
  77982. */
  77983. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  77984. /**
  77985. * Fired when the secondary button state has changed
  77986. */
  77987. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  77988. /**
  77989. * Fired when the pad state has changed
  77990. */
  77991. _this.onPadStateChangedObservable = new BABYLON.Observable();
  77992. /**
  77993. * Fired when controllers stick values have changed
  77994. */
  77995. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  77996. /**
  77997. * X and Y axis corrisponding to the controllers joystick
  77998. */
  77999. _this.pad = { x: 0, y: 0 };
  78000. // avoid GC, store state in a tmp object
  78001. _this._changes = {
  78002. pressChanged: false,
  78003. touchChanged: false,
  78004. valueChanged: false,
  78005. changed: false
  78006. };
  78007. _this._buttons = new Array(vrGamepad.buttons.length);
  78008. _this.hand = vrGamepad.hand;
  78009. return _this;
  78010. }
  78011. /**
  78012. * Fired when a controller button's state has changed
  78013. * @param callback the callback containing the button that was modified
  78014. */
  78015. WebVRController.prototype.onButtonStateChange = function (callback) {
  78016. this._onButtonStateChange = callback;
  78017. };
  78018. Object.defineProperty(WebVRController.prototype, "defaultModel", {
  78019. /**
  78020. * The default controller model for the controller
  78021. */
  78022. get: function () {
  78023. return this._defaultModel;
  78024. },
  78025. enumerable: true,
  78026. configurable: true
  78027. });
  78028. /**
  78029. * Updates the state of the controller and mesh based on the current position and rotation of the controller
  78030. */
  78031. WebVRController.prototype.update = function () {
  78032. _super.prototype.update.call(this);
  78033. for (var index = 0; index < this._buttons.length; index++) {
  78034. this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
  78035. }
  78036. ;
  78037. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  78038. this.pad.x = this.leftStick.x;
  78039. this.pad.y = this.leftStick.y;
  78040. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  78041. }
  78042. };
  78043. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  78044. if (!newState) {
  78045. newState = {
  78046. pressed: false,
  78047. touched: false,
  78048. value: 0
  78049. };
  78050. }
  78051. if (!currentState) {
  78052. this._buttons[buttonIndex] = {
  78053. pressed: newState.pressed,
  78054. touched: newState.touched,
  78055. value: newState.value
  78056. };
  78057. return;
  78058. }
  78059. this._checkChanges(newState, currentState);
  78060. if (this._changes.changed) {
  78061. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  78062. this._handleButtonChange(buttonIndex, newState, this._changes);
  78063. }
  78064. this._buttons[buttonIndex].pressed = newState.pressed;
  78065. this._buttons[buttonIndex].touched = newState.touched;
  78066. // oculus triggers are never 0, thou not touched.
  78067. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  78068. };
  78069. WebVRController.prototype._checkChanges = function (newState, currentState) {
  78070. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  78071. this._changes.touchChanged = newState.touched !== currentState.touched;
  78072. this._changes.valueChanged = newState.value !== currentState.value;
  78073. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  78074. return this._changes;
  78075. };
  78076. /**
  78077. * Disposes of th webVRCOntroller
  78078. */
  78079. WebVRController.prototype.dispose = function () {
  78080. _super.prototype.dispose.call(this);
  78081. this.onTriggerStateChangedObservable.clear();
  78082. this.onMainButtonStateChangedObservable.clear();
  78083. this.onSecondaryButtonStateChangedObservable.clear();
  78084. this.onPadStateChangedObservable.clear();
  78085. this.onPadValuesChangedObservable.clear();
  78086. };
  78087. return WebVRController;
  78088. }(BABYLON.PoseEnabledController));
  78089. BABYLON.WebVRController = WebVRController;
  78090. })(BABYLON || (BABYLON = {}));
  78091. //# sourceMappingURL=babylon.webVRController.js.map
  78092. var BABYLON;
  78093. (function (BABYLON) {
  78094. /**
  78095. * Oculus Touch Controller
  78096. */
  78097. var OculusTouchController = /** @class */ (function (_super) {
  78098. __extends(OculusTouchController, _super);
  78099. /**
  78100. * Creates a new OculusTouchController from a gamepad
  78101. * @param vrGamepad the gamepad that the controller should be created from
  78102. */
  78103. function OculusTouchController(vrGamepad) {
  78104. var _this = _super.call(this, vrGamepad) || this;
  78105. /**
  78106. * Fired when the secondary trigger on this controller is modified
  78107. */
  78108. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  78109. /**
  78110. * Fired when the thumb rest on this controller is modified
  78111. */
  78112. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  78113. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  78114. return _this;
  78115. }
  78116. /**
  78117. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  78118. * @param scene scene in which to add meshes
  78119. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  78120. */
  78121. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  78122. var _this = this;
  78123. var meshName;
  78124. // Hand
  78125. if (this.hand === 'left') {
  78126. meshName = OculusTouchController.MODEL_LEFT_FILENAME;
  78127. }
  78128. else { // Right is the default if no hand is specified
  78129. meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
  78130. }
  78131. BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
  78132. /*
  78133. Parent Mesh name: oculus_touch_left
  78134. - body
  78135. - trigger
  78136. - thumbstick
  78137. - grip
  78138. - button_y
  78139. - button_x
  78140. - button_enter
  78141. */
  78142. _this._defaultModel = newMeshes[1];
  78143. _this.attachToMesh(_this._defaultModel);
  78144. if (meshLoaded) {
  78145. meshLoaded(_this._defaultModel);
  78146. }
  78147. });
  78148. };
  78149. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  78150. /**
  78151. * Fired when the A button on this controller is modified
  78152. */
  78153. get: function () {
  78154. if (this.hand === 'right') {
  78155. return this.onMainButtonStateChangedObservable;
  78156. }
  78157. else {
  78158. throw new Error('No A button on left hand');
  78159. }
  78160. },
  78161. enumerable: true,
  78162. configurable: true
  78163. });
  78164. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  78165. /**
  78166. * Fired when the B button on this controller is modified
  78167. */
  78168. get: function () {
  78169. if (this.hand === 'right') {
  78170. return this.onSecondaryButtonStateChangedObservable;
  78171. }
  78172. else {
  78173. throw new Error('No B button on left hand');
  78174. }
  78175. },
  78176. enumerable: true,
  78177. configurable: true
  78178. });
  78179. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  78180. /**
  78181. * Fired when the X button on this controller is modified
  78182. */
  78183. get: function () {
  78184. if (this.hand === 'left') {
  78185. return this.onMainButtonStateChangedObservable;
  78186. }
  78187. else {
  78188. throw new Error('No X button on right hand');
  78189. }
  78190. },
  78191. enumerable: true,
  78192. configurable: true
  78193. });
  78194. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  78195. /**
  78196. * Fired when the Y button on this controller is modified
  78197. */
  78198. get: function () {
  78199. if (this.hand === 'left') {
  78200. return this.onSecondaryButtonStateChangedObservable;
  78201. }
  78202. else {
  78203. throw new Error('No Y button on right hand');
  78204. }
  78205. },
  78206. enumerable: true,
  78207. configurable: true
  78208. });
  78209. /**
  78210. * Called once for each button that changed state since the last frame
  78211. * 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  78212. * 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  78213. * 2) secondary trigger (same)
  78214. * 3) A (right) X (left), touch, pressed = value
  78215. * 4) B / Y
  78216. * 5) thumb rest
  78217. * @param buttonIdx Which button index changed
  78218. * @param state New state of the button
  78219. * @param changes Which properties on the state changed since last frame
  78220. */
  78221. OculusTouchController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  78222. var notifyObject = state; //{ state: state, changes: changes };
  78223. var triggerDirection = this.hand === 'right' ? -1 : 1;
  78224. switch (buttonIdx) {
  78225. case 0:
  78226. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  78227. return;
  78228. case 1: // index trigger
  78229. if (this._defaultModel) {
  78230. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  78231. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  78232. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  78233. }
  78234. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  78235. return;
  78236. case 2: // secondary trigger
  78237. if (this._defaultModel) {
  78238. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  78239. }
  78240. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  78241. return;
  78242. case 3:
  78243. if (this._defaultModel) {
  78244. if (notifyObject.pressed) {
  78245. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  78246. }
  78247. else {
  78248. (this._defaultModel.getChildren()[1]).position.y = 0;
  78249. }
  78250. }
  78251. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  78252. return;
  78253. case 4:
  78254. if (this._defaultModel) {
  78255. if (notifyObject.pressed) {
  78256. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  78257. }
  78258. else {
  78259. (this._defaultModel.getChildren()[2]).position.y = 0;
  78260. }
  78261. }
  78262. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  78263. return;
  78264. case 5:
  78265. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  78266. return;
  78267. }
  78268. };
  78269. /**
  78270. * Base Url for the controller model.
  78271. */
  78272. OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
  78273. /**
  78274. * File name for the left controller model.
  78275. */
  78276. OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
  78277. /**
  78278. * File name for the right controller model.
  78279. */
  78280. OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
  78281. return OculusTouchController;
  78282. }(BABYLON.WebVRController));
  78283. BABYLON.OculusTouchController = OculusTouchController;
  78284. })(BABYLON || (BABYLON = {}));
  78285. //# sourceMappingURL=babylon.oculusTouchController.js.map
  78286. var BABYLON;
  78287. (function (BABYLON) {
  78288. /**
  78289. * Vive Controller
  78290. */
  78291. var ViveController = /** @class */ (function (_super) {
  78292. __extends(ViveController, _super);
  78293. /**
  78294. * Creates a new ViveController from a gamepad
  78295. * @param vrGamepad the gamepad that the controller should be created from
  78296. */
  78297. function ViveController(vrGamepad) {
  78298. var _this = _super.call(this, vrGamepad) || this;
  78299. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  78300. _this._invertLeftStickY = true;
  78301. return _this;
  78302. }
  78303. /**
  78304. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  78305. * @param scene scene in which to add meshes
  78306. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  78307. */
  78308. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  78309. var _this = this;
  78310. BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
  78311. /*
  78312. Parent Mesh name: ViveWand
  78313. - body
  78314. - r_gripper
  78315. - l_gripper
  78316. - menu_button
  78317. - system_button
  78318. - trackpad
  78319. - trigger
  78320. - LED
  78321. */
  78322. _this._defaultModel = newMeshes[1];
  78323. _this.attachToMesh(_this._defaultModel);
  78324. if (meshLoaded) {
  78325. meshLoaded(_this._defaultModel);
  78326. }
  78327. });
  78328. };
  78329. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  78330. /**
  78331. * Fired when the left button on this controller is modified
  78332. */
  78333. get: function () {
  78334. return this.onMainButtonStateChangedObservable;
  78335. },
  78336. enumerable: true,
  78337. configurable: true
  78338. });
  78339. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  78340. /**
  78341. * Fired when the right button on this controller is modified
  78342. */
  78343. get: function () {
  78344. return this.onMainButtonStateChangedObservable;
  78345. },
  78346. enumerable: true,
  78347. configurable: true
  78348. });
  78349. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  78350. /**
  78351. * Fired when the menu button on this controller is modified
  78352. */
  78353. get: function () {
  78354. return this.onSecondaryButtonStateChangedObservable;
  78355. },
  78356. enumerable: true,
  78357. configurable: true
  78358. });
  78359. /**
  78360. * Called once for each button that changed state since the last frame
  78361. * Vive mapping:
  78362. * 0: touchpad
  78363. * 1: trigger
  78364. * 2: left AND right buttons
  78365. * 3: menu button
  78366. * @param buttonIdx Which button index changed
  78367. * @param state New state of the button
  78368. * @param changes Which properties on the state changed since last frame
  78369. */
  78370. ViveController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  78371. var notifyObject = state; //{ state: state, changes: changes };
  78372. switch (buttonIdx) {
  78373. case 0:
  78374. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  78375. return;
  78376. case 1: // index trigger
  78377. if (this._defaultModel) {
  78378. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  78379. }
  78380. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  78381. return;
  78382. case 2: // left AND right button
  78383. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  78384. return;
  78385. case 3:
  78386. if (this._defaultModel) {
  78387. if (notifyObject.pressed) {
  78388. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  78389. }
  78390. else {
  78391. (this._defaultModel.getChildren()[2]).position.y = 0;
  78392. }
  78393. }
  78394. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  78395. return;
  78396. }
  78397. };
  78398. /**
  78399. * Base Url for the controller model.
  78400. */
  78401. ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
  78402. /**
  78403. * File name for the controller model.
  78404. */
  78405. ViveController.MODEL_FILENAME = 'wand.babylon';
  78406. return ViveController;
  78407. }(BABYLON.WebVRController));
  78408. BABYLON.ViveController = ViveController;
  78409. })(BABYLON || (BABYLON = {}));
  78410. //# sourceMappingURL=babylon.viveController.js.map
  78411. var BABYLON;
  78412. (function (BABYLON) {
  78413. /**
  78414. * Generic Controller
  78415. */
  78416. var GenericController = /** @class */ (function (_super) {
  78417. __extends(GenericController, _super);
  78418. /**
  78419. * Creates a new GenericController from a gamepad
  78420. * @param vrGamepad the gamepad that the controller should be created from
  78421. */
  78422. function GenericController(vrGamepad) {
  78423. return _super.call(this, vrGamepad) || this;
  78424. }
  78425. /**
  78426. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  78427. * @param scene scene in which to add meshes
  78428. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  78429. */
  78430. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  78431. var _this = this;
  78432. BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
  78433. _this._defaultModel = newMeshes[1];
  78434. _this.attachToMesh(_this._defaultModel);
  78435. if (meshLoaded) {
  78436. meshLoaded(_this._defaultModel);
  78437. }
  78438. });
  78439. };
  78440. /**
  78441. * Called once for each button that changed state since the last frame
  78442. * @param buttonIdx Which button index changed
  78443. * @param state New state of the button
  78444. * @param changes Which properties on the state changed since last frame
  78445. */
  78446. GenericController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  78447. console.log("Button id: " + buttonIdx + "state: ");
  78448. console.dir(state);
  78449. };
  78450. /**
  78451. * Base Url for the controller model.
  78452. */
  78453. GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  78454. /**
  78455. * File name for the controller model.
  78456. */
  78457. GenericController.MODEL_FILENAME = 'generic.babylon';
  78458. return GenericController;
  78459. }(BABYLON.WebVRController));
  78460. BABYLON.GenericController = GenericController;
  78461. })(BABYLON || (BABYLON = {}));
  78462. //# sourceMappingURL=babylon.genericController.js.map
  78463. var BABYLON;
  78464. (function (BABYLON) {
  78465. /**
  78466. * Defines the LoadedMeshInfo object that describes information about the loaded webVR controller mesh
  78467. */
  78468. var LoadedMeshInfo = /** @class */ (function () {
  78469. function LoadedMeshInfo() {
  78470. /**
  78471. * Map of the button meshes contained in the controller
  78472. */
  78473. this.buttonMeshes = {};
  78474. /**
  78475. * Map of the axis meshes contained in the controller
  78476. */
  78477. this.axisMeshes = {};
  78478. }
  78479. return LoadedMeshInfo;
  78480. }());
  78481. /**
  78482. * Defines the WindowsMotionController object that the state of the windows motion controller
  78483. */
  78484. var WindowsMotionController = /** @class */ (function (_super) {
  78485. __extends(WindowsMotionController, _super);
  78486. /**
  78487. * Creates a new WindowsMotionController from a gamepad
  78488. * @param vrGamepad the gamepad that the controller should be created from
  78489. */
  78490. function WindowsMotionController(vrGamepad) {
  78491. var _this = _super.call(this, vrGamepad) || this;
  78492. _this._mapping = {
  78493. // Semantic button names
  78494. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  78495. // A mapping of the button name to glTF model node name
  78496. // that should be transformed by button value.
  78497. buttonMeshNames: {
  78498. 'trigger': 'SELECT',
  78499. 'menu': 'MENU',
  78500. 'grip': 'GRASP',
  78501. 'thumbstick': 'THUMBSTICK_PRESS',
  78502. 'trackpad': 'TOUCHPAD_PRESS'
  78503. },
  78504. // This mapping is used to translate from the Motion Controller to Babylon semantics
  78505. buttonObservableNames: {
  78506. 'trigger': 'onTriggerStateChangedObservable',
  78507. 'menu': 'onSecondaryButtonStateChangedObservable',
  78508. 'grip': 'onMainButtonStateChangedObservable',
  78509. 'thumbstick': 'onPadStateChangedObservable',
  78510. 'trackpad': 'onTrackpadChangedObservable'
  78511. },
  78512. // A mapping of the axis name to glTF model node name
  78513. // that should be transformed by axis value.
  78514. // This array mirrors the browserGamepad.axes array, such that
  78515. // the mesh corresponding to axis 0 is in this array index 0.
  78516. axisMeshNames: [
  78517. 'THUMBSTICK_X',
  78518. 'THUMBSTICK_Y',
  78519. 'TOUCHPAD_TOUCH_X',
  78520. 'TOUCHPAD_TOUCH_Y'
  78521. ],
  78522. pointingPoseMeshName: BABYLON.PoseEnabledController.POINTING_POSE
  78523. };
  78524. /**
  78525. * Fired when the trackpad on this controller is clicked
  78526. */
  78527. _this.onTrackpadChangedObservable = new BABYLON.Observable();
  78528. /**
  78529. * Fired when the trackpad on this controller is modified
  78530. */
  78531. _this.onTrackpadValuesChangedObservable = new BABYLON.Observable();
  78532. /**
  78533. * The current x and y values of this controller's trackpad
  78534. */
  78535. _this.trackpad = { x: 0, y: 0 };
  78536. _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
  78537. _this._loadedMeshInfo = null;
  78538. return _this;
  78539. }
  78540. Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
  78541. /**
  78542. * Fired when the trigger on this controller is modified
  78543. */
  78544. get: function () {
  78545. return this.onTriggerStateChangedObservable;
  78546. },
  78547. enumerable: true,
  78548. configurable: true
  78549. });
  78550. Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
  78551. /**
  78552. * Fired when the menu button on this controller is modified
  78553. */
  78554. get: function () {
  78555. return this.onSecondaryButtonStateChangedObservable;
  78556. },
  78557. enumerable: true,
  78558. configurable: true
  78559. });
  78560. Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
  78561. /**
  78562. * Fired when the grip button on this controller is modified
  78563. */
  78564. get: function () {
  78565. return this.onMainButtonStateChangedObservable;
  78566. },
  78567. enumerable: true,
  78568. configurable: true
  78569. });
  78570. Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
  78571. /**
  78572. * Fired when the thumbstick button on this controller is modified
  78573. */
  78574. get: function () {
  78575. return this.onPadStateChangedObservable;
  78576. },
  78577. enumerable: true,
  78578. configurable: true
  78579. });
  78580. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
  78581. /**
  78582. * Fired when the touchpad button on this controller is modified
  78583. */
  78584. get: function () {
  78585. return this.onTrackpadChangedObservable;
  78586. },
  78587. enumerable: true,
  78588. configurable: true
  78589. });
  78590. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadValuesChangedObservable", {
  78591. /**
  78592. * Fired when the touchpad values on this controller are modified
  78593. */
  78594. get: function () {
  78595. return this.onTrackpadValuesChangedObservable;
  78596. },
  78597. enumerable: true,
  78598. configurable: true
  78599. });
  78600. WindowsMotionController.prototype._updateTrackpad = function () {
  78601. if (this.browserGamepad.axes && (this.browserGamepad.axes[2] != this.trackpad.x || this.browserGamepad.axes[3] != this.trackpad.y)) {
  78602. this.trackpad.x = this.browserGamepad["axes"][2];
  78603. this.trackpad.y = this.browserGamepad["axes"][3];
  78604. this.onTrackpadValuesChangedObservable.notifyObservers(this.trackpad);
  78605. }
  78606. };
  78607. /**
  78608. * Called once per frame by the engine.
  78609. */
  78610. WindowsMotionController.prototype.update = function () {
  78611. _super.prototype.update.call(this);
  78612. if (this.browserGamepad.axes) {
  78613. this._updateTrackpad();
  78614. // Only need to animate axes if there is a loaded mesh
  78615. if (this._loadedMeshInfo) {
  78616. for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  78617. this._lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  78618. }
  78619. }
  78620. }
  78621. };
  78622. /**
  78623. * Called once for each button that changed state since the last frame
  78624. * @param buttonIdx Which button index changed
  78625. * @param state New state of the button
  78626. * @param changes Which properties on the state changed since last frame
  78627. */
  78628. WindowsMotionController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  78629. var buttonName = this._mapping.buttons[buttonIdx];
  78630. if (!buttonName) {
  78631. return;
  78632. }
  78633. // Update the trackpad to ensure trackpad.x/y are accurate during button events between frames
  78634. this._updateTrackpad();
  78635. // Only emit events for buttons that we know how to map from index to name
  78636. var observable = this[(this._mapping.buttonObservableNames)[buttonName]];
  78637. if (observable) {
  78638. observable.notifyObservers(state);
  78639. }
  78640. this._lerpButtonTransform(buttonName, state.value);
  78641. };
  78642. /**
  78643. * Moves the buttons on the controller mesh based on their current state
  78644. * @param buttonName the name of the button to move
  78645. * @param buttonValue the value of the button which determines the buttons new position
  78646. */
  78647. WindowsMotionController.prototype._lerpButtonTransform = function (buttonName, buttonValue) {
  78648. // If there is no loaded mesh, there is nothing to transform.
  78649. if (!this._loadedMeshInfo) {
  78650. return;
  78651. }
  78652. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  78653. if (!meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  78654. return;
  78655. }
  78656. BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
  78657. BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
  78658. };
  78659. /**
  78660. * Moves the axis on the controller mesh based on its current state
  78661. * @param axis the index of the axis
  78662. * @param axisValue the value of the axis which determines the meshes new position
  78663. * @hidden
  78664. */
  78665. WindowsMotionController.prototype._lerpAxisTransform = function (axis, axisValue) {
  78666. if (!this._loadedMeshInfo) {
  78667. return;
  78668. }
  78669. var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  78670. if (!meshInfo) {
  78671. return;
  78672. }
  78673. if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  78674. return;
  78675. }
  78676. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  78677. var lerpValue = axisValue * 0.5 + 0.5;
  78678. BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
  78679. BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
  78680. };
  78681. /**
  78682. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  78683. * @param scene scene in which to add meshes
  78684. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  78685. */
  78686. WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
  78687. var _this = this;
  78688. if (forceDefault === void 0) { forceDefault = false; }
  78689. var path;
  78690. var filename;
  78691. // Checking if GLB loader is present
  78692. if (BABYLON.SceneLoader.IsPluginForExtensionAvailable(".glb")) {
  78693. // Determine the device specific folder based on the ID suffix
  78694. var device = 'default';
  78695. if (this.id && !forceDefault) {
  78696. var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  78697. device = ((match && match[0]) || device);
  78698. }
  78699. // Hand
  78700. if (this.hand === 'left') {
  78701. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  78702. }
  78703. else { // Right is the default if no hand is specified
  78704. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  78705. }
  78706. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  78707. }
  78708. else {
  78709. BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  78710. path = BABYLON.GenericController.MODEL_BASE_URL;
  78711. filename = BABYLON.GenericController.MODEL_FILENAME;
  78712. }
  78713. BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
  78714. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  78715. _this._loadedMeshInfo = _this.processModel(scene, meshes);
  78716. if (!_this._loadedMeshInfo) {
  78717. return;
  78718. }
  78719. _this._defaultModel = _this._loadedMeshInfo.rootNode;
  78720. _this.attachToMesh(_this._defaultModel);
  78721. if (meshLoaded) {
  78722. meshLoaded(_this._defaultModel);
  78723. }
  78724. }, null, function (scene, message) {
  78725. BABYLON.Tools.Log(message);
  78726. BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  78727. if (!forceDefault) {
  78728. _this.initControllerMesh(scene, meshLoaded, true);
  78729. }
  78730. });
  78731. };
  78732. /**
  78733. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  78734. * can be transformed by button presses and axes values, based on this._mapping.
  78735. *
  78736. * @param scene scene in which the meshes exist
  78737. * @param meshes list of meshes that make up the controller model to process
  78738. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  78739. */
  78740. WindowsMotionController.prototype.processModel = function (scene, meshes) {
  78741. var loadedMeshInfo = null;
  78742. // Create a new mesh to contain the glTF hierarchy
  78743. var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  78744. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  78745. var childMesh = null;
  78746. for (var i = 0; i < meshes.length; i++) {
  78747. var mesh = meshes[i];
  78748. if (!mesh.parent) {
  78749. // Exclude controller meshes from picking results
  78750. mesh.isPickable = false;
  78751. // Handle root node, attach to the new parentMesh
  78752. childMesh = mesh;
  78753. break;
  78754. }
  78755. }
  78756. if (childMesh) {
  78757. childMesh.setParent(parentMesh);
  78758. // Create our mesh info. Note that this method will always return non-null.
  78759. loadedMeshInfo = this.createMeshInfo(parentMesh);
  78760. }
  78761. else {
  78762. BABYLON.Tools.Warn('Could not find root node in model file.');
  78763. }
  78764. return loadedMeshInfo;
  78765. };
  78766. WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
  78767. var loadedMeshInfo = new LoadedMeshInfo();
  78768. var i;
  78769. loadedMeshInfo.rootNode = rootNode;
  78770. // Reset the caches
  78771. loadedMeshInfo.buttonMeshes = {};
  78772. loadedMeshInfo.axisMeshes = {};
  78773. // Button Meshes
  78774. for (i = 0; i < this._mapping.buttons.length; i++) {
  78775. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  78776. if (!buttonMeshName) {
  78777. BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  78778. continue;
  78779. }
  78780. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  78781. if (!buttonMesh) {
  78782. BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  78783. continue;
  78784. }
  78785. var buttonMeshInfo = {
  78786. index: i,
  78787. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  78788. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  78789. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  78790. };
  78791. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  78792. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  78793. }
  78794. else {
  78795. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  78796. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  78797. '(VALUE: ' + !!buttonMeshInfo.value +
  78798. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  78799. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  78800. ')');
  78801. }
  78802. }
  78803. // Axis Meshes
  78804. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  78805. var axisMeshName = this._mapping.axisMeshNames[i];
  78806. if (!axisMeshName) {
  78807. BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
  78808. continue;
  78809. }
  78810. var axisMesh = getChildByName(rootNode, axisMeshName);
  78811. if (!axisMesh) {
  78812. BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  78813. continue;
  78814. }
  78815. var axisMeshInfo = {
  78816. index: i,
  78817. value: getImmediateChildByName(axisMesh, 'VALUE'),
  78818. min: getImmediateChildByName(axisMesh, 'MIN'),
  78819. max: getImmediateChildByName(axisMesh, 'MAX')
  78820. };
  78821. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  78822. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  78823. }
  78824. else {
  78825. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  78826. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  78827. '(VALUE: ' + !!axisMeshInfo.value +
  78828. ', MIN: ' + !!axisMeshInfo.min +
  78829. ', MAX:' + !!axisMeshInfo.max +
  78830. ')');
  78831. }
  78832. }
  78833. // Pointing Ray
  78834. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  78835. if (!loadedMeshInfo.pointingPoseNode) {
  78836. BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  78837. }
  78838. else {
  78839. this._pointingPoseNode = loadedMeshInfo.pointingPoseNode;
  78840. }
  78841. return loadedMeshInfo;
  78842. // Look through all children recursively. This will return null if no mesh exists with the given name.
  78843. function getChildByName(node, name) {
  78844. return node.getChildMeshes(false, function (n) { return n.name === name; })[0];
  78845. }
  78846. // Look through only immediate children. This will return null if no mesh exists with the given name.
  78847. function getImmediateChildByName(node, name) {
  78848. return node.getChildMeshes(true, function (n) { return n.name == name; })[0];
  78849. }
  78850. };
  78851. /**
  78852. * Gets the ray of the controller in the direction the controller is pointing
  78853. * @param length the length the resulting ray should be
  78854. * @returns a ray in the direction the controller is pointing
  78855. */
  78856. WindowsMotionController.prototype.getForwardRay = function (length) {
  78857. if (length === void 0) { length = 100; }
  78858. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  78859. return _super.prototype.getForwardRay.call(this, length);
  78860. }
  78861. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  78862. var origin = m.getTranslation();
  78863. var forward = new BABYLON.Vector3(0, 0, -1);
  78864. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  78865. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  78866. return new BABYLON.Ray(origin, direction, length);
  78867. };
  78868. /**
  78869. * Disposes of the controller
  78870. */
  78871. WindowsMotionController.prototype.dispose = function () {
  78872. _super.prototype.dispose.call(this);
  78873. this.onTrackpadChangedObservable.clear();
  78874. };
  78875. /**
  78876. * The base url used to load the left and right controller models
  78877. */
  78878. WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
  78879. /**
  78880. * The name of the left controller model file
  78881. */
  78882. WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
  78883. /**
  78884. * The name of the right controller model file
  78885. */
  78886. WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
  78887. /**
  78888. * The controller name prefix for this controller type
  78889. */
  78890. WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  78891. /**
  78892. * The controller id pattern for this controller type
  78893. */
  78894. WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  78895. return WindowsMotionController;
  78896. }(BABYLON.WebVRController));
  78897. BABYLON.WindowsMotionController = WindowsMotionController;
  78898. })(BABYLON || (BABYLON = {}));
  78899. //# sourceMappingURL=babylon.windowsMotionController.js.map
  78900. var BABYLON;
  78901. (function (BABYLON) {
  78902. /**
  78903. * Gear VR Controller
  78904. */
  78905. var GearVRController = /** @class */ (function (_super) {
  78906. __extends(GearVRController, _super);
  78907. /**
  78908. * Creates a new GearVRController from a gamepad
  78909. * @param vrGamepad the gamepad that the controller should be created from
  78910. */
  78911. function GearVRController(vrGamepad) {
  78912. var _this = _super.call(this, vrGamepad) || this;
  78913. _this._buttonIndexToObservableNameMap = [
  78914. 'onTrackpadChangedObservable',
  78915. 'onTriggerStateChangedObservable' // Trigger
  78916. ];
  78917. _this.controllerType = BABYLON.PoseEnabledControllerType.GEAR_VR;
  78918. // Initial starting position defaults to where hand would be (incase of only 3dof controller)
  78919. _this._calculatedPosition = new BABYLON.Vector3(_this.hand == "left" ? -0.15 : 0.15, -0.5, 0.25);
  78920. _this._disableTrackPosition(_this._calculatedPosition);
  78921. return _this;
  78922. }
  78923. /**
  78924. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  78925. * @param scene scene in which to add meshes
  78926. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  78927. */
  78928. GearVRController.prototype.initControllerMesh = function (scene, meshLoaded) {
  78929. var _this = this;
  78930. BABYLON.SceneLoader.ImportMesh("", GearVRController.MODEL_BASE_URL, GearVRController.MODEL_FILENAME, scene, function (newMeshes) {
  78931. // Offset the controller so it will rotate around the users wrist
  78932. var mesh = new BABYLON.Mesh("", scene);
  78933. newMeshes[1].parent = mesh;
  78934. newMeshes[1].position.z = -0.15;
  78935. _this._defaultModel = mesh;
  78936. _this.attachToMesh(_this._defaultModel);
  78937. if (meshLoaded) {
  78938. meshLoaded(_this._defaultModel);
  78939. }
  78940. });
  78941. };
  78942. /**
  78943. * Called once for each button that changed state since the last frame
  78944. * @param buttonIdx Which button index changed
  78945. * @param state New state of the button
  78946. * @param changes Which properties on the state changed since last frame
  78947. */
  78948. GearVRController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  78949. if (buttonIdx < this._buttonIndexToObservableNameMap.length) {
  78950. var observableName = this._buttonIndexToObservableNameMap[buttonIdx];
  78951. // Only emit events for buttons that we know how to map from index to observable
  78952. var observable = this[observableName];
  78953. if (observable) {
  78954. observable.notifyObservers(state);
  78955. }
  78956. }
  78957. };
  78958. /**
  78959. * Base Url for the controller model.
  78960. */
  78961. GearVRController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  78962. /**
  78963. * File name for the controller model.
  78964. */
  78965. GearVRController.MODEL_FILENAME = 'generic.babylon';
  78966. /**
  78967. * Gamepad Id prefix used to identify this controller.
  78968. */
  78969. GearVRController.GAMEPAD_ID_PREFIX = 'Gear VR'; // id is 'Gear VR Controller'
  78970. return GearVRController;
  78971. }(BABYLON.WebVRController));
  78972. BABYLON.GearVRController = GearVRController;
  78973. })(BABYLON || (BABYLON = {}));
  78974. //# sourceMappingURL=babylon.gearVRController.js.map
  78975. var BABYLON;
  78976. (function (BABYLON) {
  78977. /**
  78978. * Google Daydream controller
  78979. */
  78980. var DaydreamController = /** @class */ (function (_super) {
  78981. __extends(DaydreamController, _super);
  78982. /**
  78983. * Creates a new DaydreamController from a gamepad
  78984. * @param vrGamepad the gamepad that the controller should be created from
  78985. */
  78986. function DaydreamController(vrGamepad) {
  78987. var _this = _super.call(this, vrGamepad) || this;
  78988. _this.controllerType = BABYLON.PoseEnabledControllerType.DAYDREAM;
  78989. return _this;
  78990. }
  78991. /**
  78992. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  78993. * @param scene scene in which to add meshes
  78994. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  78995. */
  78996. DaydreamController.prototype.initControllerMesh = function (scene, meshLoaded) {
  78997. var _this = this;
  78998. BABYLON.SceneLoader.ImportMesh("", DaydreamController.MODEL_BASE_URL, DaydreamController.MODEL_FILENAME, scene, function (newMeshes) {
  78999. _this._defaultModel = newMeshes[1];
  79000. _this.attachToMesh(_this._defaultModel);
  79001. if (meshLoaded) {
  79002. meshLoaded(_this._defaultModel);
  79003. }
  79004. });
  79005. };
  79006. /**
  79007. * Called once for each button that changed state since the last frame
  79008. * @param buttonIdx Which button index changed
  79009. * @param state New state of the button
  79010. * @param changes Which properties on the state changed since last frame
  79011. */
  79012. DaydreamController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  79013. // Daydream controller only has 1 GamepadButton (on the trackpad).
  79014. if (buttonIdx === 0) {
  79015. var observable = this.onTriggerStateChangedObservable;
  79016. if (observable) {
  79017. observable.notifyObservers(state);
  79018. }
  79019. }
  79020. else {
  79021. // If the app or home buttons are ever made available
  79022. BABYLON.Tools.Warn("Unrecognized Daydream button index: " + buttonIdx);
  79023. }
  79024. };
  79025. /**
  79026. * Base Url for the controller model.
  79027. */
  79028. DaydreamController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  79029. /**
  79030. * File name for the controller model.
  79031. */
  79032. DaydreamController.MODEL_FILENAME = 'generic.babylon';
  79033. /**
  79034. * Gamepad Id prefix used to identify Daydream Controller.
  79035. */
  79036. DaydreamController.GAMEPAD_ID_PREFIX = 'Daydream'; // id is 'Daydream Controller'
  79037. return DaydreamController;
  79038. }(BABYLON.WebVRController));
  79039. BABYLON.DaydreamController = DaydreamController;
  79040. })(BABYLON || (BABYLON = {}));
  79041. //# sourceMappingURL=babylon.daydreamController.js.map
  79042. var BABYLON;
  79043. (function (BABYLON) {
  79044. Object.defineProperty(BABYLON.Scene.prototype, "gamepadManager", {
  79045. get: function () {
  79046. if (!this._gamepadManager) {
  79047. this._gamepadManager = new BABYLON.GamepadManager(this);
  79048. var component = this._getComponent(BABYLON.SceneComponentConstants.NAME_GAMEPAD);
  79049. if (!component) {
  79050. component = new GamepadSystemSceneComponent(this);
  79051. this._addComponent(component);
  79052. }
  79053. }
  79054. return this._gamepadManager;
  79055. },
  79056. enumerable: true,
  79057. configurable: true
  79058. });
  79059. BABYLON.FreeCameraInputsManager.prototype.addGamepad = function () {
  79060. this.add(new BABYLON.FreeCameraGamepadInput());
  79061. return this;
  79062. };
  79063. BABYLON.ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  79064. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  79065. return this;
  79066. };
  79067. /**
  79068. * Defines the gamepad scene component responsible to manage gamepads in a given scene
  79069. */
  79070. var GamepadSystemSceneComponent = /** @class */ (function () {
  79071. /**
  79072. * Creates a new instance of the component for the given scene
  79073. * @param scene Defines the scene to register the component in
  79074. */
  79075. function GamepadSystemSceneComponent(scene) {
  79076. /**
  79077. * The component name helpfull to identify the component in the list of scene components.
  79078. */
  79079. this.name = BABYLON.SceneComponentConstants.NAME_GAMEPAD;
  79080. this.scene = scene;
  79081. }
  79082. /**
  79083. * Registers the component in a given scene
  79084. */
  79085. GamepadSystemSceneComponent.prototype.register = function () {
  79086. this.scene._beforeCameraUpdateStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERAUPDATE_GAMEPAD, this, this._beforeCameraUpdate);
  79087. };
  79088. /**
  79089. * Rebuilds the elements related to this component in case of
  79090. * context lost for instance.
  79091. */
  79092. GamepadSystemSceneComponent.prototype.rebuild = function () {
  79093. // Nothing to do for gamepads
  79094. };
  79095. /**
  79096. * Disposes the component and the associated ressources
  79097. */
  79098. GamepadSystemSceneComponent.prototype.dispose = function () {
  79099. var gamepadManager = this.scene._gamepadManager;
  79100. if (gamepadManager) {
  79101. gamepadManager.dispose();
  79102. this.scene._gamepadManager = null;
  79103. }
  79104. };
  79105. GamepadSystemSceneComponent.prototype._beforeCameraUpdate = function () {
  79106. var gamepadManager = this.scene._gamepadManager;
  79107. if (gamepadManager && gamepadManager._isMonitoring) {
  79108. gamepadManager._checkGamepadsStatus();
  79109. }
  79110. };
  79111. return GamepadSystemSceneComponent;
  79112. }());
  79113. BABYLON.GamepadSystemSceneComponent = GamepadSystemSceneComponent;
  79114. })(BABYLON || (BABYLON = {}));
  79115. //# sourceMappingURL=babylon.gamepadSceneComponent.js.map
  79116. var BABYLON;
  79117. (function (BABYLON) {
  79118. BABYLON.Node.AddNodeConstructor("FollowCamera", function (name, scene) {
  79119. return function () { return new FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  79120. });
  79121. BABYLON.Node.AddNodeConstructor("ArcFollowCamera", function (name, scene) {
  79122. return function () { return new ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  79123. });
  79124. /**
  79125. * A follow camera takes a mesh as a target and follows it as it moves. Both a free camera version followCamera and
  79126. * an arc rotate version arcFollowCamera are available.
  79127. * @see http://doc.babylonjs.com/features/cameras#follow-camera
  79128. */
  79129. var FollowCamera = /** @class */ (function (_super) {
  79130. __extends(FollowCamera, _super);
  79131. /**
  79132. * Instantiates the follow camera.
  79133. * @see http://doc.babylonjs.com/features/cameras#follow-camera
  79134. * @param name Define the name of the camera in the scene
  79135. * @param position Define the position of the camera
  79136. * @param scene Define the scene the camera belong to
  79137. * @param lockedTarget Define the target of the camera
  79138. */
  79139. function FollowCamera(name, position, scene, lockedTarget) {
  79140. if (lockedTarget === void 0) { lockedTarget = null; }
  79141. var _this = _super.call(this, name, position, scene) || this;
  79142. /**
  79143. * Distance the follow camera should follow an object at
  79144. */
  79145. _this.radius = 12;
  79146. /**
  79147. * Define a rotation offset between the camera and the object it follows
  79148. */
  79149. _this.rotationOffset = 0;
  79150. /**
  79151. * Define a height offset between the camera and the object it follows.
  79152. * It can help following an object from the top (like a car chaing a plane)
  79153. */
  79154. _this.heightOffset = 4;
  79155. /**
  79156. * Define how fast the camera can accelerate to follow it s target.
  79157. */
  79158. _this.cameraAcceleration = 0.05;
  79159. /**
  79160. * Define the speed limit of the camera following an object.
  79161. */
  79162. _this.maxCameraSpeed = 20;
  79163. _this.lockedTarget = lockedTarget;
  79164. return _this;
  79165. }
  79166. FollowCamera.prototype._follow = function (cameraTarget) {
  79167. if (!cameraTarget)
  79168. return;
  79169. var yRotation;
  79170. if (cameraTarget.rotationQuaternion) {
  79171. var rotMatrix = new BABYLON.Matrix();
  79172. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  79173. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  79174. }
  79175. else {
  79176. yRotation = cameraTarget.rotation.y;
  79177. }
  79178. var radians = BABYLON.Tools.ToRadians(this.rotationOffset) + yRotation;
  79179. var targetPosition = cameraTarget.getAbsolutePosition();
  79180. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  79181. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  79182. var dx = targetX - this.position.x;
  79183. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  79184. var dz = (targetZ) - this.position.z;
  79185. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  79186. var vy = dy * this.cameraAcceleration;
  79187. var vz = dz * this.cameraAcceleration * 2;
  79188. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  79189. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  79190. }
  79191. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  79192. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  79193. }
  79194. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  79195. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  79196. }
  79197. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  79198. this.setTarget(targetPosition);
  79199. };
  79200. /** @hidden */
  79201. FollowCamera.prototype._checkInputs = function () {
  79202. _super.prototype._checkInputs.call(this);
  79203. if (this.lockedTarget) {
  79204. this._follow(this.lockedTarget);
  79205. }
  79206. };
  79207. /**
  79208. * Gets the camera class name.
  79209. * @returns the class name
  79210. */
  79211. FollowCamera.prototype.getClassName = function () {
  79212. return "FollowCamera";
  79213. };
  79214. __decorate([
  79215. BABYLON.serialize()
  79216. ], FollowCamera.prototype, "radius", void 0);
  79217. __decorate([
  79218. BABYLON.serialize()
  79219. ], FollowCamera.prototype, "rotationOffset", void 0);
  79220. __decorate([
  79221. BABYLON.serialize()
  79222. ], FollowCamera.prototype, "heightOffset", void 0);
  79223. __decorate([
  79224. BABYLON.serialize()
  79225. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  79226. __decorate([
  79227. BABYLON.serialize()
  79228. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  79229. __decorate([
  79230. BABYLON.serializeAsMeshReference("lockedTargetId")
  79231. ], FollowCamera.prototype, "lockedTarget", void 0);
  79232. return FollowCamera;
  79233. }(BABYLON.TargetCamera));
  79234. BABYLON.FollowCamera = FollowCamera;
  79235. /**
  79236. * Arc Rotate version of the follow camera.
  79237. * It still follows a Defined mesh but in an Arc Rotate Camera fashion.
  79238. * @see http://doc.babylonjs.com/features/cameras#follow-camera
  79239. */
  79240. var ArcFollowCamera = /** @class */ (function (_super) {
  79241. __extends(ArcFollowCamera, _super);
  79242. /**
  79243. * Instantiates a new ArcFollowCamera
  79244. * @see http://doc.babylonjs.com/features/cameras#follow-camera
  79245. * @param name Define the name of the camera
  79246. * @param alpha Define the rotation angle of the camera around the logitudinal axis
  79247. * @param beta Define the rotation angle of the camera around the elevation axis
  79248. * @param radius Define the radius of the camera from its target point
  79249. * @param target Define the target of the camera
  79250. * @param scene Define the scene the camera belongs to
  79251. */
  79252. function ArcFollowCamera(name,
  79253. /** The longitudinal angle of the camera */
  79254. alpha,
  79255. /** The latitudinal angle of the camera */
  79256. beta,
  79257. /** The radius of the camera from its target */
  79258. radius,
  79259. /** Define the camera target (the messh it should follow) */
  79260. target, scene) {
  79261. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  79262. _this.alpha = alpha;
  79263. _this.beta = beta;
  79264. _this.radius = radius;
  79265. _this.target = target;
  79266. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  79267. _this._follow();
  79268. return _this;
  79269. }
  79270. ArcFollowCamera.prototype._follow = function () {
  79271. if (!this.target) {
  79272. return;
  79273. }
  79274. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  79275. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  79276. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  79277. var targetPosition = this.target.getAbsolutePosition();
  79278. this.position = targetPosition.add(this._cartesianCoordinates);
  79279. this.setTarget(targetPosition);
  79280. };
  79281. /** @hidden */
  79282. ArcFollowCamera.prototype._checkInputs = function () {
  79283. _super.prototype._checkInputs.call(this);
  79284. this._follow();
  79285. };
  79286. /**
  79287. * Returns the class name of the object.
  79288. * It is mostly used internally for serialization purposes.
  79289. */
  79290. ArcFollowCamera.prototype.getClassName = function () {
  79291. return "ArcFollowCamera";
  79292. };
  79293. return ArcFollowCamera;
  79294. }(BABYLON.TargetCamera));
  79295. BABYLON.ArcFollowCamera = ArcFollowCamera;
  79296. })(BABYLON || (BABYLON = {}));
  79297. //# sourceMappingURL=babylon.followCamera.js.map
  79298. var BABYLON;
  79299. (function (BABYLON) {
  79300. /**
  79301. * The Universal Camera is the one to choose for first person shooter type games, and works with all the keyboard, mouse, touch and gamepads. This replaces the earlier Free Camera,
  79302. * which still works and will still be found in many Playgrounds.
  79303. * @see http://doc.babylonjs.com/features/cameras#universal-camera
  79304. */
  79305. var UniversalCamera = /** @class */ (function (_super) {
  79306. __extends(UniversalCamera, _super);
  79307. /**
  79308. * The Universal Camera is the one to choose for first person shooter type games, and works with all the keyboard, mouse, touch and gamepads. This replaces the earlier Free Camera,
  79309. * which still works and will still be found in many Playgrounds.
  79310. * @see http://doc.babylonjs.com/features/cameras#universal-camera
  79311. * @param name Define the name of the camera in the scene
  79312. * @param position Define the start position of the camera in the scene
  79313. * @param scene Define the scene the camera belongs to
  79314. */
  79315. function UniversalCamera(name, position, scene) {
  79316. var _this = _super.call(this, name, position, scene) || this;
  79317. _this.inputs.addGamepad();
  79318. return _this;
  79319. }
  79320. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  79321. /**
  79322. * Defines the gamepad rotation sensiblity.
  79323. * This is the threshold from when rotation starts to be accounted for to prevent jittering.
  79324. */
  79325. get: function () {
  79326. var gamepad = this.inputs.attached["gamepad"];
  79327. if (gamepad)
  79328. return gamepad.gamepadAngularSensibility;
  79329. return 0;
  79330. },
  79331. set: function (value) {
  79332. var gamepad = this.inputs.attached["gamepad"];
  79333. if (gamepad)
  79334. gamepad.gamepadAngularSensibility = value;
  79335. },
  79336. enumerable: true,
  79337. configurable: true
  79338. });
  79339. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  79340. /**
  79341. * Defines the gamepad move sensiblity.
  79342. * This is the threshold from when moving starts to be accounted for for to prevent jittering.
  79343. */
  79344. get: function () {
  79345. var gamepad = this.inputs.attached["gamepad"];
  79346. if (gamepad)
  79347. return gamepad.gamepadMoveSensibility;
  79348. return 0;
  79349. },
  79350. set: function (value) {
  79351. var gamepad = this.inputs.attached["gamepad"];
  79352. if (gamepad)
  79353. gamepad.gamepadMoveSensibility = value;
  79354. },
  79355. enumerable: true,
  79356. configurable: true
  79357. });
  79358. /**
  79359. * Gets the current object class name.
  79360. * @return the class name
  79361. */
  79362. UniversalCamera.prototype.getClassName = function () {
  79363. return "UniversalCamera";
  79364. };
  79365. return UniversalCamera;
  79366. }(BABYLON.TouchCamera));
  79367. BABYLON.UniversalCamera = UniversalCamera;
  79368. })(BABYLON || (BABYLON = {}));
  79369. //# sourceMappingURL=babylon.universalCamera.js.map
  79370. var BABYLON;
  79371. (function (BABYLON) {
  79372. BABYLON.Node.AddNodeConstructor("GamepadCamera", function (name, scene) {
  79373. return function () { return new GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  79374. });
  79375. /**
  79376. * This represents a FPS type of camera. This is only here for back compat purpose.
  79377. * Please use the UniversalCamera instead as both are identical.
  79378. * @see http://doc.babylonjs.com/features/cameras#universal-camera
  79379. */
  79380. var GamepadCamera = /** @class */ (function (_super) {
  79381. __extends(GamepadCamera, _super);
  79382. /**
  79383. * Instantiates a new Gamepad Camera
  79384. * This represents a FPS type of camera. This is only here for back compat purpose.
  79385. * Please use the UniversalCamera instead as both are identical.
  79386. * @see http://doc.babylonjs.com/features/cameras#universal-camera
  79387. * @param name Define the name of the camera in the scene
  79388. * @param position Define the start position of the camera in the scene
  79389. * @param scene Define the scene the camera belongs to
  79390. */
  79391. function GamepadCamera(name, position, scene) {
  79392. return _super.call(this, name, position, scene) || this;
  79393. }
  79394. /**
  79395. * Gets the current object class name.
  79396. * @return the class name
  79397. */
  79398. GamepadCamera.prototype.getClassName = function () {
  79399. return "GamepadCamera";
  79400. };
  79401. return GamepadCamera;
  79402. }(BABYLON.UniversalCamera));
  79403. BABYLON.GamepadCamera = GamepadCamera;
  79404. })(BABYLON || (BABYLON = {}));
  79405. //# sourceMappingURL=babylon.gamepadCamera.js.map
  79406. var BABYLON;
  79407. (function (BABYLON) {
  79408. var PostProcessRenderPipelineManager = /** @class */ (function () {
  79409. function PostProcessRenderPipelineManager() {
  79410. this._renderPipelines = {};
  79411. }
  79412. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  79413. this._renderPipelines[renderPipeline._name] = renderPipeline;
  79414. };
  79415. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  79416. if (unique === void 0) { unique = false; }
  79417. var renderPipeline = this._renderPipelines[renderPipelineName];
  79418. if (!renderPipeline) {
  79419. return;
  79420. }
  79421. renderPipeline._attachCameras(cameras, unique);
  79422. };
  79423. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  79424. var renderPipeline = this._renderPipelines[renderPipelineName];
  79425. if (!renderPipeline) {
  79426. return;
  79427. }
  79428. renderPipeline._detachCameras(cameras);
  79429. };
  79430. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  79431. var renderPipeline = this._renderPipelines[renderPipelineName];
  79432. if (!renderPipeline) {
  79433. return;
  79434. }
  79435. renderPipeline._enableEffect(renderEffectName, cameras);
  79436. };
  79437. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  79438. var renderPipeline = this._renderPipelines[renderPipelineName];
  79439. if (!renderPipeline) {
  79440. return;
  79441. }
  79442. renderPipeline._disableEffect(renderEffectName, cameras);
  79443. };
  79444. PostProcessRenderPipelineManager.prototype.update = function () {
  79445. for (var renderPipelineName in this._renderPipelines) {
  79446. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  79447. var pipeline = this._renderPipelines[renderPipelineName];
  79448. if (!pipeline.isSupported) {
  79449. pipeline.dispose();
  79450. delete this._renderPipelines[renderPipelineName];
  79451. }
  79452. else {
  79453. pipeline._update();
  79454. }
  79455. }
  79456. }
  79457. };
  79458. /** @hidden */
  79459. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  79460. for (var renderPipelineName in this._renderPipelines) {
  79461. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  79462. var pipeline = this._renderPipelines[renderPipelineName];
  79463. pipeline._rebuild();
  79464. }
  79465. }
  79466. };
  79467. PostProcessRenderPipelineManager.prototype.dispose = function () {
  79468. for (var renderPipelineName in this._renderPipelines) {
  79469. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  79470. var pipeline = this._renderPipelines[renderPipelineName];
  79471. pipeline.dispose();
  79472. }
  79473. }
  79474. };
  79475. return PostProcessRenderPipelineManager;
  79476. }());
  79477. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  79478. })(BABYLON || (BABYLON = {}));
  79479. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  79480. var BABYLON;
  79481. (function (BABYLON) {
  79482. Object.defineProperty(BABYLON.Scene.prototype, "postProcessRenderPipelineManager", {
  79483. get: function () {
  79484. if (!this._postProcessRenderPipelineManager) {
  79485. // Register the G Buffer component to the scene.
  79486. var component = this._getComponent(BABYLON.SceneComponentConstants.NAME_POSTPROCESSRENDERPIPELINEMANAGER);
  79487. if (!component) {
  79488. component = new PostProcessRenderPipelineManagerSceneComponent(this);
  79489. this._addComponent(component);
  79490. }
  79491. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  79492. }
  79493. return this._postProcessRenderPipelineManager;
  79494. },
  79495. enumerable: true,
  79496. configurable: true
  79497. });
  79498. /**
  79499. * Defines the Render Pipeline scene component responsible to rendering pipelines
  79500. */
  79501. var PostProcessRenderPipelineManagerSceneComponent = /** @class */ (function () {
  79502. /**
  79503. * Creates a new instance of the component for the given scene
  79504. * @param scene Defines the scene to register the component in
  79505. */
  79506. function PostProcessRenderPipelineManagerSceneComponent(scene) {
  79507. /**
  79508. * The component name helpfull to identify the component in the list of scene components.
  79509. */
  79510. this.name = BABYLON.SceneComponentConstants.NAME_POSTPROCESSRENDERPIPELINEMANAGER;
  79511. this.scene = scene;
  79512. }
  79513. /**
  79514. * Registers the component in a given scene
  79515. */
  79516. PostProcessRenderPipelineManagerSceneComponent.prototype.register = function () {
  79517. this.scene._gatherRenderTargetsStage.registerStep(BABYLON.SceneComponentConstants.STEP_GATHERRENDERTARGETS_POSTPROCESSRENDERPIPELINEMANAGER, this, this._gatherRenderTargets);
  79518. };
  79519. /**
  79520. * Rebuilds the elements related to this component in case of
  79521. * context lost for instance.
  79522. */
  79523. PostProcessRenderPipelineManagerSceneComponent.prototype.rebuild = function () {
  79524. if (this.scene._postProcessRenderPipelineManager) {
  79525. this.scene._postProcessRenderPipelineManager._rebuild();
  79526. }
  79527. };
  79528. /**
  79529. * Disposes the component and the associated ressources
  79530. */
  79531. PostProcessRenderPipelineManagerSceneComponent.prototype.dispose = function () {
  79532. if (this.scene._postProcessRenderPipelineManager) {
  79533. this.scene._postProcessRenderPipelineManager.dispose();
  79534. }
  79535. };
  79536. PostProcessRenderPipelineManagerSceneComponent.prototype._gatherRenderTargets = function (renderTargets) {
  79537. if (this.scene._postProcessRenderPipelineManager) {
  79538. this.scene._postProcessRenderPipelineManager.update();
  79539. }
  79540. };
  79541. return PostProcessRenderPipelineManagerSceneComponent;
  79542. }());
  79543. BABYLON.PostProcessRenderPipelineManagerSceneComponent = PostProcessRenderPipelineManagerSceneComponent;
  79544. })(BABYLON || (BABYLON = {}));
  79545. //# sourceMappingURL=babylon.postProcessRenderPipelineManagerSceneComponent.js.map
  79546. var BABYLON;
  79547. (function (BABYLON) {
  79548. /**
  79549. * This represents a set of one or more post processes in Babylon.
  79550. * A post process can be used to apply a shader to a texture after it is rendered.
  79551. * @example https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  79552. */
  79553. var PostProcessRenderEffect = /** @class */ (function () {
  79554. /**
  79555. * Instantiates a post process render effect.
  79556. * A post process can be used to apply a shader to a texture after it is rendered.
  79557. * @param engine The engine the effect is tied to
  79558. * @param name The name of the effect
  79559. * @param getPostProcesses A function that returns a set of post processes which the effect will run in order to be run.
  79560. * @param singleInstance False if this post process can be run on multiple cameras. (default: true)
  79561. */
  79562. function PostProcessRenderEffect(engine, name, getPostProcesses, singleInstance) {
  79563. this._name = name;
  79564. this._singleInstance = singleInstance || true;
  79565. this._getPostProcesses = getPostProcesses;
  79566. this._cameras = {};
  79567. this._indicesForCamera = {};
  79568. this._postProcesses = {};
  79569. }
  79570. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  79571. /**
  79572. * Checks if all the post processes in the effect are supported.
  79573. */
  79574. get: function () {
  79575. for (var index in this._postProcesses) {
  79576. if (this._postProcesses.hasOwnProperty(index)) {
  79577. var pps = this._postProcesses[index];
  79578. for (var ppIndex = 0; ppIndex < pps.length; ppIndex++) {
  79579. if (!pps[ppIndex].isSupported) {
  79580. return false;
  79581. }
  79582. }
  79583. }
  79584. }
  79585. return true;
  79586. },
  79587. enumerable: true,
  79588. configurable: true
  79589. });
  79590. /**
  79591. * Updates the current state of the effect
  79592. * @hidden
  79593. */
  79594. PostProcessRenderEffect.prototype._update = function () {
  79595. };
  79596. /**
  79597. * Attaches the effect on cameras
  79598. * @param cameras The camera to attach to.
  79599. * @hidden
  79600. */
  79601. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  79602. var _this = this;
  79603. var cameraKey;
  79604. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  79605. if (!cams) {
  79606. return;
  79607. }
  79608. for (var i = 0; i < cams.length; i++) {
  79609. var camera = cams[i];
  79610. var cameraName = camera.name;
  79611. if (this._singleInstance) {
  79612. cameraKey = 0;
  79613. }
  79614. else {
  79615. cameraKey = cameraName;
  79616. }
  79617. if (!this._postProcesses[cameraKey]) {
  79618. var postProcess = this._getPostProcesses();
  79619. if (postProcess) {
  79620. this._postProcesses[cameraKey] = Array.isArray(postProcess) ? postProcess : [postProcess];
  79621. }
  79622. }
  79623. if (!this._indicesForCamera[cameraName]) {
  79624. this._indicesForCamera[cameraName] = [];
  79625. }
  79626. this._postProcesses[cameraKey].forEach(function (postProcess) {
  79627. var index = camera.attachPostProcess(postProcess);
  79628. _this._indicesForCamera[cameraName].push(index);
  79629. });
  79630. if (!this._cameras[cameraName]) {
  79631. this._cameras[cameraName] = camera;
  79632. }
  79633. }
  79634. };
  79635. /**
  79636. * Detatches the effect on cameras
  79637. * @param cameras The camera to detatch from.
  79638. * @hidden
  79639. */
  79640. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  79641. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  79642. if (!cams) {
  79643. return;
  79644. }
  79645. for (var i = 0; i < cams.length; i++) {
  79646. var camera = cams[i];
  79647. var cameraName = camera.name;
  79648. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  79649. camera.detachPostProcess(postProcess);
  79650. });
  79651. if (this._cameras[cameraName]) {
  79652. //this._indicesForCamera.splice(index, 1);
  79653. this._cameras[cameraName] = null;
  79654. }
  79655. }
  79656. };
  79657. /**
  79658. * Enables the effect on given cameras
  79659. * @param cameras The camera to enable.
  79660. * @hidden
  79661. */
  79662. PostProcessRenderEffect.prototype._enable = function (cameras) {
  79663. var _this = this;
  79664. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  79665. if (!cams) {
  79666. return;
  79667. }
  79668. for (var i = 0; i < cams.length; i++) {
  79669. var camera = cams[i];
  79670. var cameraName = camera.name;
  79671. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  79672. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined || camera._postProcesses[this._indicesForCamera[cameraName][j]] === null) {
  79673. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  79674. cams[i].attachPostProcess(postProcess, _this._indicesForCamera[cameraName][j]);
  79675. });
  79676. }
  79677. }
  79678. }
  79679. };
  79680. /**
  79681. * Disables the effect on the given cameras
  79682. * @param cameras The camera to disable.
  79683. * @hidden
  79684. */
  79685. PostProcessRenderEffect.prototype._disable = function (cameras) {
  79686. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  79687. if (!cams) {
  79688. return;
  79689. }
  79690. for (var i = 0; i < cams.length; i++) {
  79691. var camera = cams[i];
  79692. var cameraName = camera.name;
  79693. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  79694. camera.detachPostProcess(postProcess);
  79695. });
  79696. }
  79697. };
  79698. /**
  79699. * Gets a list of the post processes contained in the effect.
  79700. * @param camera The camera to get the post processes on.
  79701. * @returns The list of the post processes in the effect.
  79702. */
  79703. PostProcessRenderEffect.prototype.getPostProcesses = function (camera) {
  79704. if (this._singleInstance) {
  79705. return this._postProcesses[0];
  79706. }
  79707. else {
  79708. if (!camera) {
  79709. return null;
  79710. }
  79711. return this._postProcesses[camera.name];
  79712. }
  79713. };
  79714. return PostProcessRenderEffect;
  79715. }());
  79716. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  79717. })(BABYLON || (BABYLON = {}));
  79718. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  79719. var BABYLON;
  79720. (function (BABYLON) {
  79721. var PostProcessRenderPipeline = /** @class */ (function () {
  79722. function PostProcessRenderPipeline(engine, name) {
  79723. this.engine = engine;
  79724. this._name = name;
  79725. this._renderEffects = {};
  79726. this._renderEffectsForIsolatedPass = new Array();
  79727. this._cameras = [];
  79728. }
  79729. PostProcessRenderPipeline.prototype.getClassName = function () {
  79730. return "PostProcessRenderPipeline";
  79731. };
  79732. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  79733. get: function () {
  79734. for (var renderEffectName in this._renderEffects) {
  79735. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  79736. if (!this._renderEffects[renderEffectName].isSupported) {
  79737. return false;
  79738. }
  79739. }
  79740. }
  79741. return true;
  79742. },
  79743. enumerable: true,
  79744. configurable: true
  79745. });
  79746. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  79747. this._renderEffects[renderEffect._name] = renderEffect;
  79748. };
  79749. // private
  79750. /** @hidden */
  79751. PostProcessRenderPipeline.prototype._rebuild = function () {
  79752. };
  79753. /** @hidden */
  79754. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  79755. var renderEffects = this._renderEffects[renderEffectName];
  79756. if (!renderEffects) {
  79757. return;
  79758. }
  79759. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  79760. };
  79761. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  79762. var renderEffects = this._renderEffects[renderEffectName];
  79763. if (!renderEffects) {
  79764. return;
  79765. }
  79766. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  79767. };
  79768. /** @hidden */
  79769. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  79770. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  79771. if (!cams) {
  79772. return;
  79773. }
  79774. var indicesToDelete = [];
  79775. var i;
  79776. for (i = 0; i < cams.length; i++) {
  79777. var camera = cams[i];
  79778. var cameraName = camera.name;
  79779. if (this._cameras.indexOf(camera) === -1) {
  79780. this._cameras[cameraName] = camera;
  79781. }
  79782. else if (unique) {
  79783. indicesToDelete.push(i);
  79784. }
  79785. }
  79786. for (i = 0; i < indicesToDelete.length; i++) {
  79787. cameras.splice(indicesToDelete[i], 1);
  79788. }
  79789. for (var renderEffectName in this._renderEffects) {
  79790. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  79791. this._renderEffects[renderEffectName]._attachCameras(cams);
  79792. }
  79793. }
  79794. };
  79795. /** @hidden */
  79796. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  79797. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  79798. if (!cams) {
  79799. return;
  79800. }
  79801. for (var renderEffectName in this._renderEffects) {
  79802. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  79803. this._renderEffects[renderEffectName]._detachCameras(cams);
  79804. }
  79805. }
  79806. for (var i = 0; i < cams.length; i++) {
  79807. this._cameras.splice(this._cameras.indexOf(cams[i]), 1);
  79808. }
  79809. };
  79810. /** @hidden */
  79811. PostProcessRenderPipeline.prototype._update = function () {
  79812. for (var renderEffectName in this._renderEffects) {
  79813. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  79814. this._renderEffects[renderEffectName]._update();
  79815. }
  79816. }
  79817. for (var i = 0; i < this._cameras.length; i++) {
  79818. var cameraName = this._cameras[i].name;
  79819. if (this._renderEffectsForIsolatedPass[cameraName]) {
  79820. this._renderEffectsForIsolatedPass[cameraName]._update();
  79821. }
  79822. }
  79823. };
  79824. /** @hidden */
  79825. PostProcessRenderPipeline.prototype._reset = function () {
  79826. this._renderEffects = {};
  79827. this._renderEffectsForIsolatedPass = new Array();
  79828. };
  79829. PostProcessRenderPipeline.prototype._enableMSAAOnFirstPostProcess = function (sampleCount) {
  79830. // 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)
  79831. var effectKeys = Object.keys(this._renderEffects);
  79832. if (this.engine.webGLVersion >= 2 && effectKeys.length > 0) {
  79833. var postProcesses = this._renderEffects[effectKeys[0]].getPostProcesses();
  79834. if (postProcesses) {
  79835. postProcesses[0].samples = sampleCount;
  79836. return true;
  79837. }
  79838. }
  79839. return false;
  79840. };
  79841. PostProcessRenderPipeline.prototype.dispose = function () {
  79842. // Must be implemented by children
  79843. };
  79844. __decorate([
  79845. BABYLON.serialize()
  79846. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  79847. return PostProcessRenderPipeline;
  79848. }());
  79849. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  79850. })(BABYLON || (BABYLON = {}));
  79851. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  79852. var BABYLON;
  79853. (function (BABYLON) {
  79854. /**
  79855. * This represents a depth renderer in Babylon.
  79856. * A depth renderer will render to it's depth map every frame which can be displayed or used in post processing
  79857. */
  79858. var DepthRenderer = /** @class */ (function () {
  79859. /**
  79860. * Instantiates a depth renderer
  79861. * @param scene The scene the renderer belongs to
  79862. * @param type The texture type of the depth map (default: Engine.TEXTURETYPE_FLOAT)
  79863. * @param camera The camera to be used to render the depth map (default: scene's active camera)
  79864. */
  79865. function DepthRenderer(scene, type, camera) {
  79866. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  79867. if (camera === void 0) { camera = null; }
  79868. var _this = this;
  79869. /**
  79870. * Specifiess that the depth renderer will only be used within
  79871. * the camera it is created for.
  79872. * This can help forcing its rendering during the camera processing.
  79873. */
  79874. this.useOnlyInActiveCamera = false;
  79875. this._scene = scene;
  79876. // Register the G Buffer component to the scene.
  79877. var component = scene._getComponent(BABYLON.SceneComponentConstants.NAME_DEPTHRENDERER);
  79878. if (!component) {
  79879. component = new BABYLON.DepthRendererSceneComponent(scene);
  79880. scene._addComponent(component);
  79881. }
  79882. this._camera = camera;
  79883. var engine = scene.getEngine();
  79884. // Render target
  79885. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  79886. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  79887. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  79888. this._depthMap.refreshRate = 1;
  79889. this._depthMap.renderParticles = false;
  79890. this._depthMap.renderList = null;
  79891. // Camera to get depth map from to support multiple concurrent cameras
  79892. this._depthMap.activeCamera = this._camera;
  79893. this._depthMap.ignoreCameraViewport = true;
  79894. this._depthMap.useCameraPostProcesses = false;
  79895. // set default depth value to 1.0 (far away)
  79896. this._depthMap.onClearObservable.add(function (engine) {
  79897. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  79898. });
  79899. // Custom render function
  79900. var renderSubMesh = function (subMesh) {
  79901. var mesh = subMesh.getRenderingMesh();
  79902. var scene = _this._scene;
  79903. var engine = scene.getEngine();
  79904. var material = subMesh.getMaterial();
  79905. if (!material) {
  79906. return;
  79907. }
  79908. // Culling and reverse (right handed system)
  79909. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  79910. // Managing instances
  79911. var batch = mesh._getInstancesRenderList(subMesh._id);
  79912. if (batch.mustReturn) {
  79913. return;
  79914. }
  79915. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  79916. var camera = _this._camera || scene.activeCamera;
  79917. if (_this.isReady(subMesh, hardwareInstancedRendering) && camera) {
  79918. engine.enableEffect(_this._effect);
  79919. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  79920. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  79921. _this._effect.setFloat2("depthValues", camera.minZ, camera.minZ + camera.maxZ);
  79922. // Alpha test
  79923. if (material && material.needAlphaTesting()) {
  79924. var alphaTexture = material.getAlphaTestTexture();
  79925. if (alphaTexture) {
  79926. _this._effect.setTexture("diffuseSampler", alphaTexture);
  79927. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  79928. }
  79929. }
  79930. // Bones
  79931. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  79932. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  79933. }
  79934. // Draw
  79935. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  79936. }
  79937. };
  79938. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  79939. var index;
  79940. if (depthOnlySubMeshes.length) {
  79941. engine.setColorWrite(false);
  79942. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  79943. renderSubMesh(depthOnlySubMeshes.data[index]);
  79944. }
  79945. engine.setColorWrite(true);
  79946. }
  79947. for (index = 0; index < opaqueSubMeshes.length; index++) {
  79948. renderSubMesh(opaqueSubMeshes.data[index]);
  79949. }
  79950. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  79951. renderSubMesh(alphaTestSubMeshes.data[index]);
  79952. }
  79953. };
  79954. }
  79955. /**
  79956. * Creates the depth rendering effect and checks if the effect is ready.
  79957. * @param subMesh The submesh to be used to render the depth map of
  79958. * @param useInstances If multiple world instances should be used
  79959. * @returns if the depth renderer is ready to render the depth map
  79960. */
  79961. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  79962. var material = subMesh.getMaterial();
  79963. if (material.disableDepthWrite) {
  79964. return false;
  79965. }
  79966. var defines = [];
  79967. var attribs = [BABYLON.VertexBuffer.PositionKind];
  79968. var mesh = subMesh.getMesh();
  79969. // Alpha test
  79970. if (material && material.needAlphaTesting() && material.getAlphaTestTexture()) {
  79971. defines.push("#define ALPHATEST");
  79972. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  79973. attribs.push(BABYLON.VertexBuffer.UVKind);
  79974. defines.push("#define UV1");
  79975. }
  79976. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  79977. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  79978. defines.push("#define UV2");
  79979. }
  79980. }
  79981. // Bones
  79982. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  79983. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  79984. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  79985. if (mesh.numBoneInfluencers > 4) {
  79986. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  79987. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  79988. }
  79989. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  79990. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  79991. }
  79992. else {
  79993. defines.push("#define NUM_BONE_INFLUENCERS 0");
  79994. }
  79995. // Instances
  79996. if (useInstances) {
  79997. defines.push("#define INSTANCES");
  79998. attribs.push("world0");
  79999. attribs.push("world1");
  80000. attribs.push("world2");
  80001. attribs.push("world3");
  80002. }
  80003. // Get correct effect
  80004. var join = defines.join("\n");
  80005. if (this._cachedDefines !== join) {
  80006. this._cachedDefines = join;
  80007. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  80008. }
  80009. return this._effect.isReady();
  80010. };
  80011. /**
  80012. * Gets the texture which the depth map will be written to.
  80013. * @returns The depth map texture
  80014. */
  80015. DepthRenderer.prototype.getDepthMap = function () {
  80016. return this._depthMap;
  80017. };
  80018. /**
  80019. * Disposes of the depth renderer.
  80020. */
  80021. DepthRenderer.prototype.dispose = function () {
  80022. this._depthMap.dispose();
  80023. };
  80024. return DepthRenderer;
  80025. }());
  80026. BABYLON.DepthRenderer = DepthRenderer;
  80027. })(BABYLON || (BABYLON = {}));
  80028. //# sourceMappingURL=babylon.depthRenderer.js.map
  80029. var BABYLON;
  80030. (function (BABYLON) {
  80031. BABYLON.Scene.prototype.enableDepthRenderer = function (camera) {
  80032. camera = camera || this.activeCamera;
  80033. if (!camera) {
  80034. throw "No camera available to enable depth renderer";
  80035. }
  80036. if (!this._depthRenderer) {
  80037. this._depthRenderer = {};
  80038. }
  80039. if (!this._depthRenderer[camera.id]) {
  80040. var textureType = 0;
  80041. if (this.getEngine().getCaps().textureHalfFloatRender) {
  80042. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  80043. }
  80044. else if (this.getEngine().getCaps().textureFloatRender) {
  80045. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  80046. }
  80047. else {
  80048. throw "Depth renderer does not support int texture type";
  80049. }
  80050. this._depthRenderer[camera.id] = new BABYLON.DepthRenderer(this, textureType, camera);
  80051. }
  80052. return this._depthRenderer[camera.id];
  80053. };
  80054. BABYLON.Scene.prototype.disableDepthRenderer = function (camera) {
  80055. camera = camera || this.activeCamera;
  80056. if (!camera || !this._depthRenderer || !this._depthRenderer[camera.id]) {
  80057. return;
  80058. }
  80059. this._depthRenderer[camera.id].dispose();
  80060. delete this._depthRenderer[camera.id];
  80061. };
  80062. /**
  80063. * Defines the Depth Renderer scene component responsible to manage a depth buffer usefull
  80064. * in several rendering techniques.
  80065. */
  80066. var DepthRendererSceneComponent = /** @class */ (function () {
  80067. /**
  80068. * Creates a new instance of the component for the given scene
  80069. * @param scene Defines the scene to register the component in
  80070. */
  80071. function DepthRendererSceneComponent(scene) {
  80072. /**
  80073. * The component name helpfull to identify the component in the list of scene components.
  80074. */
  80075. this.name = BABYLON.SceneComponentConstants.NAME_DEPTHRENDERER;
  80076. this.scene = scene;
  80077. }
  80078. /**
  80079. * Registers the component in a given scene
  80080. */
  80081. DepthRendererSceneComponent.prototype.register = function () {
  80082. this.scene._gatherRenderTargetsStage.registerStep(BABYLON.SceneComponentConstants.STEP_GATHERRENDERTARGETS_DEPTHRENDERER, this, this._gatherRenderTargets);
  80083. this.scene._gatherActiveCameraRenderTargetsStage.registerStep(BABYLON.SceneComponentConstants.STEP_GATHERACTIVECAMERARENDERTARGETS_DEPTHRENDERER, this, this._gatherActiveCameraRenderTargets);
  80084. };
  80085. /**
  80086. * Rebuilds the elements related to this component in case of
  80087. * context lost for instance.
  80088. */
  80089. DepthRendererSceneComponent.prototype.rebuild = function () {
  80090. // Nothing to do for this component
  80091. };
  80092. /**
  80093. * Disposes the component and the associated ressources
  80094. */
  80095. DepthRendererSceneComponent.prototype.dispose = function () {
  80096. for (var key in this.scene._depthRenderer) {
  80097. this.scene._depthRenderer[key].dispose();
  80098. }
  80099. };
  80100. DepthRendererSceneComponent.prototype._gatherRenderTargets = function (renderTargets) {
  80101. if (this.scene._depthRenderer) {
  80102. for (var key in this.scene._depthRenderer) {
  80103. var depthRenderer = this.scene._depthRenderer[key];
  80104. if (!depthRenderer.useOnlyInActiveCamera) {
  80105. renderTargets.push(depthRenderer.getDepthMap());
  80106. }
  80107. }
  80108. }
  80109. };
  80110. DepthRendererSceneComponent.prototype._gatherActiveCameraRenderTargets = function (renderTargets) {
  80111. if (this.scene._depthRenderer) {
  80112. for (var key in this.scene._depthRenderer) {
  80113. var depthRenderer = this.scene._depthRenderer[key];
  80114. if (depthRenderer.useOnlyInActiveCamera && this.scene.activeCamera.id === key) {
  80115. renderTargets.push(depthRenderer.getDepthMap());
  80116. }
  80117. }
  80118. }
  80119. };
  80120. return DepthRendererSceneComponent;
  80121. }());
  80122. BABYLON.DepthRendererSceneComponent = DepthRendererSceneComponent;
  80123. })(BABYLON || (BABYLON = {}));
  80124. //# sourceMappingURL=babylon.depthRendererSceneComponent.js.map
  80125. var BABYLON;
  80126. (function (BABYLON) {
  80127. /**
  80128. * This renderer is helpfull to fill one of the render target with a geometry buffer.
  80129. */
  80130. var GeometryBufferRenderer = /** @class */ (function () {
  80131. /**
  80132. * Creates a new G Buffer for the scene
  80133. * @param scene The scene the buffer belongs to
  80134. * @param ratio How big is the buffer related to the main canvas.
  80135. */
  80136. function GeometryBufferRenderer(scene, ratio) {
  80137. if (ratio === void 0) { ratio = 1; }
  80138. this._enablePosition = false;
  80139. this._scene = scene;
  80140. this._ratio = ratio;
  80141. // Register the G Buffer component to the scene.
  80142. var component = scene._getComponent(BABYLON.SceneComponentConstants.NAME_GEOMETRYBUFFERRENDERER);
  80143. if (!component) {
  80144. component = new BABYLON.GeometryBufferRendererSceneComponent(scene);
  80145. scene._addComponent(component);
  80146. }
  80147. // Render target
  80148. this._createRenderTargets();
  80149. }
  80150. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  80151. /**
  80152. * Set the render list (meshes to be rendered) used in the G buffer.
  80153. */
  80154. set: function (meshes) {
  80155. this._multiRenderTarget.renderList = meshes;
  80156. },
  80157. enumerable: true,
  80158. configurable: true
  80159. });
  80160. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  80161. /**
  80162. * Gets wether or not G buffer are supported by the running hardware.
  80163. * This requires draw buffer supports
  80164. */
  80165. get: function () {
  80166. return this._multiRenderTarget.isSupported;
  80167. },
  80168. enumerable: true,
  80169. configurable: true
  80170. });
  80171. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  80172. /**
  80173. * Gets wether or not position are enabled for the G buffer.
  80174. */
  80175. get: function () {
  80176. return this._enablePosition;
  80177. },
  80178. /**
  80179. * Sets wether or not position are enabled for the G buffer.
  80180. */
  80181. set: function (enable) {
  80182. this._enablePosition = enable;
  80183. this.dispose();
  80184. this._createRenderTargets();
  80185. },
  80186. enumerable: true,
  80187. configurable: true
  80188. });
  80189. Object.defineProperty(GeometryBufferRenderer.prototype, "scene", {
  80190. /**
  80191. * Gets the scene associated with the buffer.
  80192. */
  80193. get: function () {
  80194. return this._scene;
  80195. },
  80196. enumerable: true,
  80197. configurable: true
  80198. });
  80199. Object.defineProperty(GeometryBufferRenderer.prototype, "ratio", {
  80200. /**
  80201. * Gets the ratio used by the buffer during its creation.
  80202. * How big is the buffer related to the main canvas.
  80203. */
  80204. get: function () {
  80205. return this._ratio;
  80206. },
  80207. enumerable: true,
  80208. configurable: true
  80209. });
  80210. /**
  80211. * Checks wether everything is ready to render a submesh to the G buffer.
  80212. * @param subMesh the submesh to check readiness for
  80213. * @param useInstances is the mesh drawn using instance or not
  80214. * @returns true if ready otherwise false
  80215. */
  80216. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  80217. var material = subMesh.getMaterial();
  80218. if (material && material.disableDepthWrite) {
  80219. return false;
  80220. }
  80221. var defines = [];
  80222. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  80223. var mesh = subMesh.getMesh();
  80224. // Alpha test
  80225. if (material && material.needAlphaTesting()) {
  80226. defines.push("#define ALPHATEST");
  80227. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  80228. attribs.push(BABYLON.VertexBuffer.UVKind);
  80229. defines.push("#define UV1");
  80230. }
  80231. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  80232. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  80233. defines.push("#define UV2");
  80234. }
  80235. }
  80236. // Buffers
  80237. if (this._enablePosition) {
  80238. defines.push("#define POSITION");
  80239. }
  80240. // Bones
  80241. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  80242. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  80243. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  80244. if (mesh.numBoneInfluencers > 4) {
  80245. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  80246. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  80247. }
  80248. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  80249. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  80250. }
  80251. else {
  80252. defines.push("#define NUM_BONE_INFLUENCERS 0");
  80253. }
  80254. // Instances
  80255. if (useInstances) {
  80256. defines.push("#define INSTANCES");
  80257. attribs.push("world0");
  80258. attribs.push("world1");
  80259. attribs.push("world2");
  80260. attribs.push("world3");
  80261. }
  80262. // Get correct effect
  80263. var join = defines.join("\n");
  80264. if (this._cachedDefines !== join) {
  80265. this._cachedDefines = join;
  80266. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join, undefined, undefined, undefined, { buffersCount: this._enablePosition ? 3 : 2 });
  80267. }
  80268. return this._effect.isReady();
  80269. };
  80270. /**
  80271. * Gets the current underlying G Buffer.
  80272. * @returns the buffer
  80273. */
  80274. GeometryBufferRenderer.prototype.getGBuffer = function () {
  80275. return this._multiRenderTarget;
  80276. };
  80277. Object.defineProperty(GeometryBufferRenderer.prototype, "samples", {
  80278. /**
  80279. * Gets the number of samples used to render the buffer (anti aliasing).
  80280. */
  80281. get: function () {
  80282. return this._multiRenderTarget.samples;
  80283. },
  80284. /**
  80285. * Sets the number of samples used to render the buffer (anti aliasing).
  80286. */
  80287. set: function (value) {
  80288. this._multiRenderTarget.samples = value;
  80289. },
  80290. enumerable: true,
  80291. configurable: true
  80292. });
  80293. /**
  80294. * Disposes the renderer and frees up associated resources.
  80295. */
  80296. GeometryBufferRenderer.prototype.dispose = function () {
  80297. this.getGBuffer().dispose();
  80298. };
  80299. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  80300. var _this = this;
  80301. var engine = this._scene.getEngine();
  80302. var count = this._enablePosition ? 3 : 2;
  80303. 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 });
  80304. if (!this.isSupported) {
  80305. return;
  80306. }
  80307. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  80308. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  80309. this._multiRenderTarget.refreshRate = 1;
  80310. this._multiRenderTarget.renderParticles = false;
  80311. this._multiRenderTarget.renderList = null;
  80312. // set default depth value to 1.0 (far away)
  80313. this._multiRenderTarget.onClearObservable.add(function (engine) {
  80314. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  80315. });
  80316. // Custom render function
  80317. var renderSubMesh = function (subMesh) {
  80318. var mesh = subMesh.getRenderingMesh();
  80319. var scene = _this._scene;
  80320. var engine = scene.getEngine();
  80321. var material = subMesh.getMaterial();
  80322. if (!material) {
  80323. return;
  80324. }
  80325. // Culling
  80326. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  80327. // Managing instances
  80328. var batch = mesh._getInstancesRenderList(subMesh._id);
  80329. if (batch.mustReturn) {
  80330. return;
  80331. }
  80332. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  80333. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  80334. engine.enableEffect(_this._effect);
  80335. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  80336. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  80337. _this._effect.setMatrix("view", scene.getViewMatrix());
  80338. // Alpha test
  80339. if (material && material.needAlphaTesting()) {
  80340. var alphaTexture = material.getAlphaTestTexture();
  80341. if (alphaTexture) {
  80342. _this._effect.setTexture("diffuseSampler", alphaTexture);
  80343. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  80344. }
  80345. }
  80346. // Bones
  80347. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  80348. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  80349. }
  80350. // Draw
  80351. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  80352. }
  80353. };
  80354. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  80355. var index;
  80356. if (depthOnlySubMeshes.length) {
  80357. engine.setColorWrite(false);
  80358. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  80359. renderSubMesh(depthOnlySubMeshes.data[index]);
  80360. }
  80361. engine.setColorWrite(true);
  80362. }
  80363. for (index = 0; index < opaqueSubMeshes.length; index++) {
  80364. renderSubMesh(opaqueSubMeshes.data[index]);
  80365. }
  80366. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  80367. renderSubMesh(alphaTestSubMeshes.data[index]);
  80368. }
  80369. };
  80370. };
  80371. return GeometryBufferRenderer;
  80372. }());
  80373. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  80374. })(BABYLON || (BABYLON = {}));
  80375. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  80376. var BABYLON;
  80377. (function (BABYLON) {
  80378. Object.defineProperty(BABYLON.Scene.prototype, "geometryBufferRenderer", {
  80379. get: function () {
  80380. this._geometryBufferRenderer;
  80381. },
  80382. set: function (value) {
  80383. if (value && value.isSupported) {
  80384. this._geometryBufferRenderer = value;
  80385. }
  80386. ;
  80387. },
  80388. enumerable: true,
  80389. configurable: true
  80390. });
  80391. BABYLON.Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  80392. if (ratio === void 0) { ratio = 1; }
  80393. if (this._geometryBufferRenderer) {
  80394. return this._geometryBufferRenderer;
  80395. }
  80396. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  80397. if (!this._geometryBufferRenderer.isSupported) {
  80398. this._geometryBufferRenderer = null;
  80399. }
  80400. return this._geometryBufferRenderer;
  80401. };
  80402. BABYLON.Scene.prototype.disableGeometryBufferRenderer = function () {
  80403. if (!this._geometryBufferRenderer) {
  80404. return;
  80405. }
  80406. this._geometryBufferRenderer.dispose();
  80407. this._geometryBufferRenderer = null;
  80408. };
  80409. /**
  80410. * Defines the Geometry Buffer scene component responsible to manage a G-Buffer useful
  80411. * in several rendering techniques.
  80412. */
  80413. var GeometryBufferRendererSceneComponent = /** @class */ (function () {
  80414. /**
  80415. * Creates a new instance of the component for the given scene
  80416. * @param scene Defines the scene to register the component in
  80417. */
  80418. function GeometryBufferRendererSceneComponent(scene) {
  80419. /**
  80420. * The component name helpful to identify the component in the list of scene components.
  80421. */
  80422. this.name = BABYLON.SceneComponentConstants.NAME_GEOMETRYBUFFERRENDERER;
  80423. this.scene = scene;
  80424. }
  80425. /**
  80426. * Registers the component in a given scene
  80427. */
  80428. GeometryBufferRendererSceneComponent.prototype.register = function () {
  80429. this.scene._gatherRenderTargetsStage.registerStep(BABYLON.SceneComponentConstants.STEP_GATHERRENDERTARGETS_GEOMETRYBUFFERRENDERER, this, this._gatherRenderTargets);
  80430. };
  80431. /**
  80432. * Rebuilds the elements related to this component in case of
  80433. * context lost for instance.
  80434. */
  80435. GeometryBufferRendererSceneComponent.prototype.rebuild = function () {
  80436. // Nothing to do for this component
  80437. };
  80438. /**
  80439. * Disposes the component and the associated ressources
  80440. */
  80441. GeometryBufferRendererSceneComponent.prototype.dispose = function () {
  80442. // Nothing to do for this component
  80443. };
  80444. GeometryBufferRendererSceneComponent.prototype._gatherRenderTargets = function (renderTargets) {
  80445. if (this.scene._geometryBufferRenderer) {
  80446. renderTargets.push(this.scene._geometryBufferRenderer.getGBuffer());
  80447. }
  80448. };
  80449. return GeometryBufferRendererSceneComponent;
  80450. }());
  80451. BABYLON.GeometryBufferRendererSceneComponent = GeometryBufferRendererSceneComponent;
  80452. })(BABYLON || (BABYLON = {}));
  80453. //# sourceMappingURL=babylon.geometryBufferRendererSceneComponent.js.map
  80454. var BABYLON;
  80455. (function (BABYLON) {
  80456. var SSAORenderingPipeline = /** @class */ (function (_super) {
  80457. __extends(SSAORenderingPipeline, _super);
  80458. /**
  80459. * @constructor
  80460. * @param {string} name - The rendering pipeline name
  80461. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  80462. * @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 }
  80463. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  80464. */
  80465. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  80466. var _this = _super.call(this, scene.getEngine(), name) || this;
  80467. // Members
  80468. /**
  80469. * The PassPostProcess id in the pipeline that contains the original scene color
  80470. */
  80471. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  80472. /**
  80473. * The SSAO PostProcess id in the pipeline
  80474. */
  80475. _this.SSAORenderEffect = "SSAORenderEffect";
  80476. /**
  80477. * The horizontal blur PostProcess id in the pipeline
  80478. */
  80479. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  80480. /**
  80481. * The vertical blur PostProcess id in the pipeline
  80482. */
  80483. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  80484. /**
  80485. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  80486. */
  80487. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  80488. /**
  80489. * The output strength of the SSAO post-process. Default value is 1.0.
  80490. */
  80491. _this.totalStrength = 1.0;
  80492. /**
  80493. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  80494. */
  80495. _this.radius = 0.0001;
  80496. /**
  80497. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  80498. * Must not be equal to fallOff and superior to fallOff.
  80499. * Default value is 0.975
  80500. */
  80501. _this.area = 0.0075;
  80502. /**
  80503. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  80504. * Must not be equal to area and inferior to area.
  80505. * Default value is 0.0
  80506. */
  80507. _this.fallOff = 0.000001;
  80508. /**
  80509. * The base color of the SSAO post-process
  80510. * The final result is "base + ssao" between [0, 1]
  80511. */
  80512. _this.base = 0.5;
  80513. _this._firstUpdate = true;
  80514. _this._scene = scene;
  80515. // Set up assets
  80516. _this._createRandomTexture();
  80517. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  80518. var ssaoRatio = ratio.ssaoRatio || ratio;
  80519. var combineRatio = ratio.combineRatio || ratio;
  80520. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  80521. _this._createSSAOPostProcess(ssaoRatio);
  80522. _this._createBlurPostProcess(ssaoRatio);
  80523. _this._createSSAOCombinePostProcess(combineRatio);
  80524. // Set up pipeline
  80525. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  80526. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  80527. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  80528. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  80529. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  80530. // Finish
  80531. scene.postProcessRenderPipelineManager.addPipeline(_this);
  80532. if (cameras)
  80533. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  80534. return _this;
  80535. }
  80536. // Public Methods
  80537. /**
  80538. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  80539. */
  80540. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  80541. if (disableDepthRender === void 0) { disableDepthRender = false; }
  80542. for (var i = 0; i < this._scene.cameras.length; i++) {
  80543. var camera = this._scene.cameras[i];
  80544. this._originalColorPostProcess.dispose(camera);
  80545. this._ssaoPostProcess.dispose(camera);
  80546. this._blurHPostProcess.dispose(camera);
  80547. this._blurVPostProcess.dispose(camera);
  80548. this._ssaoCombinePostProcess.dispose(camera);
  80549. }
  80550. this._randomTexture.dispose();
  80551. if (disableDepthRender)
  80552. this._scene.disableDepthRenderer();
  80553. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  80554. _super.prototype.dispose.call(this);
  80555. };
  80556. // Private Methods
  80557. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  80558. var _this = this;
  80559. var size = 16;
  80560. 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);
  80561. 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);
  80562. this._blurHPostProcess.onActivateObservable.add(function () {
  80563. var dw = _this._blurHPostProcess.width / _this._scene.getEngine().getRenderWidth();
  80564. _this._blurHPostProcess.kernel = size * dw;
  80565. });
  80566. this._blurVPostProcess.onActivateObservable.add(function () {
  80567. var dw = _this._blurVPostProcess.height / _this._scene.getEngine().getRenderHeight();
  80568. _this._blurVPostProcess.kernel = size * dw;
  80569. });
  80570. };
  80571. /** @hidden */
  80572. SSAORenderingPipeline.prototype._rebuild = function () {
  80573. this._firstUpdate = true;
  80574. _super.prototype._rebuild.call(this);
  80575. };
  80576. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  80577. var _this = this;
  80578. var numSamples = 16;
  80579. var sampleSphere = [
  80580. 0.5381, 0.1856, -0.4319,
  80581. 0.1379, 0.2486, 0.4430,
  80582. 0.3371, 0.5679, -0.0057,
  80583. -0.6999, -0.0451, -0.0019,
  80584. 0.0689, -0.1598, -0.8547,
  80585. 0.0560, 0.0069, -0.1843,
  80586. -0.0146, 0.1402, 0.0762,
  80587. 0.0100, -0.1924, -0.0344,
  80588. -0.3577, -0.5301, -0.4358,
  80589. -0.3169, 0.1063, 0.0158,
  80590. 0.0103, -0.5869, 0.0046,
  80591. -0.0897, -0.4940, 0.3287,
  80592. 0.7119, -0.0154, -0.0918,
  80593. -0.0533, 0.0596, -0.5411,
  80594. 0.0352, -0.0631, 0.5460,
  80595. -0.4776, 0.2847, -0.0271
  80596. ];
  80597. var samplesFactor = 1.0 / numSamples;
  80598. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  80599. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  80600. "area", "fallOff", "base", "range", "viewport"
  80601. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  80602. this._ssaoPostProcess.onApply = function (effect) {
  80603. if (_this._firstUpdate) {
  80604. effect.setArray3("sampleSphere", sampleSphere);
  80605. effect.setFloat("samplesFactor", samplesFactor);
  80606. effect.setFloat("randTextureTiles", 4.0);
  80607. }
  80608. effect.setFloat("totalStrength", _this.totalStrength);
  80609. effect.setFloat("radius", _this.radius);
  80610. effect.setFloat("area", _this.area);
  80611. effect.setFloat("fallOff", _this.fallOff);
  80612. effect.setFloat("base", _this.base);
  80613. effect.setTexture("textureSampler", _this._depthTexture);
  80614. effect.setTexture("randomSampler", _this._randomTexture);
  80615. };
  80616. };
  80617. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  80618. var _this = this;
  80619. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor", "viewport"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  80620. this._ssaoCombinePostProcess.onApply = function (effect) {
  80621. effect.setVector4("viewport", BABYLON.Tmp.Vector4[0].copyFromFloats(0, 0, 1.0, 1.0));
  80622. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  80623. };
  80624. };
  80625. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  80626. var size = 512;
  80627. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  80628. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  80629. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  80630. var context = this._randomTexture.getContext();
  80631. var rand = function (min, max) {
  80632. return Math.random() * (max - min) + min;
  80633. };
  80634. var randVector = BABYLON.Vector3.Zero();
  80635. for (var x = 0; x < size; x++) {
  80636. for (var y = 0; y < size; y++) {
  80637. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  80638. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  80639. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  80640. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  80641. context.fillRect(x, y, 1, 1);
  80642. }
  80643. }
  80644. this._randomTexture.update(false);
  80645. };
  80646. __decorate([
  80647. BABYLON.serialize()
  80648. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  80649. __decorate([
  80650. BABYLON.serialize()
  80651. ], SSAORenderingPipeline.prototype, "radius", void 0);
  80652. __decorate([
  80653. BABYLON.serialize()
  80654. ], SSAORenderingPipeline.prototype, "area", void 0);
  80655. __decorate([
  80656. BABYLON.serialize()
  80657. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  80658. __decorate([
  80659. BABYLON.serialize()
  80660. ], SSAORenderingPipeline.prototype, "base", void 0);
  80661. return SSAORenderingPipeline;
  80662. }(BABYLON.PostProcessRenderPipeline));
  80663. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  80664. })(BABYLON || (BABYLON = {}));
  80665. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  80666. var BABYLON;
  80667. (function (BABYLON) {
  80668. var SSAO2RenderingPipeline = /** @class */ (function (_super) {
  80669. __extends(SSAO2RenderingPipeline, _super);
  80670. /**
  80671. * @constructor
  80672. * @param {string} name - The rendering pipeline name
  80673. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  80674. * @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 }
  80675. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  80676. */
  80677. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  80678. var _this = _super.call(this, scene.getEngine(), name) || this;
  80679. // Members
  80680. /**
  80681. * The PassPostProcess id in the pipeline that contains the original scene color
  80682. */
  80683. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  80684. /**
  80685. * The SSAO PostProcess id in the pipeline
  80686. */
  80687. _this.SSAORenderEffect = "SSAORenderEffect";
  80688. /**
  80689. * The horizontal blur PostProcess id in the pipeline
  80690. */
  80691. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  80692. /**
  80693. * The vertical blur PostProcess id in the pipeline
  80694. */
  80695. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  80696. /**
  80697. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  80698. */
  80699. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  80700. /**
  80701. * The output strength of the SSAO post-process. Default value is 1.0.
  80702. */
  80703. _this.totalStrength = 1.0;
  80704. /**
  80705. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  80706. */
  80707. _this.maxZ = 100.0;
  80708. /**
  80709. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  80710. */
  80711. _this.minZAspect = 0.2;
  80712. _this._samples = 8;
  80713. _this._textureSamples = 1;
  80714. /**
  80715. * Are we using bilateral blur ?
  80716. */
  80717. _this._expensiveBlur = true;
  80718. /**
  80719. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  80720. */
  80721. _this.radius = 2.0;
  80722. /**
  80723. * The base color of the SSAO post-process
  80724. * The final result is "base + ssao" between [0, 1]
  80725. */
  80726. _this.base = 0;
  80727. _this._firstUpdate = true;
  80728. _this._bits = new Uint32Array(1);
  80729. _this._scene = scene;
  80730. _this._ratio = ratio;
  80731. if (!_this.isSupported) {
  80732. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  80733. return _this;
  80734. }
  80735. var ssaoRatio = _this._ratio.ssaoRatio || ratio;
  80736. var blurRatio = _this._ratio.blurRatio || ratio;
  80737. // Set up assets
  80738. var geometryBufferRenderer = scene.enableGeometryBufferRenderer();
  80739. _this._createRandomTexture();
  80740. _this._depthTexture = geometryBufferRenderer.getGBuffer().textures[0];
  80741. _this._normalTexture = geometryBufferRenderer.getGBuffer().textures[1];
  80742. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  80743. _this._originalColorPostProcess.samples = _this.textureSamples;
  80744. _this._createSSAOPostProcess(1.0);
  80745. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  80746. _this._createSSAOCombinePostProcess(blurRatio);
  80747. // Set up pipeline
  80748. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  80749. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  80750. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  80751. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  80752. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  80753. // Finish
  80754. scene.postProcessRenderPipelineManager.addPipeline(_this);
  80755. if (cameras)
  80756. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  80757. return _this;
  80758. }
  80759. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  80760. get: function () {
  80761. return this._samples;
  80762. },
  80763. /**
  80764. * Number of samples used for the SSAO calculations. Default value is 8
  80765. */
  80766. set: function (n) {
  80767. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  80768. this._samples = n;
  80769. this._sampleSphere = this._generateHemisphere();
  80770. this._firstUpdate = true;
  80771. },
  80772. enumerable: true,
  80773. configurable: true
  80774. });
  80775. Object.defineProperty(SSAO2RenderingPipeline.prototype, "textureSamples", {
  80776. get: function () {
  80777. return this._textureSamples;
  80778. },
  80779. /**
  80780. * Number of samples to use for antialiasing
  80781. */
  80782. set: function (n) {
  80783. this._textureSamples = n;
  80784. this._originalColorPostProcess.samples = n;
  80785. this._blurHPostProcess.samples = n;
  80786. this._blurVPostProcess.samples = n;
  80787. this._ssaoPostProcess.samples = n;
  80788. this._ssaoCombinePostProcess.samples = n;
  80789. },
  80790. enumerable: true,
  80791. configurable: true
  80792. });
  80793. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  80794. get: function () {
  80795. return this._expensiveBlur;
  80796. },
  80797. set: function (b) {
  80798. 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"]);
  80799. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  80800. this._expensiveBlur = b;
  80801. this._firstUpdate = true;
  80802. },
  80803. enumerable: true,
  80804. configurable: true
  80805. });
  80806. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  80807. /**
  80808. * Support test.
  80809. */
  80810. get: function () {
  80811. var engine = BABYLON.Engine.LastCreatedEngine;
  80812. if (!engine) {
  80813. return false;
  80814. }
  80815. return engine.getCaps().drawBuffersExtension;
  80816. },
  80817. enumerable: true,
  80818. configurable: true
  80819. });
  80820. // Public Methods
  80821. /**
  80822. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  80823. */
  80824. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  80825. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  80826. for (var i = 0; i < this._scene.cameras.length; i++) {
  80827. var camera = this._scene.cameras[i];
  80828. this._originalColorPostProcess.dispose(camera);
  80829. this._ssaoPostProcess.dispose(camera);
  80830. this._blurHPostProcess.dispose(camera);
  80831. this._blurVPostProcess.dispose(camera);
  80832. this._ssaoCombinePostProcess.dispose(camera);
  80833. }
  80834. this._randomTexture.dispose();
  80835. if (disableGeometryBufferRenderer)
  80836. this._scene.disableGeometryBufferRenderer();
  80837. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  80838. _super.prototype.dispose.call(this);
  80839. };
  80840. // Private Methods
  80841. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  80842. var _this = this;
  80843. this._samplerOffsets = [];
  80844. var expensive = this.expensiveBlur;
  80845. for (var i = -8; i < 8; i++) {
  80846. this._samplerOffsets.push(i * 2 + 0.5);
  80847. }
  80848. 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");
  80849. this._blurHPostProcess.onApply = function (effect) {
  80850. if (!_this._scene.activeCamera) {
  80851. return;
  80852. }
  80853. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width > 0 ? _this._ssaoCombinePostProcess.width : _this._originalColorPostProcess.width);
  80854. effect.setFloat("near", _this._scene.activeCamera.minZ);
  80855. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  80856. effect.setFloat("radius", _this.radius);
  80857. effect.setTexture("depthSampler", _this._depthTexture);
  80858. if (_this._firstUpdate) {
  80859. effect.setArray("samplerOffsets", _this._samplerOffsets);
  80860. }
  80861. };
  80862. 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");
  80863. this._blurVPostProcess.onApply = function (effect) {
  80864. if (!_this._scene.activeCamera) {
  80865. return;
  80866. }
  80867. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height > 0 ? _this._ssaoCombinePostProcess.height : _this._originalColorPostProcess.height);
  80868. effect.setFloat("near", _this._scene.activeCamera.minZ);
  80869. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  80870. effect.setFloat("radius", _this.radius);
  80871. effect.setTexture("depthSampler", _this._depthTexture);
  80872. if (_this._firstUpdate) {
  80873. effect.setArray("samplerOffsets", _this._samplerOffsets);
  80874. _this._firstUpdate = false;
  80875. }
  80876. };
  80877. this._blurHPostProcess.samples = this.textureSamples;
  80878. this._blurVPostProcess.samples = this.textureSamples;
  80879. };
  80880. /** @hidden */
  80881. SSAO2RenderingPipeline.prototype._rebuild = function () {
  80882. this._firstUpdate = true;
  80883. _super.prototype._rebuild.call(this);
  80884. };
  80885. //Van der Corput radical inverse
  80886. SSAO2RenderingPipeline.prototype._radicalInverse_VdC = function (i) {
  80887. this._bits[0] = i;
  80888. this._bits[0] = ((this._bits[0] << 16) | (this._bits[0] >> 16)) >>> 0;
  80889. this._bits[0] = ((this._bits[0] & 0x55555555) << 1) | ((this._bits[0] & 0xAAAAAAAA) >>> 1) >>> 0;
  80890. this._bits[0] = ((this._bits[0] & 0x33333333) << 2) | ((this._bits[0] & 0xCCCCCCCC) >>> 2) >>> 0;
  80891. this._bits[0] = ((this._bits[0] & 0x0F0F0F0F) << 4) | ((this._bits[0] & 0xF0F0F0F0) >>> 4) >>> 0;
  80892. this._bits[0] = ((this._bits[0] & 0x00FF00FF) << 8) | ((this._bits[0] & 0xFF00FF00) >>> 8) >>> 0;
  80893. return this._bits[0] * 2.3283064365386963e-10; // / 0x100000000 or / 4294967296
  80894. };
  80895. SSAO2RenderingPipeline.prototype._hammersley = function (i, n) {
  80896. return [i / n, this._radicalInverse_VdC(i)];
  80897. };
  80898. SSAO2RenderingPipeline.prototype._hemisphereSample_uniform = function (u, v) {
  80899. var phi = v * 2.0 * Math.PI;
  80900. // rejecting samples that are close to tangent plane to avoid z-fighting artifacts
  80901. var cosTheta = 1.0 - (u * 0.85 + 0.15);
  80902. var sinTheta = Math.sqrt(1.0 - cosTheta * cosTheta);
  80903. return new BABYLON.Vector3(Math.cos(phi) * sinTheta, Math.sin(phi) * sinTheta, cosTheta);
  80904. };
  80905. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  80906. var numSamples = this.samples;
  80907. var result = [];
  80908. var vector;
  80909. var i = 0;
  80910. while (i < numSamples) {
  80911. if (numSamples < 16) {
  80912. vector = this._hemisphereSample_uniform(Math.random(), Math.random());
  80913. }
  80914. else {
  80915. var rand = this._hammersley(i, numSamples);
  80916. vector = this._hemisphereSample_uniform(rand[0], rand[1]);
  80917. }
  80918. result.push(vector.x, vector.y, vector.z);
  80919. i++;
  80920. }
  80921. return result;
  80922. };
  80923. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  80924. var _this = this;
  80925. var numSamples = this.samples;
  80926. this._sampleSphere = this._generateHemisphere();
  80927. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  80928. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  80929. "base", "range", "projection", "near", "far", "texelSize",
  80930. "xViewport", "yViewport", "maxZ", "minZAspect"
  80931. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  80932. this._ssaoPostProcess.onApply = function (effect) {
  80933. if (_this._firstUpdate) {
  80934. effect.setArray3("sampleSphere", _this._sampleSphere);
  80935. effect.setFloat("randTextureTiles", 32.0);
  80936. }
  80937. if (!_this._scene.activeCamera) {
  80938. return;
  80939. }
  80940. effect.setFloat("samplesFactor", 1 / _this.samples);
  80941. effect.setFloat("totalStrength", _this.totalStrength);
  80942. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  80943. effect.setFloat("radius", _this.radius);
  80944. effect.setFloat("maxZ", _this.maxZ);
  80945. effect.setFloat("minZAspect", _this.minZAspect);
  80946. effect.setFloat("base", _this.base);
  80947. effect.setFloat("near", _this._scene.activeCamera.minZ);
  80948. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  80949. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  80950. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  80951. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  80952. effect.setTexture("textureSampler", _this._depthTexture);
  80953. effect.setTexture("normalSampler", _this._normalTexture);
  80954. effect.setTexture("randomSampler", _this._randomTexture);
  80955. };
  80956. this._ssaoPostProcess.samples = this.textureSamples;
  80957. };
  80958. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  80959. var _this = this;
  80960. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor", "viewport"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  80961. this._ssaoCombinePostProcess.onApply = function (effect) {
  80962. var viewport = _this._scene.activeCamera.viewport;
  80963. effect.setVector4("viewport", BABYLON.Tmp.Vector4[0].copyFromFloats(viewport.x, viewport.y, viewport.width, viewport.height));
  80964. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  80965. };
  80966. this._ssaoCombinePostProcess.samples = this.textureSamples;
  80967. };
  80968. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  80969. var size = 128;
  80970. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  80971. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  80972. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  80973. var context = this._randomTexture.getContext();
  80974. var rand = function (min, max) {
  80975. return Math.random() * (max - min) + min;
  80976. };
  80977. var randVector = BABYLON.Vector3.Zero();
  80978. for (var x = 0; x < size; x++) {
  80979. for (var y = 0; y < size; y++) {
  80980. randVector.x = rand(0.0, 1.0);
  80981. randVector.y = rand(0.0, 1.0);
  80982. randVector.z = 0.0;
  80983. randVector.normalize();
  80984. randVector.scaleInPlace(255);
  80985. randVector.x = Math.floor(randVector.x);
  80986. randVector.y = Math.floor(randVector.y);
  80987. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  80988. context.fillRect(x, y, 1, 1);
  80989. }
  80990. }
  80991. this._randomTexture.update(false);
  80992. };
  80993. /**
  80994. * Serialize the rendering pipeline (Used when exporting)
  80995. * @returns the serialized object
  80996. */
  80997. SSAO2RenderingPipeline.prototype.serialize = function () {
  80998. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  80999. serializationObject.customType = "SSAO2RenderingPipeline";
  81000. return serializationObject;
  81001. };
  81002. /**
  81003. * Parse the serialized pipeline
  81004. * @param source Source pipeline.
  81005. * @param scene The scene to load the pipeline to.
  81006. * @param rootUrl The URL of the serialized pipeline.
  81007. * @returns An instantiated pipeline from the serialized object.
  81008. */
  81009. SSAO2RenderingPipeline.Parse = function (source, scene, rootUrl) {
  81010. return BABYLON.SerializationHelper.Parse(function () { return new SSAO2RenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  81011. };
  81012. __decorate([
  81013. BABYLON.serialize()
  81014. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  81015. __decorate([
  81016. BABYLON.serialize()
  81017. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  81018. __decorate([
  81019. BABYLON.serialize()
  81020. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  81021. __decorate([
  81022. BABYLON.serialize("samples")
  81023. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  81024. __decorate([
  81025. BABYLON.serialize("textureSamples")
  81026. ], SSAO2RenderingPipeline.prototype, "_textureSamples", void 0);
  81027. __decorate([
  81028. BABYLON.serialize()
  81029. ], SSAO2RenderingPipeline.prototype, "_ratio", void 0);
  81030. __decorate([
  81031. BABYLON.serialize("expensiveBlur")
  81032. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  81033. __decorate([
  81034. BABYLON.serialize()
  81035. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  81036. __decorate([
  81037. BABYLON.serialize()
  81038. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  81039. return SSAO2RenderingPipeline;
  81040. }(BABYLON.PostProcessRenderPipeline));
  81041. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  81042. })(BABYLON || (BABYLON = {}));
  81043. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  81044. // BABYLON.JS Chromatic Aberration GLSL Shader
  81045. // Author: Olivier Guyot
  81046. // Separates very slightly R, G and B colors on the edges of the screen
  81047. // Inspired by Francois Tarlier & Martins Upitis
  81048. var BABYLON;
  81049. (function (BABYLON) {
  81050. var LensRenderingPipeline = /** @class */ (function (_super) {
  81051. __extends(LensRenderingPipeline, _super);
  81052. /**
  81053. * @constructor
  81054. *
  81055. * Effect parameters are as follow:
  81056. * {
  81057. * chromatic_aberration: number; // from 0 to x (1 for realism)
  81058. * edge_blur: number; // from 0 to x (1 for realism)
  81059. * distortion: number; // from 0 to x (1 for realism)
  81060. * grain_amount: number; // from 0 to 1
  81061. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  81062. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  81063. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  81064. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  81065. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  81066. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  81067. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  81068. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  81069. * }
  81070. * Note: if an effect parameter is unset, effect is disabled
  81071. *
  81072. * @param {string} name - The rendering pipeline name
  81073. * @param {object} parameters - An object containing all parameters (see above)
  81074. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  81075. * @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)
  81076. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  81077. */
  81078. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  81079. if (ratio === void 0) { ratio = 1.0; }
  81080. var _this = _super.call(this, scene.getEngine(), name) || this;
  81081. // Lens effects can be of the following:
  81082. // - chromatic aberration (slight shift of RGB colors)
  81083. // - blur on the edge of the lens
  81084. // - lens distortion
  81085. // - depth-of-field blur & highlights enhancing
  81086. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  81087. // - grain effect (noise or custom texture)
  81088. // Two additional texture samplers are needed:
  81089. // - depth map (for depth-of-field)
  81090. // - grain texture
  81091. /**
  81092. * The chromatic aberration PostProcess id in the pipeline
  81093. */
  81094. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  81095. /**
  81096. * The highlights enhancing PostProcess id in the pipeline
  81097. */
  81098. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  81099. /**
  81100. * The depth-of-field PostProcess id in the pipeline
  81101. */
  81102. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  81103. _this._scene = scene;
  81104. // Fetch texture samplers
  81105. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  81106. if (parameters.grain_texture) {
  81107. _this._grainTexture = parameters.grain_texture;
  81108. }
  81109. else {
  81110. _this._createGrainTexture();
  81111. }
  81112. // save parameters
  81113. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  81114. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  81115. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  81116. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  81117. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  81118. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  81119. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  81120. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  81121. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  81122. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  81123. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  81124. // Create effects
  81125. _this._createChromaticAberrationPostProcess(ratio);
  81126. _this._createHighlightsPostProcess(ratio);
  81127. _this._createDepthOfFieldPostProcess(ratio / 4);
  81128. // Set up pipeline
  81129. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  81130. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  81131. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  81132. if (_this._highlightsGain === -1) {
  81133. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  81134. }
  81135. // Finish
  81136. scene.postProcessRenderPipelineManager.addPipeline(_this);
  81137. if (cameras) {
  81138. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  81139. }
  81140. return _this;
  81141. }
  81142. // public methods (self explanatory)
  81143. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  81144. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  81145. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  81146. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  81147. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  81148. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  81149. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  81150. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  81151. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  81152. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  81153. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  81154. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  81155. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  81156. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  81157. };
  81158. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  81159. this._highlightsPostProcess.updateEffect();
  81160. };
  81161. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  81162. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  81163. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  81164. this._highlightsGain = amount;
  81165. };
  81166. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  81167. if (this._highlightsGain === -1) {
  81168. this._highlightsGain = 1.0;
  81169. }
  81170. this._highlightsThreshold = amount;
  81171. };
  81172. LensRenderingPipeline.prototype.disableHighlights = function () {
  81173. this._highlightsGain = -1;
  81174. };
  81175. /**
  81176. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  81177. */
  81178. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  81179. if (disableDepthRender === void 0) { disableDepthRender = false; }
  81180. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  81181. this._chromaticAberrationPostProcess = null;
  81182. this._highlightsPostProcess = null;
  81183. this._depthOfFieldPostProcess = null;
  81184. this._grainTexture.dispose();
  81185. if (disableDepthRender)
  81186. this._scene.disableDepthRenderer();
  81187. };
  81188. // colors shifting and distortion
  81189. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  81190. var _this = this;
  81191. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height", "direction", "radialIntensity", "centerPosition"], // uniforms
  81192. [], // samplers
  81193. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  81194. this._chromaticAberrationPostProcess.onApply = function (effect) {
  81195. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  81196. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  81197. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  81198. effect.setFloat('radialIntensity', 1);
  81199. effect.setFloat2('direction', 17, 17);
  81200. effect.setFloat2('centerPosition', 0.5, 0.5);
  81201. };
  81202. };
  81203. // highlights enhancing
  81204. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  81205. var _this = this;
  81206. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  81207. [], // samplers
  81208. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  81209. this._highlightsPostProcess.onApply = function (effect) {
  81210. effect.setFloat('gain', _this._highlightsGain);
  81211. effect.setFloat('threshold', _this._highlightsThreshold);
  81212. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  81213. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  81214. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  81215. };
  81216. };
  81217. // colors shifting and distortion
  81218. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  81219. var _this = this;
  81220. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  81221. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  81222. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  81223. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  81224. this._depthOfFieldPostProcess.onApply = function (effect) {
  81225. effect.setTexture("depthSampler", _this._depthTexture);
  81226. effect.setTexture("grainSampler", _this._grainTexture);
  81227. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  81228. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  81229. effect.setFloat('grain_amount', _this._grainAmount);
  81230. effect.setBool('blur_noise', _this._blurNoise);
  81231. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  81232. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  81233. effect.setFloat('distortion', _this._distortion);
  81234. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  81235. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  81236. effect.setFloat('aperture', _this._dofAperture);
  81237. effect.setFloat('darken', _this._dofDarken);
  81238. effect.setFloat('edge_blur', _this._edgeBlur);
  81239. effect.setBool('highlights', (_this._highlightsGain !== -1));
  81240. if (_this._scene.activeCamera) {
  81241. effect.setFloat('near', _this._scene.activeCamera.minZ);
  81242. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  81243. }
  81244. };
  81245. };
  81246. // creates a black and white random noise texture, 512x512
  81247. LensRenderingPipeline.prototype._createGrainTexture = function () {
  81248. var size = 512;
  81249. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  81250. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  81251. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  81252. var context = this._grainTexture.getContext();
  81253. var rand = function (min, max) {
  81254. return Math.random() * (max - min) + min;
  81255. };
  81256. var value;
  81257. for (var x = 0; x < size; x++) {
  81258. for (var y = 0; y < size; y++) {
  81259. value = Math.floor(rand(0.42, 0.58) * 255);
  81260. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  81261. context.fillRect(x, y, 1, 1);
  81262. }
  81263. }
  81264. this._grainTexture.update(false);
  81265. };
  81266. return LensRenderingPipeline;
  81267. }(BABYLON.PostProcessRenderPipeline));
  81268. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  81269. })(BABYLON || (BABYLON = {}));
  81270. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  81271. var BABYLON;
  81272. (function (BABYLON) {
  81273. var StandardRenderingPipeline = /** @class */ (function (_super) {
  81274. __extends(StandardRenderingPipeline, _super);
  81275. /**
  81276. * @constructor
  81277. * @param {string} name - The rendering pipeline name
  81278. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  81279. * @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)
  81280. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  81281. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  81282. */
  81283. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  81284. if (originalPostProcess === void 0) { originalPostProcess = null; }
  81285. var _this = _super.call(this, scene.getEngine(), name) || this;
  81286. /**
  81287. * Post-process used to down scale an image x4
  81288. */
  81289. _this.downSampleX4PostProcess = null;
  81290. /**
  81291. * Post-process used to calculate the illuminated surfaces controlled by a threshold
  81292. */
  81293. _this.brightPassPostProcess = null;
  81294. /**
  81295. * Post-process array storing all the horizontal blur post-processes used by the pipeline
  81296. */
  81297. _this.blurHPostProcesses = [];
  81298. /**
  81299. * Post-process array storing all the vertical blur post-processes used by the pipeline
  81300. */
  81301. _this.blurVPostProcesses = [];
  81302. /**
  81303. * Post-process used to add colors of 2 textures (typically brightness + real scene color)
  81304. */
  81305. _this.textureAdderPostProcess = null;
  81306. /**
  81307. * Post-process used to create volumetric lighting effect
  81308. */
  81309. _this.volumetricLightPostProcess = null;
  81310. /**
  81311. * Post-process used to smooth the previous volumetric light post-process on the X axis
  81312. */
  81313. _this.volumetricLightSmoothXPostProcess = null;
  81314. /**
  81315. * Post-process used to smooth the previous volumetric light post-process on the Y axis
  81316. */
  81317. _this.volumetricLightSmoothYPostProcess = null;
  81318. /**
  81319. * Post-process used to merge the volumetric light effect and the real scene color
  81320. */
  81321. _this.volumetricLightMergePostProces = null;
  81322. /**
  81323. * Post-process used to store the final volumetric light post-process (attach/detach for debug purpose)
  81324. */
  81325. _this.volumetricLightFinalPostProcess = null;
  81326. /**
  81327. * Base post-process used to calculate the average luminance of the final image for HDR
  81328. */
  81329. _this.luminancePostProcess = null;
  81330. /**
  81331. * Post-processes used to create down sample post-processes in order to get
  81332. * the average luminance of the final image for HDR
  81333. * Array of length "StandardRenderingPipeline.LuminanceSteps"
  81334. */
  81335. _this.luminanceDownSamplePostProcesses = [];
  81336. /**
  81337. * Post-process used to create a HDR effect (light adaptation)
  81338. */
  81339. _this.hdrPostProcess = null;
  81340. /**
  81341. * Post-process used to store the final texture adder post-process (attach/detach for debug purpose)
  81342. */
  81343. _this.textureAdderFinalPostProcess = null;
  81344. /**
  81345. * Post-process used to store the final lens flare post-process (attach/detach for debug purpose)
  81346. */
  81347. _this.lensFlareFinalPostProcess = null;
  81348. /**
  81349. * Post-process used to merge the final HDR post-process and the real scene color
  81350. */
  81351. _this.hdrFinalPostProcess = null;
  81352. /**
  81353. * Post-process used to create a lens flare effect
  81354. */
  81355. _this.lensFlarePostProcess = null;
  81356. /**
  81357. * Post-process that merges the result of the lens flare post-process and the real scene color
  81358. */
  81359. _this.lensFlareComposePostProcess = null;
  81360. /**
  81361. * Post-process used to create a motion blur effect
  81362. */
  81363. _this.motionBlurPostProcess = null;
  81364. /**
  81365. * Post-process used to create a depth of field effect
  81366. */
  81367. _this.depthOfFieldPostProcess = null;
  81368. /**
  81369. * The Fast Approximate Anti-Aliasing post process which attemps to remove aliasing from an image.
  81370. */
  81371. _this.fxaaPostProcess = null;
  81372. // Values
  81373. /**
  81374. * Represents the brightness threshold in order to configure the illuminated surfaces
  81375. */
  81376. _this.brightThreshold = 1.0;
  81377. /**
  81378. * Configures the blur intensity used for surexposed surfaces are highlighted surfaces (light halo)
  81379. */
  81380. _this.blurWidth = 512.0;
  81381. /**
  81382. * Sets if the blur for highlighted surfaces must be only horizontal
  81383. */
  81384. _this.horizontalBlur = false;
  81385. /**
  81386. * Sets the overall exposure used by the pipeline
  81387. */
  81388. _this.exposure = 1.0;
  81389. /**
  81390. * Texture used typically to simulate "dirty" on camera lens
  81391. */
  81392. _this.lensTexture = null;
  81393. /**
  81394. * Represents the offset coefficient based on Rayleigh principle. Typically in interval [-0.2, 0.2]
  81395. */
  81396. _this.volumetricLightCoefficient = 0.2;
  81397. /**
  81398. * The overall power of volumetric lights, typically in interval [0, 10] maximum
  81399. */
  81400. _this.volumetricLightPower = 4.0;
  81401. /**
  81402. * Used the set the blur intensity to smooth the volumetric lights
  81403. */
  81404. _this.volumetricLightBlurScale = 64.0;
  81405. /**
  81406. * Light (spot or directional) used to generate the volumetric lights rays
  81407. * The source light must have a shadow generate so the pipeline can get its
  81408. * depth map
  81409. */
  81410. _this.sourceLight = null;
  81411. /**
  81412. * For eye adaptation, represents the minimum luminance the eye can see
  81413. */
  81414. _this.hdrMinimumLuminance = 1.0;
  81415. /**
  81416. * For eye adaptation, represents the decrease luminance speed
  81417. */
  81418. _this.hdrDecreaseRate = 0.5;
  81419. /**
  81420. * For eye adaptation, represents the increase luminance speed
  81421. */
  81422. _this.hdrIncreaseRate = 0.5;
  81423. /**
  81424. * Lens color texture used by the lens flare effect. Mandatory if lens flare effect enabled
  81425. */
  81426. _this.lensColorTexture = null;
  81427. /**
  81428. * The overall strengh for the lens flare effect
  81429. */
  81430. _this.lensFlareStrength = 20.0;
  81431. /**
  81432. * Dispersion coefficient for lens flare ghosts
  81433. */
  81434. _this.lensFlareGhostDispersal = 1.4;
  81435. /**
  81436. * Main lens flare halo width
  81437. */
  81438. _this.lensFlareHaloWidth = 0.7;
  81439. /**
  81440. * Based on the lens distortion effect, defines how much the lens flare result
  81441. * is distorted
  81442. */
  81443. _this.lensFlareDistortionStrength = 16.0;
  81444. /**
  81445. * Lens star texture must be used to simulate rays on the flares and is available
  81446. * in the documentation
  81447. */
  81448. _this.lensStarTexture = null;
  81449. /**
  81450. * As the "lensTexture" (can be the same texture or different), it is used to apply the lens
  81451. * flare effect by taking account of the dirt texture
  81452. */
  81453. _this.lensFlareDirtTexture = null;
  81454. /**
  81455. * Represents the focal length for the depth of field effect
  81456. */
  81457. _this.depthOfFieldDistance = 10.0;
  81458. /**
  81459. * Represents the blur intensity for the blurred part of the depth of field effect
  81460. */
  81461. _this.depthOfFieldBlurWidth = 64.0;
  81462. /**
  81463. * For motion blur, defines how much the image is blurred by the movement
  81464. */
  81465. _this.motionStrength = 1.0;
  81466. /**
  81467. * List of animations for the pipeline (IAnimatable implementation)
  81468. */
  81469. _this.animations = [];
  81470. _this._currentDepthOfFieldSource = null;
  81471. _this._hdrCurrentLuminance = 1.0;
  81472. // Getters and setters
  81473. _this._bloomEnabled = false;
  81474. _this._depthOfFieldEnabled = false;
  81475. _this._vlsEnabled = false;
  81476. _this._lensFlareEnabled = false;
  81477. _this._hdrEnabled = false;
  81478. _this._motionBlurEnabled = false;
  81479. _this._fxaaEnabled = false;
  81480. _this._motionBlurSamples = 64.0;
  81481. _this._volumetricLightStepsCount = 50.0;
  81482. _this._samples = 1;
  81483. _this._cameras = cameras || [];
  81484. // Initialize
  81485. _this._scene = scene;
  81486. _this._basePostProcess = originalPostProcess;
  81487. _this._ratio = ratio;
  81488. // Misc
  81489. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  81490. // Finish
  81491. scene.postProcessRenderPipelineManager.addPipeline(_this);
  81492. _this._buildPipeline();
  81493. return _this;
  81494. }
  81495. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  81496. /**
  81497. * Specifies if the bloom pipeline is enabled
  81498. */
  81499. get: function () {
  81500. return this._bloomEnabled;
  81501. },
  81502. set: function (enabled) {
  81503. if (this._bloomEnabled === enabled) {
  81504. return;
  81505. }
  81506. this._bloomEnabled = enabled;
  81507. this._buildPipeline();
  81508. },
  81509. enumerable: true,
  81510. configurable: true
  81511. });
  81512. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  81513. /**
  81514. * Specifies if the depth of field pipeline is enabed
  81515. */
  81516. get: function () {
  81517. return this._depthOfFieldEnabled;
  81518. },
  81519. set: function (enabled) {
  81520. if (this._depthOfFieldEnabled === enabled) {
  81521. return;
  81522. }
  81523. this._depthOfFieldEnabled = enabled;
  81524. this._buildPipeline();
  81525. },
  81526. enumerable: true,
  81527. configurable: true
  81528. });
  81529. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  81530. /**
  81531. * Specifies if the lens flare pipeline is enabed
  81532. */
  81533. get: function () {
  81534. return this._lensFlareEnabled;
  81535. },
  81536. set: function (enabled) {
  81537. if (this._lensFlareEnabled === enabled) {
  81538. return;
  81539. }
  81540. this._lensFlareEnabled = enabled;
  81541. this._buildPipeline();
  81542. },
  81543. enumerable: true,
  81544. configurable: true
  81545. });
  81546. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  81547. /**
  81548. * Specifies if the HDR pipeline is enabled
  81549. */
  81550. get: function () {
  81551. return this._hdrEnabled;
  81552. },
  81553. set: function (enabled) {
  81554. if (this._hdrEnabled === enabled) {
  81555. return;
  81556. }
  81557. this._hdrEnabled = enabled;
  81558. this._buildPipeline();
  81559. },
  81560. enumerable: true,
  81561. configurable: true
  81562. });
  81563. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  81564. /**
  81565. * Specifies if the volumetric lights scattering effect is enabled
  81566. */
  81567. get: function () {
  81568. return this._vlsEnabled;
  81569. },
  81570. set: function (enabled) {
  81571. if (this._vlsEnabled === enabled) {
  81572. return;
  81573. }
  81574. if (enabled) {
  81575. var geometry = this._scene.enableGeometryBufferRenderer();
  81576. if (!geometry) {
  81577. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  81578. return;
  81579. }
  81580. }
  81581. this._vlsEnabled = enabled;
  81582. this._buildPipeline();
  81583. },
  81584. enumerable: true,
  81585. configurable: true
  81586. });
  81587. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  81588. /**
  81589. * Specifies if the motion blur effect is enabled
  81590. */
  81591. get: function () {
  81592. return this._motionBlurEnabled;
  81593. },
  81594. set: function (enabled) {
  81595. if (this._motionBlurEnabled === enabled) {
  81596. return;
  81597. }
  81598. this._motionBlurEnabled = enabled;
  81599. this._buildPipeline();
  81600. },
  81601. enumerable: true,
  81602. configurable: true
  81603. });
  81604. Object.defineProperty(StandardRenderingPipeline.prototype, "fxaaEnabled", {
  81605. /**
  81606. * Specifies if anti-aliasing is enabled
  81607. */
  81608. get: function () {
  81609. return this._fxaaEnabled;
  81610. },
  81611. set: function (enabled) {
  81612. if (this._fxaaEnabled === enabled) {
  81613. return;
  81614. }
  81615. this._fxaaEnabled = enabled;
  81616. this._buildPipeline();
  81617. },
  81618. enumerable: true,
  81619. configurable: true
  81620. });
  81621. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  81622. /**
  81623. * Specifies the number of steps used to calculate the volumetric lights
  81624. * Typically in interval [50, 200]
  81625. */
  81626. get: function () {
  81627. return this._volumetricLightStepsCount;
  81628. },
  81629. set: function (count) {
  81630. if (this.volumetricLightPostProcess) {
  81631. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  81632. }
  81633. this._volumetricLightStepsCount = count;
  81634. },
  81635. enumerable: true,
  81636. configurable: true
  81637. });
  81638. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  81639. /**
  81640. * Specifies the number of samples used for the motion blur effect
  81641. * Typically in interval [16, 64]
  81642. */
  81643. get: function () {
  81644. return this._motionBlurSamples;
  81645. },
  81646. set: function (samples) {
  81647. if (this.motionBlurPostProcess) {
  81648. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  81649. }
  81650. this._motionBlurSamples = samples;
  81651. },
  81652. enumerable: true,
  81653. configurable: true
  81654. });
  81655. Object.defineProperty(StandardRenderingPipeline.prototype, "samples", {
  81656. /**
  81657. * Specifies MSAA sample count, setting this to 4 will provide 4x anti aliasing. (default: 1)
  81658. */
  81659. get: function () {
  81660. return this._samples;
  81661. },
  81662. set: function (sampleCount) {
  81663. if (this._samples === sampleCount) {
  81664. return;
  81665. }
  81666. this._samples = sampleCount;
  81667. this._buildPipeline();
  81668. },
  81669. enumerable: true,
  81670. configurable: true
  81671. });
  81672. StandardRenderingPipeline.prototype._buildPipeline = function () {
  81673. var _this = this;
  81674. var ratio = this._ratio;
  81675. var scene = this._scene;
  81676. this._disposePostProcesses();
  81677. this._reset();
  81678. // Create pass post-process
  81679. if (!this._basePostProcess) {
  81680. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  81681. this.originalPostProcess.onApply = function (effect) {
  81682. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  81683. };
  81684. }
  81685. else {
  81686. this.originalPostProcess = this._basePostProcess;
  81687. }
  81688. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  81689. this._currentDepthOfFieldSource = this.originalPostProcess;
  81690. if (this._bloomEnabled) {
  81691. // Create down sample X4 post-process
  81692. this._createDownSampleX4PostProcess(scene, ratio / 2);
  81693. // Create bright pass post-process
  81694. this._createBrightPassPostProcess(scene, ratio / 2);
  81695. // Create gaussian blur post-processes (down sampling blurs)
  81696. this._createBlurPostProcesses(scene, ratio / 4, 1);
  81697. // Create texture adder post-process
  81698. this._createTextureAdderPostProcess(scene, ratio);
  81699. // Create depth-of-field source post-process
  81700. 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);
  81701. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  81702. }
  81703. if (this._vlsEnabled) {
  81704. // Create volumetric light
  81705. this._createVolumetricLightPostProcess(scene, ratio);
  81706. // Create volumetric light final post-process
  81707. 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);
  81708. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  81709. }
  81710. if (this._lensFlareEnabled) {
  81711. // Create lens flare post-process
  81712. this._createLensFlarePostProcess(scene, ratio);
  81713. // Create depth-of-field source post-process post lens-flare and disable it now
  81714. 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);
  81715. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  81716. }
  81717. if (this._hdrEnabled) {
  81718. // Create luminance
  81719. this._createLuminancePostProcesses(scene, this._floatTextureType);
  81720. // Create HDR
  81721. this._createHdrPostProcess(scene, ratio);
  81722. // Create depth-of-field source post-process post hdr and disable it now
  81723. 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);
  81724. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  81725. }
  81726. if (this._depthOfFieldEnabled) {
  81727. // Create gaussian blur used by depth-of-field
  81728. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  81729. // Create depth-of-field post-process
  81730. this._createDepthOfFieldPostProcess(scene, ratio);
  81731. }
  81732. if (this._motionBlurEnabled) {
  81733. // Create motion blur post-process
  81734. this._createMotionBlurPostProcess(scene, ratio);
  81735. }
  81736. if (this._fxaaEnabled) {
  81737. // Create fxaa post-process
  81738. this.fxaaPostProcess = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  81739. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRFxaa", function () { return _this.fxaaPostProcess; }, true));
  81740. }
  81741. if (this._cameras !== null) {
  81742. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  81743. }
  81744. if (!this._enableMSAAOnFirstPostProcess(this._samples) && this._samples > 1) {
  81745. BABYLON.Tools.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0");
  81746. }
  81747. };
  81748. // Down Sample X4 Post-Processs
  81749. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  81750. var _this = this;
  81751. var downSampleX4Offsets = new Array(32);
  81752. 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);
  81753. this.downSampleX4PostProcess.onApply = function (effect) {
  81754. var id = 0;
  81755. var width = _this.downSampleX4PostProcess.width;
  81756. var height = _this.downSampleX4PostProcess.height;
  81757. for (var i = -2; i < 2; i++) {
  81758. for (var j = -2; j < 2; j++) {
  81759. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / width);
  81760. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / height);
  81761. id += 2;
  81762. }
  81763. }
  81764. effect.setArray2("dsOffsets", downSampleX4Offsets);
  81765. };
  81766. // Add to pipeline
  81767. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  81768. };
  81769. // Brightpass Post-Process
  81770. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  81771. var _this = this;
  81772. var brightOffsets = new Array(8);
  81773. 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);
  81774. this.brightPassPostProcess.onApply = function (effect) {
  81775. var sU = (1.0 / _this.brightPassPostProcess.width);
  81776. var sV = (1.0 / _this.brightPassPostProcess.height);
  81777. brightOffsets[0] = -0.5 * sU;
  81778. brightOffsets[1] = 0.5 * sV;
  81779. brightOffsets[2] = 0.5 * sU;
  81780. brightOffsets[3] = 0.5 * sV;
  81781. brightOffsets[4] = -0.5 * sU;
  81782. brightOffsets[5] = -0.5 * sV;
  81783. brightOffsets[6] = 0.5 * sU;
  81784. brightOffsets[7] = -0.5 * sV;
  81785. effect.setArray2("dsOffsets", brightOffsets);
  81786. effect.setFloat("brightThreshold", _this.brightThreshold);
  81787. };
  81788. // Add to pipeline
  81789. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  81790. };
  81791. // Create blur H&V post-processes
  81792. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  81793. var _this = this;
  81794. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  81795. var engine = scene.getEngine();
  81796. 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);
  81797. 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);
  81798. blurX.onActivateObservable.add(function () {
  81799. var dw = blurX.width / engine.getRenderWidth();
  81800. blurX.kernel = _this[blurWidthKey] * dw;
  81801. });
  81802. blurY.onActivateObservable.add(function () {
  81803. var dw = blurY.height / engine.getRenderHeight();
  81804. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  81805. });
  81806. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  81807. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  81808. this.blurHPostProcesses.push(blurX);
  81809. this.blurVPostProcesses.push(blurY);
  81810. };
  81811. // Create texture adder post-process
  81812. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  81813. var _this = this;
  81814. 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);
  81815. this.textureAdderPostProcess.onApply = function (effect) {
  81816. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  81817. effect.setTexture("lensSampler", _this.lensTexture);
  81818. effect.setFloat("exposure", _this.exposure);
  81819. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  81820. };
  81821. // Add to pipeline
  81822. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  81823. };
  81824. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  81825. var _this = this;
  81826. var geometryRenderer = scene.enableGeometryBufferRenderer();
  81827. geometryRenderer.enablePosition = true;
  81828. var geometry = geometryRenderer.getGBuffer();
  81829. // Base post-process
  81830. 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));
  81831. var depthValues = BABYLON.Vector2.Zero();
  81832. this.volumetricLightPostProcess.onApply = function (effect) {
  81833. if (_this.sourceLight && _this.sourceLight.getShadowGenerator() && _this._scene.activeCamera) {
  81834. var generator = _this.sourceLight.getShadowGenerator();
  81835. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  81836. effect.setTexture("positionSampler", geometry.textures[2]);
  81837. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  81838. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  81839. effect.setVector3("cameraPosition", _this._scene.activeCamera.globalPosition);
  81840. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  81841. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  81842. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  81843. depthValues.x = _this.sourceLight.getDepthMinZ(_this._scene.activeCamera);
  81844. depthValues.y = _this.sourceLight.getDepthMaxZ(_this._scene.activeCamera);
  81845. effect.setVector2("depthValues", depthValues);
  81846. }
  81847. };
  81848. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  81849. // Smooth
  81850. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  81851. // Merge
  81852. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  81853. this.volumetricLightMergePostProces.onApply = function (effect) {
  81854. effect.setTextureFromPostProcess("originalSampler", _this._bloomEnabled ? _this.textureAdderFinalPostProcess : _this.originalPostProcess);
  81855. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  81856. };
  81857. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  81858. };
  81859. // Create luminance
  81860. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  81861. var _this = this;
  81862. // Create luminance
  81863. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  81864. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  81865. var offsets = [];
  81866. this.luminancePostProcess.onApply = function (effect) {
  81867. var sU = (1.0 / _this.luminancePostProcess.width);
  81868. var sV = (1.0 / _this.luminancePostProcess.height);
  81869. offsets[0] = -0.5 * sU;
  81870. offsets[1] = 0.5 * sV;
  81871. offsets[2] = 0.5 * sU;
  81872. offsets[3] = 0.5 * sV;
  81873. offsets[4] = -0.5 * sU;
  81874. offsets[5] = -0.5 * sV;
  81875. offsets[6] = 0.5 * sU;
  81876. offsets[7] = -0.5 * sV;
  81877. effect.setArray2("lumOffsets", offsets);
  81878. };
  81879. // Add to pipeline
  81880. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  81881. // Create down sample luminance
  81882. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  81883. var size = Math.pow(3, i);
  81884. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  81885. if (i === 0) {
  81886. defines += "#define FINAL_DOWN_SAMPLER";
  81887. }
  81888. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  81889. this.luminanceDownSamplePostProcesses.push(postProcess);
  81890. }
  81891. // Create callbacks and add effects
  81892. var lastLuminance = this.luminancePostProcess;
  81893. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  81894. var downSampleOffsets = new Array(18);
  81895. pp.onApply = function (effect) {
  81896. if (!lastLuminance) {
  81897. return;
  81898. }
  81899. var id = 0;
  81900. for (var x = -1; x < 2; x++) {
  81901. for (var y = -1; y < 2; y++) {
  81902. downSampleOffsets[id] = x / lastLuminance.width;
  81903. downSampleOffsets[id + 1] = y / lastLuminance.height;
  81904. id += 2;
  81905. }
  81906. }
  81907. effect.setArray2("dsOffsets", downSampleOffsets);
  81908. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  81909. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  81910. lastLuminance = _this.luminancePostProcess;
  81911. }
  81912. else {
  81913. lastLuminance = pp;
  81914. }
  81915. };
  81916. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  81917. pp.onAfterRender = function (effect) {
  81918. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  81919. 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);
  81920. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  81921. };
  81922. }
  81923. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  81924. });
  81925. };
  81926. // Create HDR post-process
  81927. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  81928. var _this = this;
  81929. 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);
  81930. var outputLiminance = 1;
  81931. var time = 0;
  81932. var lastTime = 0;
  81933. this.hdrPostProcess.onApply = function (effect) {
  81934. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  81935. time += scene.getEngine().getDeltaTime();
  81936. if (outputLiminance < 0) {
  81937. outputLiminance = _this._hdrCurrentLuminance;
  81938. }
  81939. else {
  81940. var dt = (lastTime - time) / 1000.0;
  81941. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  81942. outputLiminance += _this.hdrDecreaseRate * dt;
  81943. }
  81944. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  81945. outputLiminance -= _this.hdrIncreaseRate * dt;
  81946. }
  81947. else {
  81948. outputLiminance = _this._hdrCurrentLuminance;
  81949. }
  81950. }
  81951. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  81952. effect.setFloat("averageLuminance", outputLiminance);
  81953. lastTime = time;
  81954. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  81955. };
  81956. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  81957. };
  81958. // Create lens flare post-process
  81959. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  81960. var _this = this;
  81961. 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);
  81962. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  81963. this._createBlurPostProcesses(scene, ratio / 4, 2);
  81964. 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);
  81965. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  81966. var resolution = new BABYLON.Vector2(0, 0);
  81967. // Lens flare
  81968. this.lensFlarePostProcess.onApply = function (effect) {
  81969. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  81970. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  81971. effect.setFloat("strength", _this.lensFlareStrength);
  81972. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  81973. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  81974. // Shift
  81975. resolution.x = _this.lensFlarePostProcess.width;
  81976. resolution.y = _this.lensFlarePostProcess.height;
  81977. effect.setVector2("resolution", resolution);
  81978. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  81979. };
  81980. // Compose
  81981. 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);
  81982. 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);
  81983. this.lensFlareComposePostProcess.onApply = function (effect) {
  81984. if (!_this._scene.activeCamera) {
  81985. return;
  81986. }
  81987. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  81988. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  81989. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  81990. // Lens start rotation matrix
  81991. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  81992. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  81993. 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));
  81994. camRot *= 4.0;
  81995. 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);
  81996. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  81997. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  81998. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  81999. };
  82000. };
  82001. // Create depth-of-field post-process
  82002. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  82003. var _this = this;
  82004. 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);
  82005. this.depthOfFieldPostProcess.onApply = function (effect) {
  82006. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  82007. effect.setTexture("depthSampler", _this._getDepthTexture());
  82008. effect.setFloat("distance", _this.depthOfFieldDistance);
  82009. };
  82010. // Add to pipeline
  82011. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  82012. };
  82013. // Create motion blur post-process
  82014. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  82015. var _this = this;
  82016. 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);
  82017. var motionScale = 0;
  82018. var prevViewProjection = BABYLON.Matrix.Identity();
  82019. var invViewProjection = BABYLON.Matrix.Identity();
  82020. var viewProjection = BABYLON.Matrix.Identity();
  82021. var screenSize = BABYLON.Vector2.Zero();
  82022. this.motionBlurPostProcess.onApply = function (effect) {
  82023. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  82024. viewProjection.invertToRef(invViewProjection);
  82025. effect.setMatrix("inverseViewProjection", invViewProjection);
  82026. effect.setMatrix("prevViewProjection", prevViewProjection);
  82027. prevViewProjection = viewProjection;
  82028. screenSize.x = _this.motionBlurPostProcess.width;
  82029. screenSize.y = _this.motionBlurPostProcess.height;
  82030. effect.setVector2("screenSize", screenSize);
  82031. motionScale = scene.getEngine().getFps() / 60.0;
  82032. effect.setFloat("motionScale", motionScale);
  82033. effect.setFloat("motionStrength", _this.motionStrength);
  82034. effect.setTexture("depthSampler", _this._getDepthTexture());
  82035. };
  82036. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  82037. };
  82038. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  82039. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  82040. var renderer = this._scene.enableGeometryBufferRenderer();
  82041. return renderer.getGBuffer().textures[0];
  82042. }
  82043. return this._scene.enableDepthRenderer().getDepthMap();
  82044. };
  82045. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  82046. for (var i = 0; i < this._cameras.length; i++) {
  82047. var camera = this._cameras[i];
  82048. if (this.originalPostProcess) {
  82049. this.originalPostProcess.dispose(camera);
  82050. }
  82051. if (this.downSampleX4PostProcess) {
  82052. this.downSampleX4PostProcess.dispose(camera);
  82053. }
  82054. if (this.brightPassPostProcess) {
  82055. this.brightPassPostProcess.dispose(camera);
  82056. }
  82057. if (this.textureAdderPostProcess) {
  82058. this.textureAdderPostProcess.dispose(camera);
  82059. }
  82060. if (this.textureAdderFinalPostProcess) {
  82061. this.textureAdderFinalPostProcess.dispose(camera);
  82062. }
  82063. if (this.volumetricLightPostProcess) {
  82064. this.volumetricLightPostProcess.dispose(camera);
  82065. }
  82066. if (this.volumetricLightSmoothXPostProcess) {
  82067. this.volumetricLightSmoothXPostProcess.dispose(camera);
  82068. }
  82069. if (this.volumetricLightSmoothYPostProcess) {
  82070. this.volumetricLightSmoothYPostProcess.dispose(camera);
  82071. }
  82072. if (this.volumetricLightMergePostProces) {
  82073. this.volumetricLightMergePostProces.dispose(camera);
  82074. }
  82075. if (this.volumetricLightFinalPostProcess) {
  82076. this.volumetricLightFinalPostProcess.dispose(camera);
  82077. }
  82078. if (this.lensFlarePostProcess) {
  82079. this.lensFlarePostProcess.dispose(camera);
  82080. }
  82081. if (this.lensFlareComposePostProcess) {
  82082. this.lensFlareComposePostProcess.dispose(camera);
  82083. }
  82084. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  82085. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  82086. }
  82087. if (this.luminancePostProcess) {
  82088. this.luminancePostProcess.dispose(camera);
  82089. }
  82090. if (this.hdrPostProcess) {
  82091. this.hdrPostProcess.dispose(camera);
  82092. }
  82093. if (this.hdrFinalPostProcess) {
  82094. this.hdrFinalPostProcess.dispose(camera);
  82095. }
  82096. if (this.depthOfFieldPostProcess) {
  82097. this.depthOfFieldPostProcess.dispose(camera);
  82098. }
  82099. if (this.motionBlurPostProcess) {
  82100. this.motionBlurPostProcess.dispose(camera);
  82101. }
  82102. if (this.fxaaPostProcess) {
  82103. this.fxaaPostProcess.dispose(camera);
  82104. }
  82105. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  82106. this.blurHPostProcesses[j].dispose(camera);
  82107. }
  82108. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  82109. this.blurVPostProcesses[j].dispose(camera);
  82110. }
  82111. }
  82112. this.originalPostProcess = null;
  82113. this.downSampleX4PostProcess = null;
  82114. this.brightPassPostProcess = null;
  82115. this.textureAdderPostProcess = null;
  82116. this.textureAdderFinalPostProcess = null;
  82117. this.volumetricLightPostProcess = null;
  82118. this.volumetricLightSmoothXPostProcess = null;
  82119. this.volumetricLightSmoothYPostProcess = null;
  82120. this.volumetricLightMergePostProces = null;
  82121. this.volumetricLightFinalPostProcess = null;
  82122. this.lensFlarePostProcess = null;
  82123. this.lensFlareComposePostProcess = null;
  82124. this.luminancePostProcess = null;
  82125. this.hdrPostProcess = null;
  82126. this.hdrFinalPostProcess = null;
  82127. this.depthOfFieldPostProcess = null;
  82128. this.motionBlurPostProcess = null;
  82129. this.fxaaPostProcess = null;
  82130. this.luminanceDownSamplePostProcesses = [];
  82131. this.blurHPostProcesses = [];
  82132. this.blurVPostProcesses = [];
  82133. };
  82134. /**
  82135. * Dispose of the pipeline and stop all post processes
  82136. */
  82137. StandardRenderingPipeline.prototype.dispose = function () {
  82138. this._disposePostProcesses();
  82139. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  82140. _super.prototype.dispose.call(this);
  82141. };
  82142. /**
  82143. * Serialize the rendering pipeline (Used when exporting)
  82144. * @returns the serialized object
  82145. */
  82146. StandardRenderingPipeline.prototype.serialize = function () {
  82147. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  82148. if (this.sourceLight) {
  82149. serializationObject.sourceLightId = this.sourceLight.id;
  82150. }
  82151. serializationObject.customType = "StandardRenderingPipeline";
  82152. return serializationObject;
  82153. };
  82154. /**
  82155. * Parse the serialized pipeline
  82156. * @param source Source pipeline.
  82157. * @param scene The scene to load the pipeline to.
  82158. * @param rootUrl The URL of the serialized pipeline.
  82159. * @returns An instantiated pipeline from the serialized object.
  82160. */
  82161. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  82162. var p = BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  82163. if (source.sourceLightId) {
  82164. p.sourceLight = scene.getLightByID(source.sourceLightId);
  82165. }
  82166. return p;
  82167. };
  82168. // Luminance steps
  82169. StandardRenderingPipeline.LuminanceSteps = 6;
  82170. __decorate([
  82171. BABYLON.serialize()
  82172. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  82173. __decorate([
  82174. BABYLON.serialize()
  82175. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  82176. __decorate([
  82177. BABYLON.serialize()
  82178. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  82179. __decorate([
  82180. BABYLON.serialize()
  82181. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  82182. __decorate([
  82183. BABYLON.serializeAsTexture("lensTexture")
  82184. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  82185. __decorate([
  82186. BABYLON.serialize()
  82187. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  82188. __decorate([
  82189. BABYLON.serialize()
  82190. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  82191. __decorate([
  82192. BABYLON.serialize()
  82193. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  82194. __decorate([
  82195. BABYLON.serialize()
  82196. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  82197. __decorate([
  82198. BABYLON.serialize()
  82199. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  82200. __decorate([
  82201. BABYLON.serialize()
  82202. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  82203. __decorate([
  82204. BABYLON.serializeAsTexture("lensColorTexture")
  82205. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  82206. __decorate([
  82207. BABYLON.serialize()
  82208. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  82209. __decorate([
  82210. BABYLON.serialize()
  82211. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  82212. __decorate([
  82213. BABYLON.serialize()
  82214. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  82215. __decorate([
  82216. BABYLON.serialize()
  82217. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  82218. __decorate([
  82219. BABYLON.serializeAsTexture("lensStarTexture")
  82220. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  82221. __decorate([
  82222. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  82223. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  82224. __decorate([
  82225. BABYLON.serialize()
  82226. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  82227. __decorate([
  82228. BABYLON.serialize()
  82229. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  82230. __decorate([
  82231. BABYLON.serialize()
  82232. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  82233. __decorate([
  82234. BABYLON.serialize()
  82235. ], StandardRenderingPipeline.prototype, "_ratio", void 0);
  82236. __decorate([
  82237. BABYLON.serialize()
  82238. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  82239. __decorate([
  82240. BABYLON.serialize()
  82241. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  82242. __decorate([
  82243. BABYLON.serialize()
  82244. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  82245. __decorate([
  82246. BABYLON.serialize()
  82247. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  82248. __decorate([
  82249. BABYLON.serialize()
  82250. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  82251. __decorate([
  82252. BABYLON.serialize()
  82253. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  82254. __decorate([
  82255. BABYLON.serialize()
  82256. ], StandardRenderingPipeline.prototype, "fxaaEnabled", null);
  82257. __decorate([
  82258. BABYLON.serialize()
  82259. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  82260. __decorate([
  82261. BABYLON.serialize()
  82262. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  82263. __decorate([
  82264. BABYLON.serialize()
  82265. ], StandardRenderingPipeline.prototype, "samples", null);
  82266. return StandardRenderingPipeline;
  82267. }(BABYLON.PostProcessRenderPipeline));
  82268. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  82269. })(BABYLON || (BABYLON = {}));
  82270. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  82271. var BABYLON;
  82272. (function (BABYLON) {
  82273. var FxaaPostProcess = /** @class */ (function (_super) {
  82274. __extends(FxaaPostProcess, _super);
  82275. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  82276. if (camera === void 0) { camera = null; }
  82277. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  82278. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa", undefined, true) || this;
  82279. var defines = _this._getDefines();
  82280. _this.updateEffect(defines);
  82281. _this.onApplyObservable.add(function (effect) {
  82282. var texelSize = _this.texelSize;
  82283. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  82284. });
  82285. return _this;
  82286. }
  82287. FxaaPostProcess.prototype._getDefines = function () {
  82288. var engine = this.getEngine();
  82289. if (!engine) {
  82290. return null;
  82291. }
  82292. var glInfo = engine.getGlInfo();
  82293. if (glInfo && glInfo.renderer && glInfo.renderer.toLowerCase().indexOf("mali") > -1) {
  82294. return "#define MALI 1\n";
  82295. }
  82296. return null;
  82297. };
  82298. return FxaaPostProcess;
  82299. }(BABYLON.PostProcess));
  82300. BABYLON.FxaaPostProcess = FxaaPostProcess;
  82301. })(BABYLON || (BABYLON = {}));
  82302. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  82303. var BABYLON;
  82304. (function (BABYLON) {
  82305. /**
  82306. * The ChromaticAberrationPostProcess separates the rgb channels in an image to produce chromatic distortion around the edges of the screen
  82307. */
  82308. var ChromaticAberrationPostProcess = /** @class */ (function (_super) {
  82309. __extends(ChromaticAberrationPostProcess, _super);
  82310. /**
  82311. * Creates a new instance ChromaticAberrationPostProcess
  82312. * @param name The name of the effect.
  82313. * @param screenWidth The width of the screen to apply the effect on.
  82314. * @param screenHeight The height of the screen to apply the effect on.
  82315. * @param options The required width/height ratio to downsize to before computing the render pass.
  82316. * @param camera The camera to apply the render pass to.
  82317. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  82318. * @param engine The engine which the post process will be applied. (default: current engine)
  82319. * @param reusable If the post process can be reused on the same frame. (default: false)
  82320. * @param textureType Type of textures used when performing the post process. (default: 0)
  82321. * @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)
  82322. */
  82323. function ChromaticAberrationPostProcess(name, screenWidth, screenHeight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  82324. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  82325. if (blockCompilation === void 0) { blockCompilation = false; }
  82326. 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;
  82327. /**
  82328. * The amount of seperation of rgb channels (default: 30)
  82329. */
  82330. _this.aberrationAmount = 30;
  82331. /**
  82332. * The amount the effect will increase for pixels closer to the edge of the screen. (default: 0)
  82333. */
  82334. _this.radialIntensity = 0;
  82335. /**
  82336. * 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))
  82337. */
  82338. _this.direction = new BABYLON.Vector2(0.707, 0.707);
  82339. /**
  82340. * 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))
  82341. */
  82342. _this.centerPosition = new BABYLON.Vector2(0.5, 0.5);
  82343. _this.onApplyObservable.add(function (effect) {
  82344. effect.setFloat('chromatic_aberration', _this.aberrationAmount);
  82345. effect.setFloat('screen_width', screenWidth);
  82346. effect.setFloat('screen_height', screenHeight);
  82347. effect.setFloat('radialIntensity', _this.radialIntensity);
  82348. effect.setFloat2('direction', _this.direction.x, _this.direction.y);
  82349. effect.setFloat2('centerPosition', _this.centerPosition.x, _this.centerPosition.y);
  82350. });
  82351. return _this;
  82352. }
  82353. return ChromaticAberrationPostProcess;
  82354. }(BABYLON.PostProcess));
  82355. BABYLON.ChromaticAberrationPostProcess = ChromaticAberrationPostProcess;
  82356. })(BABYLON || (BABYLON = {}));
  82357. //# sourceMappingURL=babylon.chromaticAberrationPostProcess.js.map
  82358. var BABYLON;
  82359. (function (BABYLON) {
  82360. /**
  82361. * The GrainPostProcess adds noise to the image at mid luminance levels
  82362. */
  82363. var GrainPostProcess = /** @class */ (function (_super) {
  82364. __extends(GrainPostProcess, _super);
  82365. /**
  82366. * Creates a new instance of @see GrainPostProcess
  82367. * @param name The name of the effect.
  82368. * @param options The required width/height ratio to downsize to before computing the render pass.
  82369. * @param camera The camera to apply the render pass to.
  82370. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  82371. * @param engine The engine which the post process will be applied. (default: current engine)
  82372. * @param reusable If the post process can be reused on the same frame. (default: false)
  82373. * @param textureType Type of textures used when performing the post process. (default: 0)
  82374. * @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)
  82375. */
  82376. function GrainPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  82377. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  82378. if (blockCompilation === void 0) { blockCompilation = false; }
  82379. var _this = _super.call(this, name, "grain", ["intensity", "animatedSeed"], [], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  82380. /**
  82381. * The intensity of the grain added (default: 30)
  82382. */
  82383. _this.intensity = 30;
  82384. /**
  82385. * If the grain should be randomized on every frame
  82386. */
  82387. _this.animated = false;
  82388. _this.onApplyObservable.add(function (effect) {
  82389. effect.setFloat('intensity', _this.intensity);
  82390. effect.setFloat('animatedSeed', _this.animated ? Math.random() + 1 : 1);
  82391. });
  82392. return _this;
  82393. }
  82394. return GrainPostProcess;
  82395. }(BABYLON.PostProcess));
  82396. BABYLON.GrainPostProcess = GrainPostProcess;
  82397. })(BABYLON || (BABYLON = {}));
  82398. //# sourceMappingURL=babylon.grainPostProcess.js.map
  82399. var BABYLON;
  82400. (function (BABYLON) {
  82401. /**
  82402. * The SharpenPostProcess applies a sharpen kernel to every pixel
  82403. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  82404. */
  82405. var SharpenPostProcess = /** @class */ (function (_super) {
  82406. __extends(SharpenPostProcess, _super);
  82407. /**
  82408. * Creates a new instance ConvolutionPostProcess
  82409. * @param name The name of the effect.
  82410. * @param options The required width/height ratio to downsize to before computing the render pass.
  82411. * @param camera The camera to apply the render pass to.
  82412. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  82413. * @param engine The engine which the post process will be applied. (default: current engine)
  82414. * @param reusable If the post process can be reused on the same frame. (default: false)
  82415. * @param textureType Type of textures used when performing the post process. (default: 0)
  82416. * @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)
  82417. */
  82418. function SharpenPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  82419. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  82420. if (blockCompilation === void 0) { blockCompilation = false; }
  82421. var _this = _super.call(this, name, "sharpen", ["sharpnessAmounts", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  82422. /**
  82423. * How much of the original color should be applied. Setting this to 0 will display edge detection. (default: 1)
  82424. */
  82425. _this.colorAmount = 1.0;
  82426. /**
  82427. * How much sharpness should be applied (default: 0.3)
  82428. */
  82429. _this.edgeAmount = 0.3;
  82430. _this.onApply = function (effect) {
  82431. effect.setFloat2("screenSize", _this.width, _this.height);
  82432. effect.setFloat2("sharpnessAmounts", _this.edgeAmount, _this.colorAmount);
  82433. };
  82434. return _this;
  82435. }
  82436. return SharpenPostProcess;
  82437. }(BABYLON.PostProcess));
  82438. BABYLON.SharpenPostProcess = SharpenPostProcess;
  82439. })(BABYLON || (BABYLON = {}));
  82440. //# sourceMappingURL=babylon.sharpenPostProcess.js.map
  82441. var BABYLON;
  82442. (function (BABYLON) {
  82443. /**
  82444. * The Blur Post Process which blurs an image based on a kernel and direction.
  82445. * Can be used twice in x and y directions to perform a guassian blur in two passes.
  82446. */
  82447. var BlurPostProcess = /** @class */ (function (_super) {
  82448. __extends(BlurPostProcess, _super);
  82449. /**
  82450. * Creates a new instance BlurPostProcess
  82451. * @param name The name of the effect.
  82452. * @param direction The direction in which to blur the image.
  82453. * @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.
  82454. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  82455. * @param camera The camera to apply the render pass to.
  82456. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  82457. * @param engine The engine which the post process will be applied. (default: current engine)
  82458. * @param reusable If the post process can be reused on the same frame. (default: false)
  82459. * @param textureType Type of textures used when performing the post process. (default: 0)
  82460. * @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)
  82461. */
  82462. function BlurPostProcess(name,
  82463. /** The direction in which to blur the image. */
  82464. direction, kernel, options, camera, samplingMode, engine, reusable, textureType, defines, blockCompilation) {
  82465. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  82466. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  82467. if (defines === void 0) { defines = ""; }
  82468. if (blockCompilation === void 0) { blockCompilation = false; }
  82469. 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;
  82470. _this.direction = direction;
  82471. _this.blockCompilation = blockCompilation;
  82472. _this._packedFloat = false;
  82473. _this._staticDefines = "";
  82474. _this._staticDefines = defines;
  82475. _this.onApplyObservable.add(function (effect) {
  82476. if (_this._outputTexture) {
  82477. effect.setFloat2('delta', (1 / _this._outputTexture.width) * _this.direction.x, (1 / _this._outputTexture.height) * _this.direction.y);
  82478. }
  82479. else {
  82480. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  82481. }
  82482. });
  82483. _this.kernel = kernel;
  82484. return _this;
  82485. }
  82486. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  82487. /**
  82488. * Gets the length in pixels of the blur sample region
  82489. */
  82490. get: function () {
  82491. return this._idealKernel;
  82492. },
  82493. /**
  82494. * Sets the length in pixels of the blur sample region
  82495. */
  82496. set: function (v) {
  82497. if (this._idealKernel === v) {
  82498. return;
  82499. }
  82500. v = Math.max(v, 1);
  82501. this._idealKernel = v;
  82502. this._kernel = this._nearestBestKernel(v);
  82503. if (!this.blockCompilation) {
  82504. this._updateParameters();
  82505. }
  82506. },
  82507. enumerable: true,
  82508. configurable: true
  82509. });
  82510. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  82511. /**
  82512. * Gets wether or not the blur is unpacking/repacking floats
  82513. */
  82514. get: function () {
  82515. return this._packedFloat;
  82516. },
  82517. /**
  82518. * Sets wether or not the blur needs to unpack/repack floats
  82519. */
  82520. set: function (v) {
  82521. if (this._packedFloat === v) {
  82522. return;
  82523. }
  82524. this._packedFloat = v;
  82525. if (!this.blockCompilation) {
  82526. this._updateParameters();
  82527. }
  82528. },
  82529. enumerable: true,
  82530. configurable: true
  82531. });
  82532. /**
  82533. * Updates the effect with the current post process compile time values and recompiles the shader.
  82534. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  82535. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  82536. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  82537. * @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
  82538. * @param onCompiled Called when the shader has been compiled.
  82539. * @param onError Called if there is an error when compiling a shader.
  82540. */
  82541. BlurPostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  82542. if (defines === void 0) { defines = null; }
  82543. if (uniforms === void 0) { uniforms = null; }
  82544. if (samplers === void 0) { samplers = null; }
  82545. this._updateParameters(onCompiled, onError);
  82546. };
  82547. BlurPostProcess.prototype._updateParameters = function (onCompiled, onError) {
  82548. // Generate sampling offsets and weights
  82549. var N = this._kernel;
  82550. var centerIndex = (N - 1) / 2;
  82551. // Generate Gaussian sampling weights over kernel
  82552. var offsets = [];
  82553. var weights = [];
  82554. var totalWeight = 0;
  82555. for (var i = 0; i < N; i++) {
  82556. var u = i / (N - 1);
  82557. var w = this._gaussianWeight(u * 2.0 - 1);
  82558. offsets[i] = (i - centerIndex);
  82559. weights[i] = w;
  82560. totalWeight += w;
  82561. }
  82562. // Normalize weights
  82563. for (var i = 0; i < weights.length; i++) {
  82564. weights[i] /= totalWeight;
  82565. }
  82566. // Optimize: combine samples to take advantage of hardware linear sampling
  82567. // Walk from left to center, combining pairs (symmetrically)
  82568. var linearSamplingWeights = [];
  82569. var linearSamplingOffsets = [];
  82570. var linearSamplingMap = [];
  82571. for (var i = 0; i <= centerIndex; i += 2) {
  82572. var j = Math.min(i + 1, Math.floor(centerIndex));
  82573. var singleCenterSample = i === j;
  82574. if (singleCenterSample) {
  82575. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  82576. }
  82577. else {
  82578. var sharedCell = j === centerIndex;
  82579. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  82580. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  82581. if (offsetLinear === 0) {
  82582. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  82583. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  82584. }
  82585. else {
  82586. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  82587. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  82588. }
  82589. }
  82590. }
  82591. for (var i = 0; i < linearSamplingMap.length; i++) {
  82592. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  82593. linearSamplingWeights[i] = linearSamplingMap[i].w;
  82594. }
  82595. // Replace with optimized
  82596. offsets = linearSamplingOffsets;
  82597. weights = linearSamplingWeights;
  82598. // Generate shaders
  82599. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  82600. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  82601. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  82602. var defines = "";
  82603. defines += this._staticDefines;
  82604. // The DOF fragment should ignore the center pixel when looping as it is handled manualy in the fragment shader.
  82605. if (this._staticDefines.indexOf("DOF") != -1) {
  82606. defines += "#define CENTER_WEIGHT " + this._glslFloat(weights[varyingCount - 1]) + "\r\n";
  82607. varyingCount--;
  82608. }
  82609. for (var i = 0; i < varyingCount; i++) {
  82610. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  82611. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  82612. }
  82613. var depCount = 0;
  82614. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  82615. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  82616. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  82617. depCount++;
  82618. }
  82619. if (this.packedFloat) {
  82620. defines += "#define PACKEDFLOAT 1";
  82621. }
  82622. this.blockCompilation = false;
  82623. _super.prototype.updateEffect.call(this, defines, null, null, {
  82624. varyingCount: varyingCount,
  82625. depCount: depCount
  82626. }, onCompiled, onError);
  82627. };
  82628. /**
  82629. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  82630. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  82631. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  82632. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  82633. * The gaps between physical kernels are compensated for in the weighting of the samples
  82634. * @param idealKernel Ideal blur kernel.
  82635. * @return Nearest best kernel.
  82636. */
  82637. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  82638. var v = Math.round(idealKernel);
  82639. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  82640. var k = _a[_i];
  82641. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  82642. return Math.max(k, 3);
  82643. }
  82644. }
  82645. return Math.max(v, 3);
  82646. };
  82647. /**
  82648. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  82649. * @param x The point on the Gaussian distribution to sample.
  82650. * @return the value of the Gaussian function at x.
  82651. */
  82652. BlurPostProcess.prototype._gaussianWeight = function (x) {
  82653. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  82654. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  82655. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  82656. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  82657. // truncated at around 1.3% of peak strength.
  82658. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  82659. var sigma = (1 / 3);
  82660. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  82661. var exponent = -((x * x) / (2.0 * sigma * sigma));
  82662. var weight = (1.0 / denominator) * Math.exp(exponent);
  82663. return weight;
  82664. };
  82665. /**
  82666. * Generates a string that can be used as a floating point number in GLSL.
  82667. * @param x Value to print.
  82668. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  82669. * @return GLSL float string.
  82670. */
  82671. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  82672. if (decimalFigures === void 0) { decimalFigures = 8; }
  82673. return x.toFixed(decimalFigures).replace(/0+$/, '');
  82674. };
  82675. return BlurPostProcess;
  82676. }(BABYLON.PostProcess));
  82677. BABYLON.BlurPostProcess = BlurPostProcess;
  82678. })(BABYLON || (BABYLON = {}));
  82679. //# sourceMappingURL=babylon.blurPostProcess.js.map
  82680. var BABYLON;
  82681. (function (BABYLON) {
  82682. /**
  82683. * The DepthOfFieldBlurPostProcess applied a blur in a give direction.
  82684. * This blur differs from the standard BlurPostProcess as it attempts to avoid blurring pixels
  82685. * based on samples that have a large difference in distance than the center pixel.
  82686. * See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  82687. */
  82688. var DepthOfFieldBlurPostProcess = /** @class */ (function (_super) {
  82689. __extends(DepthOfFieldBlurPostProcess, _super);
  82690. /**
  82691. * Creates a new instance CircleOfConfusionPostProcess
  82692. * @param name The name of the effect.
  82693. * @param scene The scene the effect belongs to.
  82694. * @param direction The direction the blur should be applied.
  82695. * @param kernel The size of the kernel used to blur.
  82696. * @param options The required width/height ratio to downsize to before computing the render pass.
  82697. * @param camera The camera to apply the render pass to.
  82698. * @param circleOfConfusion The circle of confusion + depth map to be used to avoid blurring accross edges
  82699. * @param imageToBlur The image to apply the blur to (default: Current rendered frame)
  82700. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  82701. * @param engine The engine which the post process will be applied. (default: current engine)
  82702. * @param reusable If the post process can be reused on the same frame. (default: false)
  82703. * @param textureType Type of textures used when performing the post process. (default: 0)
  82704. * @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)
  82705. */
  82706. function DepthOfFieldBlurPostProcess(name, scene, direction, kernel, options, camera, circleOfConfusion, imageToBlur, samplingMode, engine, reusable, textureType, blockCompilation) {
  82707. if (imageToBlur === void 0) { imageToBlur = null; }
  82708. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  82709. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  82710. if (blockCompilation === void 0) { blockCompilation = false; }
  82711. 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;
  82712. _this.direction = direction;
  82713. _this.onApplyObservable.add(function (effect) {
  82714. if (imageToBlur != null) {
  82715. effect.setTextureFromPostProcess("textureSampler", imageToBlur);
  82716. }
  82717. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  82718. if (scene.activeCamera) {
  82719. effect.setFloat2('cameraMinMaxZ', scene.activeCamera.minZ, scene.activeCamera.maxZ);
  82720. }
  82721. });
  82722. return _this;
  82723. }
  82724. return DepthOfFieldBlurPostProcess;
  82725. }(BABYLON.BlurPostProcess));
  82726. BABYLON.DepthOfFieldBlurPostProcess = DepthOfFieldBlurPostProcess;
  82727. })(BABYLON || (BABYLON = {}));
  82728. //# sourceMappingURL=babylon.depthOfFieldBlurPostProcess.js.map
  82729. var BABYLON;
  82730. (function (BABYLON) {
  82731. /**
  82732. * Options to be set when merging outputs from the default pipeline.
  82733. */
  82734. var DepthOfFieldMergePostProcessOptions = /** @class */ (function () {
  82735. function DepthOfFieldMergePostProcessOptions() {
  82736. }
  82737. return DepthOfFieldMergePostProcessOptions;
  82738. }());
  82739. BABYLON.DepthOfFieldMergePostProcessOptions = DepthOfFieldMergePostProcessOptions;
  82740. /**
  82741. * The DepthOfFieldMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  82742. */
  82743. var DepthOfFieldMergePostProcess = /** @class */ (function (_super) {
  82744. __extends(DepthOfFieldMergePostProcess, _super);
  82745. /**
  82746. * Creates a new instance of DepthOfFieldMergePostProcess
  82747. * @param name The name of the effect.
  82748. * @param originalFromInput Post process which's input will be used for the merge.
  82749. * @param circleOfConfusion Circle of confusion post process which's output will be used to blur each pixel.
  82750. * @param blurSteps Blur post processes from low to high which will be mixed with the original image.
  82751. * @param options The required width/height ratio to downsize to before computing the render pass.
  82752. * @param camera The camera to apply the render pass to.
  82753. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  82754. * @param engine The engine which the post process will be applied. (default: current engine)
  82755. * @param reusable If the post process can be reused on the same frame. (default: false)
  82756. * @param textureType Type of textures used when performing the post process. (default: 0)
  82757. * @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)
  82758. */
  82759. function DepthOfFieldMergePostProcess(name, originalFromInput, circleOfConfusion, blurSteps, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  82760. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  82761. if (blockCompilation === void 0) { blockCompilation = false; }
  82762. var _this = _super.call(this, name, "depthOfFieldMerge", [], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  82763. _this.blurSteps = blurSteps;
  82764. _this.onApplyObservable.add(function (effect) {
  82765. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  82766. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  82767. blurSteps.forEach(function (step, index) {
  82768. effect.setTextureFromPostProcessOutput("blurStep" + (blurSteps.length - index - 1), step);
  82769. });
  82770. });
  82771. if (!blockCompilation) {
  82772. _this.updateEffect();
  82773. }
  82774. return _this;
  82775. }
  82776. /**
  82777. * Updates the effect with the current post process compile time values and recompiles the shader.
  82778. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  82779. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  82780. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  82781. * @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
  82782. * @param onCompiled Called when the shader has been compiled.
  82783. * @param onError Called if there is an error when compiling a shader.
  82784. */
  82785. DepthOfFieldMergePostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  82786. if (defines === void 0) { defines = null; }
  82787. if (uniforms === void 0) { uniforms = null; }
  82788. if (samplers === void 0) { samplers = null; }
  82789. if (!defines) {
  82790. defines = "";
  82791. defines += "#define BLUR_LEVEL " + (this.blurSteps.length - 1) + "\n";
  82792. }
  82793. _super.prototype.updateEffect.call(this, defines, uniforms, samplers, indexParameters, onCompiled, onError);
  82794. };
  82795. return DepthOfFieldMergePostProcess;
  82796. }(BABYLON.PostProcess));
  82797. BABYLON.DepthOfFieldMergePostProcess = DepthOfFieldMergePostProcess;
  82798. })(BABYLON || (BABYLON = {}));
  82799. //# sourceMappingURL=babylon.depthOfFieldMergePostProcess.js.map
  82800. var BABYLON;
  82801. (function (BABYLON) {
  82802. /**
  82803. * The CircleOfConfusionPostProcess computes the circle of confusion value for each pixel given required lens parameters. See https://en.wikipedia.org/wiki/Circle_of_confusion
  82804. */
  82805. var CircleOfConfusionPostProcess = /** @class */ (function (_super) {
  82806. __extends(CircleOfConfusionPostProcess, _super);
  82807. /**
  82808. * Creates a new instance CircleOfConfusionPostProcess
  82809. * @param name The name of the effect.
  82810. * @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.
  82811. * @param options The required width/height ratio to downsize to before computing the render pass.
  82812. * @param camera The camera to apply the render pass to.
  82813. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  82814. * @param engine The engine which the post process will be applied. (default: current engine)
  82815. * @param reusable If the post process can be reused on the same frame. (default: false)
  82816. * @param textureType Type of textures used when performing the post process. (default: 0)
  82817. * @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)
  82818. */
  82819. function CircleOfConfusionPostProcess(name, depthTexture, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  82820. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  82821. if (blockCompilation === void 0) { blockCompilation = false; }
  82822. var _this = _super.call(this, name, "circleOfConfusion", ["cameraMinMaxZ", "focusDistance", "cocPrecalculation"], ["depthSampler"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  82823. /**
  82824. * 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.
  82825. */
  82826. _this.lensSize = 50;
  82827. /**
  82828. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  82829. */
  82830. _this.fStop = 1.4;
  82831. /**
  82832. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  82833. */
  82834. _this.focusDistance = 2000;
  82835. /**
  82836. * Focal length of the effect's camera in scene units/1000 (eg. millimeter). (default: 50)
  82837. */
  82838. _this.focalLength = 50;
  82839. _this._depthTexture = null;
  82840. _this._depthTexture = depthTexture;
  82841. _this.onApplyObservable.add(function (effect) {
  82842. if (!_this._depthTexture) {
  82843. BABYLON.Tools.Warn("No depth texture set on CircleOfConfusionPostProcess");
  82844. return;
  82845. }
  82846. effect.setTexture("depthSampler", _this._depthTexture);
  82847. // Circle of confusion calculation, See https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch23.html
  82848. var aperture = _this.lensSize / _this.fStop;
  82849. var cocPrecalculation = ((aperture * _this.focalLength) / ((_this.focusDistance - _this.focalLength))); // * ((this.focusDistance - pixelDistance)/pixelDistance) [This part is done in shader]
  82850. effect.setFloat('focusDistance', _this.focusDistance);
  82851. effect.setFloat('cocPrecalculation', cocPrecalculation);
  82852. effect.setFloat2('cameraMinMaxZ', _this._depthTexture.activeCamera.minZ, _this._depthTexture.activeCamera.maxZ);
  82853. });
  82854. return _this;
  82855. }
  82856. Object.defineProperty(CircleOfConfusionPostProcess.prototype, "depthTexture", {
  82857. /**
  82858. * 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.
  82859. */
  82860. set: function (value) {
  82861. this._depthTexture = value;
  82862. },
  82863. enumerable: true,
  82864. configurable: true
  82865. });
  82866. return CircleOfConfusionPostProcess;
  82867. }(BABYLON.PostProcess));
  82868. BABYLON.CircleOfConfusionPostProcess = CircleOfConfusionPostProcess;
  82869. })(BABYLON || (BABYLON = {}));
  82870. //# sourceMappingURL=babylon.circleOfConfusionPostProcess.js.map
  82871. var BABYLON;
  82872. (function (BABYLON) {
  82873. /**
  82874. * Specifies the level of max blur that should be applied when using the depth of field effect
  82875. */
  82876. var DepthOfFieldEffectBlurLevel;
  82877. (function (DepthOfFieldEffectBlurLevel) {
  82878. /**
  82879. * Subtle blur
  82880. */
  82881. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Low"] = 0] = "Low";
  82882. /**
  82883. * Medium blur
  82884. */
  82885. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Medium"] = 1] = "Medium";
  82886. /**
  82887. * Large blur
  82888. */
  82889. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["High"] = 2] = "High";
  82890. })(DepthOfFieldEffectBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel || (BABYLON.DepthOfFieldEffectBlurLevel = {}));
  82891. ;
  82892. /**
  82893. * The depth of field effect applies a blur to objects that are closer or further from where the camera is focusing.
  82894. */
  82895. var DepthOfFieldEffect = /** @class */ (function (_super) {
  82896. __extends(DepthOfFieldEffect, _super);
  82897. /**
  82898. * Creates a new instance DepthOfFieldEffect
  82899. * @param scene The scene the effect belongs to.
  82900. * @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.
  82901. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  82902. * @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)
  82903. */
  82904. function DepthOfFieldEffect(scene, depthTexture, blurLevel, pipelineTextureType, blockCompilation) {
  82905. if (blurLevel === void 0) { blurLevel = DepthOfFieldEffectBlurLevel.Low; }
  82906. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  82907. if (blockCompilation === void 0) { blockCompilation = false; }
  82908. var _this = _super.call(this, scene.getEngine(), "depth of field", function () {
  82909. return _this._effects;
  82910. }, true) || this;
  82911. /**
  82912. * @hidden Internal post processes in depth of field effect
  82913. */
  82914. _this._effects = [];
  82915. // Circle of confusion value for each pixel is used to determine how much to blur that pixel
  82916. _this._circleOfConfusion = new BABYLON.CircleOfConfusionPostProcess("circleOfConfusion", depthTexture, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  82917. // 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)
  82918. // Blur the image but do not blur on sharp far to near distance changes to avoid bleeding artifacts
  82919. // See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  82920. _this._depthOfFieldBlurY = [];
  82921. _this._depthOfFieldBlurX = [];
  82922. var blurCount = 1;
  82923. var kernelSize = 15;
  82924. switch (blurLevel) {
  82925. case DepthOfFieldEffectBlurLevel.High: {
  82926. blurCount = 3;
  82927. kernelSize = 51;
  82928. break;
  82929. }
  82930. case DepthOfFieldEffectBlurLevel.Medium: {
  82931. blurCount = 2;
  82932. kernelSize = 31;
  82933. break;
  82934. }
  82935. default: {
  82936. kernelSize = 15;
  82937. blurCount = 1;
  82938. break;
  82939. }
  82940. }
  82941. var adjustedKernelSize = kernelSize / Math.pow(2, blurCount - 1);
  82942. var ratio = 1.0;
  82943. for (var i = 0; i < blurCount; i++) {
  82944. 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);
  82945. blurY.autoClear = false;
  82946. ratio = 0.75 / Math.pow(2, i);
  82947. 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);
  82948. blurX.autoClear = false;
  82949. _this._depthOfFieldBlurY.push(blurY);
  82950. _this._depthOfFieldBlurX.push(blurX);
  82951. }
  82952. // Set all post processes on the effect.
  82953. _this._effects = [_this._circleOfConfusion];
  82954. for (var i = 0; i < _this._depthOfFieldBlurX.length; i++) {
  82955. _this._effects.push(_this._depthOfFieldBlurY[i]);
  82956. _this._effects.push(_this._depthOfFieldBlurX[i]);
  82957. }
  82958. // Merge blurred images with original image based on circleOfConfusion
  82959. _this._dofMerge = new BABYLON.DepthOfFieldMergePostProcess("dofMerge", _this._circleOfConfusion, _this._circleOfConfusion, _this._depthOfFieldBlurX, ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  82960. _this._dofMerge.autoClear = false;
  82961. _this._effects.push(_this._dofMerge);
  82962. return _this;
  82963. }
  82964. Object.defineProperty(DepthOfFieldEffect.prototype, "focalLength", {
  82965. get: function () {
  82966. return this._circleOfConfusion.focalLength;
  82967. },
  82968. /**
  82969. * The focal the length of the camera used in the effect in scene units/1000 (eg. millimeter)
  82970. */
  82971. set: function (value) {
  82972. this._circleOfConfusion.focalLength = value;
  82973. },
  82974. enumerable: true,
  82975. configurable: true
  82976. });
  82977. Object.defineProperty(DepthOfFieldEffect.prototype, "fStop", {
  82978. get: function () {
  82979. return this._circleOfConfusion.fStop;
  82980. },
  82981. /**
  82982. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  82983. */
  82984. set: function (value) {
  82985. this._circleOfConfusion.fStop = value;
  82986. },
  82987. enumerable: true,
  82988. configurable: true
  82989. });
  82990. Object.defineProperty(DepthOfFieldEffect.prototype, "focusDistance", {
  82991. get: function () {
  82992. return this._circleOfConfusion.focusDistance;
  82993. },
  82994. /**
  82995. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  82996. */
  82997. set: function (value) {
  82998. this._circleOfConfusion.focusDistance = value;
  82999. },
  83000. enumerable: true,
  83001. configurable: true
  83002. });
  83003. Object.defineProperty(DepthOfFieldEffect.prototype, "lensSize", {
  83004. get: function () {
  83005. return this._circleOfConfusion.lensSize;
  83006. },
  83007. /**
  83008. * 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.
  83009. */
  83010. set: function (value) {
  83011. this._circleOfConfusion.lensSize = value;
  83012. },
  83013. enumerable: true,
  83014. configurable: true
  83015. });
  83016. Object.defineProperty(DepthOfFieldEffect.prototype, "depthTexture", {
  83017. /**
  83018. * 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.
  83019. */
  83020. set: function (value) {
  83021. this._circleOfConfusion.depthTexture = value;
  83022. },
  83023. enumerable: true,
  83024. configurable: true
  83025. });
  83026. /**
  83027. * Disposes each of the internal effects for a given camera.
  83028. * @param camera The camera to dispose the effect on.
  83029. */
  83030. DepthOfFieldEffect.prototype.disposeEffects = function (camera) {
  83031. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  83032. this._effects[effectIndex].dispose(camera);
  83033. }
  83034. };
  83035. /**
  83036. * @hidden Internal
  83037. */
  83038. DepthOfFieldEffect.prototype._updateEffects = function () {
  83039. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  83040. this._effects[effectIndex].updateEffect();
  83041. }
  83042. };
  83043. /**
  83044. * Internal
  83045. * @returns if all the contained post processes are ready.
  83046. * @hidden
  83047. */
  83048. DepthOfFieldEffect.prototype._isReady = function () {
  83049. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  83050. if (!this._effects[effectIndex].isReady()) {
  83051. return false;
  83052. }
  83053. }
  83054. return true;
  83055. };
  83056. return DepthOfFieldEffect;
  83057. }(BABYLON.PostProcessRenderEffect));
  83058. BABYLON.DepthOfFieldEffect = DepthOfFieldEffect;
  83059. })(BABYLON || (BABYLON = {}));
  83060. //# sourceMappingURL=babylon.depthOfFieldEffect.js.map
  83061. var BABYLON;
  83062. (function (BABYLON) {
  83063. /**
  83064. * The BloomMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  83065. */
  83066. var BloomMergePostProcess = /** @class */ (function (_super) {
  83067. __extends(BloomMergePostProcess, _super);
  83068. /**
  83069. * Creates a new instance of @see BloomMergePostProcess
  83070. * @param name The name of the effect.
  83071. * @param originalFromInput Post process which's input will be used for the merge.
  83072. * @param blurred Blurred highlights post process which's output will be used.
  83073. * @param weight Weight of the bloom to be added to the original input.
  83074. * @param options The required width/height ratio to downsize to before computing the render pass.
  83075. * @param camera The camera to apply the render pass to.
  83076. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  83077. * @param engine The engine which the post process will be applied. (default: current engine)
  83078. * @param reusable If the post process can be reused on the same frame. (default: false)
  83079. * @param textureType Type of textures used when performing the post process. (default: 0)
  83080. * @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)
  83081. */
  83082. function BloomMergePostProcess(name, originalFromInput, blurred,
  83083. /** Weight of the bloom to be added to the original input. */
  83084. weight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  83085. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  83086. if (blockCompilation === void 0) { blockCompilation = false; }
  83087. var _this = _super.call(this, name, "bloomMerge", ["bloomWeight"], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2", "bloomBlur"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  83088. _this.weight = weight;
  83089. _this.onApplyObservable.add(function (effect) {
  83090. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  83091. effect.setTextureFromPostProcessOutput("bloomBlur", blurred);
  83092. effect.setFloat("bloomWeight", _this.weight);
  83093. });
  83094. if (!blockCompilation) {
  83095. _this.updateEffect();
  83096. }
  83097. return _this;
  83098. }
  83099. return BloomMergePostProcess;
  83100. }(BABYLON.PostProcess));
  83101. BABYLON.BloomMergePostProcess = BloomMergePostProcess;
  83102. })(BABYLON || (BABYLON = {}));
  83103. //# sourceMappingURL=babylon.bloomMergePostProcess.js.map
  83104. var BABYLON;
  83105. (function (BABYLON) {
  83106. /**
  83107. * 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.
  83108. */
  83109. var ExtractHighlightsPostProcess = /** @class */ (function (_super) {
  83110. __extends(ExtractHighlightsPostProcess, _super);
  83111. function ExtractHighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  83112. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  83113. if (blockCompilation === void 0) { blockCompilation = false; }
  83114. var _this = _super.call(this, name, "extractHighlights", ["threshold", "exposure"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  83115. /**
  83116. * The luminance threshold, pixels below this value will be set to black.
  83117. */
  83118. _this.threshold = 0.9;
  83119. /** @hidden */
  83120. _this._exposure = 1;
  83121. /**
  83122. * Post process which has the input texture to be used when performing highlight extraction
  83123. * @hidden
  83124. */
  83125. _this._inputPostProcess = null;
  83126. _this.onApplyObservable.add(function (effect) {
  83127. if (_this._inputPostProcess) {
  83128. effect.setTextureFromPostProcess("textureSampler", _this._inputPostProcess);
  83129. }
  83130. effect.setFloat('threshold', Math.pow(_this.threshold, BABYLON.ToGammaSpace));
  83131. effect.setFloat('exposure', _this._exposure);
  83132. });
  83133. return _this;
  83134. }
  83135. return ExtractHighlightsPostProcess;
  83136. }(BABYLON.PostProcess));
  83137. BABYLON.ExtractHighlightsPostProcess = ExtractHighlightsPostProcess;
  83138. })(BABYLON || (BABYLON = {}));
  83139. //# sourceMappingURL=babylon.extractHighlightsPostProcess.js.map
  83140. var BABYLON;
  83141. (function (BABYLON) {
  83142. /**
  83143. * The bloom effect spreads bright areas of an image to simulate artifacts seen in cameras
  83144. */
  83145. var BloomEffect = /** @class */ (function (_super) {
  83146. __extends(BloomEffect, _super);
  83147. /**
  83148. * Creates a new instance of @see BloomEffect
  83149. * @param scene The scene the effect belongs to.
  83150. * @param bloomScale The ratio of the blur texture to the input texture that should be used to compute the bloom.
  83151. * @param bloomKernel The size of the kernel to be used when applying the blur.
  83152. * @param bloomWeight The the strength of bloom.
  83153. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  83154. * @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)
  83155. */
  83156. function BloomEffect(scene, bloomScale, bloomWeight, bloomKernel, pipelineTextureType, blockCompilation) {
  83157. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  83158. if (blockCompilation === void 0) { blockCompilation = false; }
  83159. var _this = _super.call(this, scene.getEngine(), "bloom", function () {
  83160. return _this._effects;
  83161. }, true) || this;
  83162. _this.bloomScale = bloomScale;
  83163. /**
  83164. * @hidden Internal
  83165. */
  83166. _this._effects = [];
  83167. _this._downscale = new BABYLON.ExtractHighlightsPostProcess("highlights", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  83168. _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);
  83169. _this._blurX.alwaysForcePOT = true;
  83170. _this._blurX.autoClear = false;
  83171. _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);
  83172. _this._blurY.alwaysForcePOT = true;
  83173. _this._blurY.autoClear = false;
  83174. _this.kernel = bloomKernel;
  83175. _this._effects = [_this._downscale, _this._blurX, _this._blurY];
  83176. _this._merge = new BABYLON.BloomMergePostProcess("bloomMerge", _this._downscale, _this._blurY, bloomWeight, bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  83177. _this._merge.autoClear = false;
  83178. _this._effects.push(_this._merge);
  83179. return _this;
  83180. }
  83181. Object.defineProperty(BloomEffect.prototype, "threshold", {
  83182. /**
  83183. * The luminance threshold to find bright areas of the image to bloom.
  83184. */
  83185. get: function () {
  83186. return this._downscale.threshold;
  83187. },
  83188. set: function (value) {
  83189. this._downscale.threshold = value;
  83190. },
  83191. enumerable: true,
  83192. configurable: true
  83193. });
  83194. Object.defineProperty(BloomEffect.prototype, "weight", {
  83195. /**
  83196. * The strength of the bloom.
  83197. */
  83198. get: function () {
  83199. return this._merge.weight;
  83200. },
  83201. set: function (value) {
  83202. this._merge.weight = value;
  83203. },
  83204. enumerable: true,
  83205. configurable: true
  83206. });
  83207. Object.defineProperty(BloomEffect.prototype, "kernel", {
  83208. /**
  83209. * Specifies the size of the bloom blur kernel, relative to the final output size
  83210. */
  83211. get: function () {
  83212. return this._blurX.kernel / this.bloomScale;
  83213. },
  83214. set: function (value) {
  83215. this._blurX.kernel = value * this.bloomScale;
  83216. this._blurY.kernel = value * this.bloomScale;
  83217. },
  83218. enumerable: true,
  83219. configurable: true
  83220. });
  83221. /**
  83222. * Disposes each of the internal effects for a given camera.
  83223. * @param camera The camera to dispose the effect on.
  83224. */
  83225. BloomEffect.prototype.disposeEffects = function (camera) {
  83226. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  83227. this._effects[effectIndex].dispose(camera);
  83228. }
  83229. };
  83230. /**
  83231. * @hidden Internal
  83232. */
  83233. BloomEffect.prototype._updateEffects = function () {
  83234. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  83235. this._effects[effectIndex].updateEffect();
  83236. }
  83237. };
  83238. /**
  83239. * Internal
  83240. * @returns if all the contained post processes are ready.
  83241. * @hidden
  83242. */
  83243. BloomEffect.prototype._isReady = function () {
  83244. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  83245. if (!this._effects[effectIndex].isReady()) {
  83246. return false;
  83247. }
  83248. }
  83249. return true;
  83250. };
  83251. return BloomEffect;
  83252. }(BABYLON.PostProcessRenderEffect));
  83253. BABYLON.BloomEffect = BloomEffect;
  83254. })(BABYLON || (BABYLON = {}));
  83255. //# sourceMappingURL=babylon.bloomEffect.js.map
  83256. var BABYLON;
  83257. (function (BABYLON) {
  83258. /**
  83259. * The default rendering pipeline can be added to a scene to apply common post processing effects such as anti-aliasing or depth of field.
  83260. * See https://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  83261. */
  83262. var DefaultRenderingPipeline = /** @class */ (function (_super) {
  83263. __extends(DefaultRenderingPipeline, _super);
  83264. /**
  83265. * @constructor
  83266. * @param {string} name - The rendering pipeline name (default: "")
  83267. * @param {boolean} hdr - If high dynamic range textures should be used (default: true)
  83268. * @param {BABYLON.Scene} scene - The scene linked to this pipeline (default: the last created scene)
  83269. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to (default: scene.cameras)
  83270. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline (default: true)
  83271. */
  83272. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  83273. if (name === void 0) { name = ""; }
  83274. if (hdr === void 0) { hdr = true; }
  83275. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  83276. if (automaticBuild === void 0) { automaticBuild = true; }
  83277. var _this = _super.call(this, scene.getEngine(), name) || this;
  83278. _this._camerasToBeAttached = [];
  83279. /**
  83280. * ID of the sharpen post process,
  83281. */
  83282. _this.SharpenPostProcessId = "SharpenPostProcessEffect";
  83283. /**
  83284. * ID of the image processing post process;
  83285. */
  83286. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  83287. /**
  83288. * ID of the Fast Approximate Anti-Aliasing post process;
  83289. */
  83290. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  83291. /**
  83292. * ID of the chromatic aberration post process,
  83293. */
  83294. _this.ChromaticAberrationPostProcessId = "ChromaticAberrationPostProcessEffect";
  83295. /**
  83296. * ID of the grain post process
  83297. */
  83298. _this.GrainPostProcessId = "GrainPostProcessEffect";
  83299. /**
  83300. * Glow post process which adds a glow to emmisive areas of the image
  83301. */
  83302. _this._glowLayer = null;
  83303. /**
  83304. * Animations which can be used to tweak settings over a period of time
  83305. */
  83306. _this.animations = [];
  83307. _this._imageProcessingConfigurationObserver = null;
  83308. // Values
  83309. _this._sharpenEnabled = false;
  83310. _this._bloomEnabled = false;
  83311. _this._depthOfFieldEnabled = false;
  83312. _this._depthOfFieldBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel.Low;
  83313. _this._fxaaEnabled = false;
  83314. _this._imageProcessingEnabled = true;
  83315. _this._bloomScale = 0.5;
  83316. _this._chromaticAberrationEnabled = false;
  83317. _this._grainEnabled = false;
  83318. _this._buildAllowed = true;
  83319. _this._resizeObserver = null;
  83320. _this._hardwareScaleLevel = 1.0;
  83321. _this._bloomKernel = 64;
  83322. /**
  83323. * Specifies the weight of the bloom in the final rendering
  83324. */
  83325. _this._bloomWeight = 0.15;
  83326. /**
  83327. * Specifies the luma threshold for the area that will be blurred by the bloom
  83328. */
  83329. _this._bloomThreshold = 0.9;
  83330. _this._samples = 1;
  83331. _this._hasCleared = false;
  83332. _this._prevPostProcess = null;
  83333. _this._prevPrevPostProcess = null;
  83334. _this._depthOfFieldSceneObserver = null;
  83335. _this._cameras = cameras || scene.cameras;
  83336. _this._cameras = _this._cameras.slice();
  83337. _this._camerasToBeAttached = _this._cameras.slice();
  83338. _this._buildAllowed = automaticBuild;
  83339. // Initialize
  83340. _this._scene = scene;
  83341. var caps = _this._scene.getEngine().getCaps();
  83342. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  83343. // Misc
  83344. if (_this._hdr) {
  83345. if (caps.textureHalfFloatRender) {
  83346. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  83347. }
  83348. else if (caps.textureFloatRender) {
  83349. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  83350. }
  83351. }
  83352. else {
  83353. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  83354. }
  83355. // Attach
  83356. scene.postProcessRenderPipelineManager.addPipeline(_this);
  83357. var engine = _this._scene.getEngine();
  83358. // Create post processes before hand so they can be modified before enabled.
  83359. // Block compilation flag is set to true to avoid compilation prior to use, these will be updated on first use in build pipeline.
  83360. _this.sharpen = new BABYLON.SharpenPostProcess("sharpen", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  83361. _this._sharpenEffect = new BABYLON.PostProcessRenderEffect(engine, _this.SharpenPostProcessId, function () { return _this.sharpen; }, true);
  83362. _this.depthOfField = new BABYLON.DepthOfFieldEffect(_this._scene, null, _this._depthOfFieldBlurLevel, _this._defaultPipelineTextureType, true);
  83363. _this.bloom = new BABYLON.BloomEffect(_this._scene, _this._bloomScale, _this._bloomWeight, _this.bloomKernel, _this._defaultPipelineTextureType, true);
  83364. _this.chromaticAberration = new BABYLON.ChromaticAberrationPostProcess("ChromaticAberration", engine.getRenderWidth(), engine.getRenderHeight(), 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  83365. _this._chromaticAberrationEffect = new BABYLON.PostProcessRenderEffect(engine, _this.ChromaticAberrationPostProcessId, function () { return _this.chromaticAberration; }, true);
  83366. _this.grain = new BABYLON.GrainPostProcess("Grain", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  83367. _this._grainEffect = new BABYLON.PostProcessRenderEffect(engine, _this.GrainPostProcessId, function () { return _this.grain; }, true);
  83368. _this._resizeObserver = engine.onResizeObservable.add(function () {
  83369. _this._hardwareScaleLevel = engine.getHardwareScalingLevel();
  83370. _this.bloomKernel = _this.bloomKernel;
  83371. });
  83372. _this._imageProcessingConfigurationObserver = _this._scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  83373. _this.bloom._downscale._exposure = _this._scene.imageProcessingConfiguration.exposure;
  83374. });
  83375. _this._buildPipeline();
  83376. return _this;
  83377. }
  83378. Object.defineProperty(DefaultRenderingPipeline.prototype, "sharpenEnabled", {
  83379. get: function () {
  83380. return this._sharpenEnabled;
  83381. },
  83382. /**
  83383. * Enable or disable the sharpen process from the pipeline
  83384. */
  83385. set: function (enabled) {
  83386. if (this._sharpenEnabled === enabled) {
  83387. return;
  83388. }
  83389. this._sharpenEnabled = enabled;
  83390. this._buildPipeline();
  83391. },
  83392. enumerable: true,
  83393. configurable: true
  83394. });
  83395. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomKernel", {
  83396. /**
  83397. * Specifies the size of the bloom blur kernel, relative to the final output size
  83398. */
  83399. get: function () {
  83400. return this._bloomKernel;
  83401. },
  83402. set: function (value) {
  83403. this._bloomKernel = value;
  83404. this.bloom.kernel = value / this._hardwareScaleLevel;
  83405. },
  83406. enumerable: true,
  83407. configurable: true
  83408. });
  83409. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  83410. get: function () {
  83411. return this._bloomWeight;
  83412. },
  83413. /**
  83414. * The strength of the bloom.
  83415. */
  83416. set: function (value) {
  83417. if (this._bloomWeight === value) {
  83418. return;
  83419. }
  83420. this.bloom.weight = value;
  83421. this._bloomWeight = value;
  83422. },
  83423. enumerable: true,
  83424. configurable: true
  83425. });
  83426. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomThreshold", {
  83427. get: function () {
  83428. return this._bloomThreshold;
  83429. },
  83430. /**
  83431. * The strength of the bloom.
  83432. */
  83433. set: function (value) {
  83434. if (this._bloomThreshold === value) {
  83435. return;
  83436. }
  83437. this.bloom.threshold = value;
  83438. this._bloomThreshold = value;
  83439. },
  83440. enumerable: true,
  83441. configurable: true
  83442. });
  83443. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  83444. get: function () {
  83445. return this._bloomScale;
  83446. },
  83447. /**
  83448. * The scale of the bloom, lower value will provide better performance.
  83449. */
  83450. set: function (value) {
  83451. if (this._bloomScale === value) {
  83452. return;
  83453. }
  83454. this._bloomScale = value;
  83455. // recreate bloom and dispose old as this setting is not dynamic
  83456. this._rebuildBloom();
  83457. this._buildPipeline();
  83458. },
  83459. enumerable: true,
  83460. configurable: true
  83461. });
  83462. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  83463. get: function () {
  83464. return this._bloomEnabled;
  83465. },
  83466. /**
  83467. * Enable or disable the bloom from the pipeline
  83468. */
  83469. set: function (enabled) {
  83470. if (this._bloomEnabled === enabled) {
  83471. return;
  83472. }
  83473. this._bloomEnabled = enabled;
  83474. this._buildPipeline();
  83475. },
  83476. enumerable: true,
  83477. configurable: true
  83478. });
  83479. DefaultRenderingPipeline.prototype._rebuildBloom = function () {
  83480. // recreate bloom and dispose old as this setting is not dynamic
  83481. var oldBloom = this.bloom;
  83482. this.bloom = new BABYLON.BloomEffect(this._scene, this.bloomScale, this._bloomWeight, this.bloomKernel, this._defaultPipelineTextureType, false);
  83483. this.bloom.threshold = oldBloom.threshold;
  83484. for (var i = 0; i < this._cameras.length; i++) {
  83485. oldBloom.disposeEffects(this._cameras[i]);
  83486. }
  83487. };
  83488. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", {
  83489. /**
  83490. * If the depth of field is enabled.
  83491. */
  83492. get: function () {
  83493. return this._depthOfFieldEnabled;
  83494. },
  83495. set: function (enabled) {
  83496. if (this._depthOfFieldEnabled === enabled) {
  83497. return;
  83498. }
  83499. this._depthOfFieldEnabled = enabled;
  83500. this._buildPipeline();
  83501. },
  83502. enumerable: true,
  83503. configurable: true
  83504. });
  83505. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", {
  83506. /**
  83507. * Blur level of the depth of field effect. (Higher blur will effect performance)
  83508. */
  83509. get: function () {
  83510. return this._depthOfFieldBlurLevel;
  83511. },
  83512. set: function (value) {
  83513. if (this._depthOfFieldBlurLevel === value) {
  83514. return;
  83515. }
  83516. this._depthOfFieldBlurLevel = value;
  83517. // recreate dof and dispose old as this setting is not dynamic
  83518. var oldDof = this.depthOfField;
  83519. this.depthOfField = new BABYLON.DepthOfFieldEffect(this._scene, null, this._depthOfFieldBlurLevel, this._defaultPipelineTextureType, false);
  83520. this.depthOfField.focalLength = oldDof.focalLength;
  83521. this.depthOfField.focusDistance = oldDof.focusDistance;
  83522. this.depthOfField.fStop = oldDof.fStop;
  83523. this.depthOfField.lensSize = oldDof.lensSize;
  83524. for (var i = 0; i < this._cameras.length; i++) {
  83525. oldDof.disposeEffects(this._cameras[i]);
  83526. }
  83527. this._buildPipeline();
  83528. },
  83529. enumerable: true,
  83530. configurable: true
  83531. });
  83532. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  83533. get: function () {
  83534. return this._fxaaEnabled;
  83535. },
  83536. /**
  83537. * If the anti aliasing is enabled.
  83538. */
  83539. set: function (enabled) {
  83540. if (this._fxaaEnabled === enabled) {
  83541. return;
  83542. }
  83543. this._fxaaEnabled = enabled;
  83544. this._buildPipeline();
  83545. },
  83546. enumerable: true,
  83547. configurable: true
  83548. });
  83549. Object.defineProperty(DefaultRenderingPipeline.prototype, "samples", {
  83550. get: function () {
  83551. return this._samples;
  83552. },
  83553. /**
  83554. * MSAA sample count, setting this to 4 will provide 4x anti aliasing. (default: 1)
  83555. */
  83556. set: function (sampleCount) {
  83557. if (this._samples === sampleCount) {
  83558. return;
  83559. }
  83560. this._samples = sampleCount;
  83561. this._buildPipeline();
  83562. },
  83563. enumerable: true,
  83564. configurable: true
  83565. });
  83566. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  83567. get: function () {
  83568. return this._imageProcessingEnabled;
  83569. },
  83570. /**
  83571. * If image processing is enabled.
  83572. */
  83573. set: function (enabled) {
  83574. if (this._imageProcessingEnabled === enabled) {
  83575. return;
  83576. }
  83577. this._imageProcessingEnabled = enabled;
  83578. this._buildPipeline();
  83579. },
  83580. enumerable: true,
  83581. configurable: true
  83582. });
  83583. Object.defineProperty(DefaultRenderingPipeline.prototype, "glowLayerEnabled", {
  83584. get: function () {
  83585. return this._glowLayer == null;
  83586. },
  83587. /**
  83588. * If glow layer is enabled. (Adds a glow effect to emmissive materials)
  83589. */
  83590. set: function (enabled) {
  83591. if (enabled && !this._glowLayer) {
  83592. this._glowLayer = new BABYLON.GlowLayer("", this._scene);
  83593. }
  83594. else if (!enabled && this._glowLayer) {
  83595. this._glowLayer.dispose();
  83596. this._glowLayer = null;
  83597. }
  83598. },
  83599. enumerable: true,
  83600. configurable: true
  83601. });
  83602. Object.defineProperty(DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", {
  83603. get: function () {
  83604. return this._chromaticAberrationEnabled;
  83605. },
  83606. /**
  83607. * Enable or disable the chromaticAberration process from the pipeline
  83608. */
  83609. set: function (enabled) {
  83610. if (this._chromaticAberrationEnabled === enabled) {
  83611. return;
  83612. }
  83613. this._chromaticAberrationEnabled = enabled;
  83614. this._buildPipeline();
  83615. },
  83616. enumerable: true,
  83617. configurable: true
  83618. });
  83619. Object.defineProperty(DefaultRenderingPipeline.prototype, "grainEnabled", {
  83620. get: function () {
  83621. return this._grainEnabled;
  83622. },
  83623. /**
  83624. * Enable or disable the grain process from the pipeline
  83625. */
  83626. set: function (enabled) {
  83627. if (this._grainEnabled === enabled) {
  83628. return;
  83629. }
  83630. this._grainEnabled = enabled;
  83631. this._buildPipeline();
  83632. },
  83633. enumerable: true,
  83634. configurable: true
  83635. });
  83636. /**
  83637. * Force the compilation of the entire pipeline.
  83638. */
  83639. DefaultRenderingPipeline.prototype.prepare = function () {
  83640. var previousState = this._buildAllowed;
  83641. this._buildAllowed = true;
  83642. this._buildPipeline();
  83643. this._buildAllowed = previousState;
  83644. };
  83645. DefaultRenderingPipeline.prototype._setAutoClearAndTextureSharing = function (postProcess, skipTextureSharing) {
  83646. if (skipTextureSharing === void 0) { skipTextureSharing = false; }
  83647. if (this._hasCleared) {
  83648. postProcess.autoClear = false;
  83649. }
  83650. else {
  83651. postProcess.autoClear = true;
  83652. this._scene.autoClear = false;
  83653. this._hasCleared = true;
  83654. }
  83655. if (!skipTextureSharing) {
  83656. if (this._prevPrevPostProcess) {
  83657. postProcess.shareOutputWith(this._prevPrevPostProcess);
  83658. }
  83659. else {
  83660. postProcess.useOwnOutput();
  83661. }
  83662. if (this._prevPostProcess) {
  83663. this._prevPrevPostProcess = this._prevPostProcess;
  83664. }
  83665. this._prevPostProcess = postProcess;
  83666. }
  83667. };
  83668. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  83669. var _this = this;
  83670. if (!this._buildAllowed) {
  83671. return;
  83672. }
  83673. this._scene.autoClear = true;
  83674. var engine = this._scene.getEngine();
  83675. this._disposePostProcesses();
  83676. if (this._cameras !== null) {
  83677. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  83678. // get back cameras to be used to reattach pipeline
  83679. this._cameras = this._camerasToBeAttached.slice();
  83680. }
  83681. this._reset();
  83682. this._prevPostProcess = null;
  83683. this._prevPrevPostProcess = null;
  83684. this._hasCleared = false;
  83685. if (this.depthOfFieldEnabled) {
  83686. // Multi camera suport
  83687. if (this._cameras.length > 1) {
  83688. for (var _i = 0, _a = this._cameras; _i < _a.length; _i++) {
  83689. var camera = _a[_i];
  83690. var depthRenderer = this._scene.enableDepthRenderer(camera);
  83691. depthRenderer.useOnlyInActiveCamera = true;
  83692. }
  83693. this._depthOfFieldSceneObserver = this._scene.onAfterRenderTargetsRenderObservable.add(function (scene) {
  83694. if (_this._cameras.indexOf(scene.activeCamera) > -1) {
  83695. _this.depthOfField.depthTexture = scene.enableDepthRenderer(scene.activeCamera).getDepthMap();
  83696. }
  83697. });
  83698. }
  83699. else {
  83700. this._scene.onAfterRenderTargetsRenderObservable.remove(this._depthOfFieldSceneObserver);
  83701. var depthRenderer = this._scene.enableDepthRenderer(this._cameras[0]);
  83702. this.depthOfField.depthTexture = depthRenderer.getDepthMap();
  83703. }
  83704. if (!this.depthOfField._isReady()) {
  83705. this.depthOfField._updateEffects();
  83706. }
  83707. this.addEffect(this.depthOfField);
  83708. this._setAutoClearAndTextureSharing(this.depthOfField._effects[0], true);
  83709. }
  83710. else {
  83711. this._scene.onAfterRenderTargetsRenderObservable.remove(this._depthOfFieldSceneObserver);
  83712. }
  83713. if (this.bloomEnabled) {
  83714. if (!this.bloom._isReady()) {
  83715. this.bloom._updateEffects();
  83716. }
  83717. this.addEffect(this.bloom);
  83718. this._setAutoClearAndTextureSharing(this.bloom._effects[0], true);
  83719. }
  83720. if (this._imageProcessingEnabled) {
  83721. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  83722. if (this._hdr) {
  83723. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  83724. this._setAutoClearAndTextureSharing(this.imageProcessing);
  83725. }
  83726. else {
  83727. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  83728. }
  83729. }
  83730. if (this.sharpenEnabled) {
  83731. if (!this.sharpen.isReady()) {
  83732. this.sharpen.updateEffect();
  83733. }
  83734. this.addEffect(this._sharpenEffect);
  83735. this._setAutoClearAndTextureSharing(this.sharpen);
  83736. }
  83737. if (this.grainEnabled) {
  83738. if (!this.grain.isReady()) {
  83739. this.grain.updateEffect();
  83740. }
  83741. this.addEffect(this._grainEffect);
  83742. this._setAutoClearAndTextureSharing(this.grain);
  83743. }
  83744. if (this.chromaticAberrationEnabled) {
  83745. if (!this.chromaticAberration.isReady()) {
  83746. this.chromaticAberration.updateEffect();
  83747. }
  83748. this.addEffect(this._chromaticAberrationEffect);
  83749. this._setAutoClearAndTextureSharing(this.chromaticAberration);
  83750. }
  83751. if (this.fxaaEnabled) {
  83752. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  83753. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  83754. this._setAutoClearAndTextureSharing(this.fxaa, true);
  83755. }
  83756. if (this._cameras !== null) {
  83757. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  83758. }
  83759. if (!this._enableMSAAOnFirstPostProcess(this.samples) && this.samples > 1) {
  83760. BABYLON.Tools.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0");
  83761. }
  83762. };
  83763. DefaultRenderingPipeline.prototype._disposePostProcesses = function (disposeNonRecreated) {
  83764. if (disposeNonRecreated === void 0) { disposeNonRecreated = false; }
  83765. for (var i = 0; i < this._cameras.length; i++) {
  83766. var camera = this._cameras[i];
  83767. if (this.imageProcessing) {
  83768. this.imageProcessing.dispose(camera);
  83769. }
  83770. if (this.fxaa) {
  83771. this.fxaa.dispose(camera);
  83772. }
  83773. // These are created in the constructor and should not be disposed on every pipeline change
  83774. if (disposeNonRecreated) {
  83775. if (this.sharpen) {
  83776. this.sharpen.dispose(camera);
  83777. }
  83778. if (this.depthOfField) {
  83779. this._scene.onAfterRenderTargetsRenderObservable.remove(this._depthOfFieldSceneObserver);
  83780. this.depthOfField.disposeEffects(camera);
  83781. }
  83782. if (this.bloom) {
  83783. this.bloom.disposeEffects(camera);
  83784. }
  83785. if (this.chromaticAberration) {
  83786. this.chromaticAberration.dispose(camera);
  83787. }
  83788. if (this.grain) {
  83789. this.grain.dispose(camera);
  83790. }
  83791. if (this._glowLayer) {
  83792. this._glowLayer.dispose();
  83793. }
  83794. }
  83795. }
  83796. this.imageProcessing = null;
  83797. this.fxaa = null;
  83798. if (disposeNonRecreated) {
  83799. this.sharpen = null;
  83800. this._sharpenEffect = null;
  83801. this.depthOfField = null;
  83802. this.bloom = null;
  83803. this.chromaticAberration = null;
  83804. this._chromaticAberrationEffect = null;
  83805. this.grain = null;
  83806. this._grainEffect = null;
  83807. this._glowLayer = null;
  83808. }
  83809. };
  83810. /**
  83811. * Adds a camera to the pipeline
  83812. * @param camera the camera to be added
  83813. */
  83814. DefaultRenderingPipeline.prototype.addCamera = function (camera) {
  83815. this._camerasToBeAttached.push(camera);
  83816. this._buildPipeline();
  83817. };
  83818. /**
  83819. * Removes a camera from the pipeline
  83820. * @param camera the camera to remove
  83821. */
  83822. DefaultRenderingPipeline.prototype.removeCamera = function (camera) {
  83823. var index = this._camerasToBeAttached.indexOf(camera);
  83824. this._camerasToBeAttached.splice(index, 1);
  83825. this._buildPipeline();
  83826. };
  83827. /**
  83828. * Dispose of the pipeline and stop all post processes
  83829. */
  83830. DefaultRenderingPipeline.prototype.dispose = function () {
  83831. this._disposePostProcesses(true);
  83832. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  83833. this._scene.autoClear = true;
  83834. if (this._resizeObserver) {
  83835. this._scene.getEngine().onResizeObservable.remove(this._resizeObserver);
  83836. this._resizeObserver = null;
  83837. }
  83838. this._scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigurationObserver);
  83839. _super.prototype.dispose.call(this);
  83840. };
  83841. /**
  83842. * Serialize the rendering pipeline (Used when exporting)
  83843. * @returns the serialized object
  83844. */
  83845. DefaultRenderingPipeline.prototype.serialize = function () {
  83846. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  83847. serializationObject.customType = "DefaultRenderingPipeline";
  83848. return serializationObject;
  83849. };
  83850. /**
  83851. * Parse the serialized pipeline
  83852. * @param source Source pipeline.
  83853. * @param scene The scene to load the pipeline to.
  83854. * @param rootUrl The URL of the serialized pipeline.
  83855. * @returns An instantiated pipeline from the serialized object.
  83856. */
  83857. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  83858. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  83859. };
  83860. __decorate([
  83861. BABYLON.serialize()
  83862. ], DefaultRenderingPipeline.prototype, "sharpenEnabled", null);
  83863. __decorate([
  83864. BABYLON.serialize()
  83865. ], DefaultRenderingPipeline.prototype, "bloomKernel", null);
  83866. __decorate([
  83867. BABYLON.serialize()
  83868. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  83869. __decorate([
  83870. BABYLON.serialize()
  83871. ], DefaultRenderingPipeline.prototype, "_bloomThreshold", void 0);
  83872. __decorate([
  83873. BABYLON.serialize()
  83874. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  83875. __decorate([
  83876. BABYLON.serialize()
  83877. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  83878. __decorate([
  83879. BABYLON.serialize()
  83880. ], DefaultRenderingPipeline.prototype, "bloomThreshold", null);
  83881. __decorate([
  83882. BABYLON.serialize()
  83883. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  83884. __decorate([
  83885. BABYLON.serialize()
  83886. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  83887. __decorate([
  83888. BABYLON.serialize()
  83889. ], DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", null);
  83890. __decorate([
  83891. BABYLON.serialize()
  83892. ], DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", null);
  83893. __decorate([
  83894. BABYLON.serialize()
  83895. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  83896. __decorate([
  83897. BABYLON.serialize()
  83898. ], DefaultRenderingPipeline.prototype, "samples", null);
  83899. __decorate([
  83900. BABYLON.serialize()
  83901. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  83902. __decorate([
  83903. BABYLON.serialize()
  83904. ], DefaultRenderingPipeline.prototype, "glowLayerEnabled", null);
  83905. __decorate([
  83906. BABYLON.serialize()
  83907. ], DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", null);
  83908. __decorate([
  83909. BABYLON.serialize()
  83910. ], DefaultRenderingPipeline.prototype, "grainEnabled", null);
  83911. return DefaultRenderingPipeline;
  83912. }(BABYLON.PostProcessRenderPipeline));
  83913. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  83914. })(BABYLON || (BABYLON = {}));
  83915. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  83916. var BABYLON;
  83917. (function (BABYLON) {
  83918. /**
  83919. * @hidden
  83920. */
  83921. var ImageProcessingConfigurationDefines = /** @class */ (function (_super) {
  83922. __extends(ImageProcessingConfigurationDefines, _super);
  83923. function ImageProcessingConfigurationDefines() {
  83924. var _this = _super.call(this) || this;
  83925. _this.IMAGEPROCESSING = false;
  83926. _this.VIGNETTE = false;
  83927. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  83928. _this.VIGNETTEBLENDMODEOPAQUE = false;
  83929. _this.TONEMAPPING = false;
  83930. _this.TONEMAPPING_ACES = false;
  83931. _this.CONTRAST = false;
  83932. _this.COLORCURVES = false;
  83933. _this.COLORGRADING = false;
  83934. _this.COLORGRADING3D = false;
  83935. _this.SAMPLER3DGREENDEPTH = false;
  83936. _this.SAMPLER3DBGRMAP = false;
  83937. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  83938. _this.EXPOSURE = false;
  83939. _this.rebuild();
  83940. return _this;
  83941. }
  83942. return ImageProcessingConfigurationDefines;
  83943. }(BABYLON.MaterialDefines));
  83944. BABYLON.ImageProcessingConfigurationDefines = ImageProcessingConfigurationDefines;
  83945. /**
  83946. * This groups together the common properties used for image processing either in direct forward pass
  83947. * or through post processing effect depending on the use of the image processing pipeline in your scene
  83948. * or not.
  83949. */
  83950. var ImageProcessingConfiguration = /** @class */ (function () {
  83951. function ImageProcessingConfiguration() {
  83952. /**
  83953. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  83954. */
  83955. this.colorCurves = new BABYLON.ColorCurves();
  83956. this._colorCurvesEnabled = false;
  83957. this._colorGradingEnabled = false;
  83958. this._colorGradingWithGreenDepth = true;
  83959. this._colorGradingBGR = true;
  83960. /** @hidden */
  83961. this._exposure = 1.0;
  83962. this._toneMappingEnabled = false;
  83963. this._toneMappingType = ImageProcessingConfiguration.TONEMAPPING_STANDARD;
  83964. this._contrast = 1.0;
  83965. /**
  83966. * Vignette stretch size.
  83967. */
  83968. this.vignetteStretch = 0;
  83969. /**
  83970. * Vignette centre X Offset.
  83971. */
  83972. this.vignetteCentreX = 0;
  83973. /**
  83974. * Vignette centre Y Offset.
  83975. */
  83976. this.vignetteCentreY = 0;
  83977. /**
  83978. * Vignette weight or intensity of the vignette effect.
  83979. */
  83980. this.vignetteWeight = 1.5;
  83981. /**
  83982. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  83983. * if vignetteEnabled is set to true.
  83984. */
  83985. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  83986. /**
  83987. * Camera field of view used by the Vignette effect.
  83988. */
  83989. this.vignetteCameraFov = 0.5;
  83990. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  83991. this._vignetteEnabled = false;
  83992. this._applyByPostProcess = false;
  83993. this._isEnabled = true;
  83994. /**
  83995. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  83996. */
  83997. this.onUpdateParameters = new BABYLON.Observable();
  83998. }
  83999. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  84000. /**
  84001. * Gets wether the color curves effect is enabled.
  84002. */
  84003. get: function () {
  84004. return this._colorCurvesEnabled;
  84005. },
  84006. /**
  84007. * Sets wether the color curves effect is enabled.
  84008. */
  84009. set: function (value) {
  84010. if (this._colorCurvesEnabled === value) {
  84011. return;
  84012. }
  84013. this._colorCurvesEnabled = value;
  84014. this._updateParameters();
  84015. },
  84016. enumerable: true,
  84017. configurable: true
  84018. });
  84019. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  84020. /**
  84021. * Gets wether the color grading effect is enabled.
  84022. */
  84023. get: function () {
  84024. return this._colorGradingEnabled;
  84025. },
  84026. /**
  84027. * Sets wether the color grading effect is enabled.
  84028. */
  84029. set: function (value) {
  84030. if (this._colorGradingEnabled === value) {
  84031. return;
  84032. }
  84033. this._colorGradingEnabled = value;
  84034. this._updateParameters();
  84035. },
  84036. enumerable: true,
  84037. configurable: true
  84038. });
  84039. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  84040. /**
  84041. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  84042. */
  84043. get: function () {
  84044. return this._colorGradingWithGreenDepth;
  84045. },
  84046. /**
  84047. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  84048. */
  84049. set: function (value) {
  84050. if (this._colorGradingWithGreenDepth === value) {
  84051. return;
  84052. }
  84053. this._colorGradingWithGreenDepth = value;
  84054. this._updateParameters();
  84055. },
  84056. enumerable: true,
  84057. configurable: true
  84058. });
  84059. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  84060. /**
  84061. * Gets wether the color grading texture contains BGR values.
  84062. */
  84063. get: function () {
  84064. return this._colorGradingBGR;
  84065. },
  84066. /**
  84067. * Sets wether the color grading texture contains BGR values.
  84068. */
  84069. set: function (value) {
  84070. if (this._colorGradingBGR === value) {
  84071. return;
  84072. }
  84073. this._colorGradingBGR = value;
  84074. this._updateParameters();
  84075. },
  84076. enumerable: true,
  84077. configurable: true
  84078. });
  84079. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  84080. /**
  84081. * Gets the Exposure used in the effect.
  84082. */
  84083. get: function () {
  84084. return this._exposure;
  84085. },
  84086. /**
  84087. * Sets the Exposure used in the effect.
  84088. */
  84089. set: function (value) {
  84090. if (this._exposure === value) {
  84091. return;
  84092. }
  84093. this._exposure = value;
  84094. this._updateParameters();
  84095. },
  84096. enumerable: true,
  84097. configurable: true
  84098. });
  84099. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  84100. /**
  84101. * Gets wether the tone mapping effect is enabled.
  84102. */
  84103. get: function () {
  84104. return this._toneMappingEnabled;
  84105. },
  84106. /**
  84107. * Sets wether the tone mapping effect is enabled.
  84108. */
  84109. set: function (value) {
  84110. if (this._toneMappingEnabled === value) {
  84111. return;
  84112. }
  84113. this._toneMappingEnabled = value;
  84114. this._updateParameters();
  84115. },
  84116. enumerable: true,
  84117. configurable: true
  84118. });
  84119. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingType", {
  84120. /**
  84121. * Gets the type of tone mapping effect.
  84122. */
  84123. get: function () {
  84124. return this._toneMappingType;
  84125. },
  84126. /**
  84127. * Sets the type of tone mapping effect used in BabylonJS.
  84128. */
  84129. set: function (value) {
  84130. if (this._toneMappingType === value) {
  84131. return;
  84132. }
  84133. this._toneMappingType = value;
  84134. this._updateParameters();
  84135. },
  84136. enumerable: true,
  84137. configurable: true
  84138. });
  84139. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  84140. /**
  84141. * Gets the contrast used in the effect.
  84142. */
  84143. get: function () {
  84144. return this._contrast;
  84145. },
  84146. /**
  84147. * Sets the contrast used in the effect.
  84148. */
  84149. set: function (value) {
  84150. if (this._contrast === value) {
  84151. return;
  84152. }
  84153. this._contrast = value;
  84154. this._updateParameters();
  84155. },
  84156. enumerable: true,
  84157. configurable: true
  84158. });
  84159. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  84160. /**
  84161. * Gets the vignette blend mode allowing different kind of effect.
  84162. */
  84163. get: function () {
  84164. return this._vignetteBlendMode;
  84165. },
  84166. /**
  84167. * Sets the vignette blend mode allowing different kind of effect.
  84168. */
  84169. set: function (value) {
  84170. if (this._vignetteBlendMode === value) {
  84171. return;
  84172. }
  84173. this._vignetteBlendMode = value;
  84174. this._updateParameters();
  84175. },
  84176. enumerable: true,
  84177. configurable: true
  84178. });
  84179. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  84180. /**
  84181. * Gets wether the vignette effect is enabled.
  84182. */
  84183. get: function () {
  84184. return this._vignetteEnabled;
  84185. },
  84186. /**
  84187. * Sets wether the vignette effect is enabled.
  84188. */
  84189. set: function (value) {
  84190. if (this._vignetteEnabled === value) {
  84191. return;
  84192. }
  84193. this._vignetteEnabled = value;
  84194. this._updateParameters();
  84195. },
  84196. enumerable: true,
  84197. configurable: true
  84198. });
  84199. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  84200. /**
  84201. * Gets wether the image processing is applied through a post process or not.
  84202. */
  84203. get: function () {
  84204. return this._applyByPostProcess;
  84205. },
  84206. /**
  84207. * Sets wether the image processing is applied through a post process or not.
  84208. */
  84209. set: function (value) {
  84210. if (this._applyByPostProcess === value) {
  84211. return;
  84212. }
  84213. this._applyByPostProcess = value;
  84214. this._updateParameters();
  84215. },
  84216. enumerable: true,
  84217. configurable: true
  84218. });
  84219. Object.defineProperty(ImageProcessingConfiguration.prototype, "isEnabled", {
  84220. /**
  84221. * Gets wether the image processing is enabled or not.
  84222. */
  84223. get: function () {
  84224. return this._isEnabled;
  84225. },
  84226. /**
  84227. * Sets wether the image processing is enabled or not.
  84228. */
  84229. set: function (value) {
  84230. if (this._isEnabled === value) {
  84231. return;
  84232. }
  84233. this._isEnabled = value;
  84234. this._updateParameters();
  84235. },
  84236. enumerable: true,
  84237. configurable: true
  84238. });
  84239. /**
  84240. * Method called each time the image processing information changes requires to recompile the effect.
  84241. */
  84242. ImageProcessingConfiguration.prototype._updateParameters = function () {
  84243. this.onUpdateParameters.notifyObservers(this);
  84244. };
  84245. ImageProcessingConfiguration.prototype.getClassName = function () {
  84246. return "ImageProcessingConfiguration";
  84247. };
  84248. /**
  84249. * Prepare the list of uniforms associated with the Image Processing effects.
  84250. * @param uniformsList The list of uniforms used in the effect
  84251. * @param defines the list of defines currently in use
  84252. */
  84253. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  84254. if (defines.EXPOSURE) {
  84255. uniforms.push("exposureLinear");
  84256. }
  84257. if (defines.CONTRAST) {
  84258. uniforms.push("contrast");
  84259. }
  84260. if (defines.COLORGRADING) {
  84261. uniforms.push("colorTransformSettings");
  84262. }
  84263. if (defines.VIGNETTE) {
  84264. uniforms.push("vInverseScreenSize");
  84265. uniforms.push("vignetteSettings1");
  84266. uniforms.push("vignetteSettings2");
  84267. }
  84268. if (defines.COLORCURVES) {
  84269. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  84270. }
  84271. };
  84272. /**
  84273. * Prepare the list of samplers associated with the Image Processing effects.
  84274. * @param uniformsList The list of uniforms used in the effect
  84275. * @param defines the list of defines currently in use
  84276. */
  84277. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  84278. if (defines.COLORGRADING) {
  84279. samplersList.push("txColorTransform");
  84280. }
  84281. };
  84282. /**
  84283. * Prepare the list of defines associated to the shader.
  84284. * @param defines the list of defines to complete
  84285. */
  84286. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  84287. if (forPostProcess === void 0) { forPostProcess = false; }
  84288. if (forPostProcess !== this.applyByPostProcess || !this._isEnabled) {
  84289. defines.VIGNETTE = false;
  84290. defines.TONEMAPPING = false;
  84291. defines.TONEMAPPING_ACES = false;
  84292. defines.CONTRAST = false;
  84293. defines.EXPOSURE = false;
  84294. defines.COLORCURVES = false;
  84295. defines.COLORGRADING = false;
  84296. defines.COLORGRADING3D = false;
  84297. defines.IMAGEPROCESSING = false;
  84298. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess && this._isEnabled;
  84299. return;
  84300. }
  84301. defines.VIGNETTE = this.vignetteEnabled;
  84302. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  84303. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  84304. defines.TONEMAPPING = this.toneMappingEnabled;
  84305. switch (this._toneMappingType) {
  84306. case ImageProcessingConfiguration.TONEMAPPING_ACES:
  84307. defines.TONEMAPPING_ACES = true;
  84308. break;
  84309. }
  84310. defines.CONTRAST = (this.contrast !== 1.0);
  84311. defines.EXPOSURE = (this.exposure !== 1.0);
  84312. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  84313. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  84314. if (defines.COLORGRADING) {
  84315. defines.COLORGRADING3D = this.colorGradingTexture.is3D;
  84316. }
  84317. else {
  84318. defines.COLORGRADING3D = false;
  84319. }
  84320. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  84321. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  84322. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  84323. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
  84324. };
  84325. /**
  84326. * Returns true if all the image processing information are ready.
  84327. */
  84328. ImageProcessingConfiguration.prototype.isReady = function () {
  84329. // Color Grading texure can not be none blocking.
  84330. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  84331. };
  84332. /**
  84333. * Binds the image processing to the shader.
  84334. * @param effect The effect to bind to
  84335. */
  84336. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  84337. if (aspectRatio === void 0) { aspectRatio = 1; }
  84338. // Color Curves
  84339. if (this._colorCurvesEnabled && this.colorCurves) {
  84340. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  84341. }
  84342. // Vignette
  84343. if (this._vignetteEnabled) {
  84344. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  84345. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  84346. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  84347. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  84348. var vignetteScaleX = vignetteScaleY * aspectRatio;
  84349. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  84350. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  84351. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  84352. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  84353. var vignettePower = -2.0 * this.vignetteWeight;
  84354. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  84355. }
  84356. // Exposure
  84357. effect.setFloat("exposureLinear", this.exposure);
  84358. // Contrast
  84359. effect.setFloat("contrast", this.contrast);
  84360. // Color transform settings
  84361. if (this.colorGradingTexture) {
  84362. effect.setTexture("txColorTransform", this.colorGradingTexture);
  84363. var textureSize = this.colorGradingTexture.getSize().height;
  84364. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  84365. 0.5 / textureSize, // textureOffset
  84366. textureSize, // textureSize
  84367. this.colorGradingTexture.level // weight
  84368. );
  84369. }
  84370. };
  84371. /**
  84372. * Clones the current image processing instance.
  84373. * @return The cloned image processing
  84374. */
  84375. ImageProcessingConfiguration.prototype.clone = function () {
  84376. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  84377. };
  84378. /**
  84379. * Serializes the current image processing instance to a json representation.
  84380. * @return a JSON representation
  84381. */
  84382. ImageProcessingConfiguration.prototype.serialize = function () {
  84383. return BABYLON.SerializationHelper.Serialize(this);
  84384. };
  84385. /**
  84386. * Parses the image processing from a json representation.
  84387. * @param source the JSON source to parse
  84388. * @return The parsed image processing
  84389. */
  84390. ImageProcessingConfiguration.Parse = function (source) {
  84391. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  84392. };
  84393. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  84394. /**
  84395. * Used to apply the vignette as a mix with the pixel color.
  84396. */
  84397. get: function () {
  84398. return this._VIGNETTEMODE_MULTIPLY;
  84399. },
  84400. enumerable: true,
  84401. configurable: true
  84402. });
  84403. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  84404. /**
  84405. * Used to apply the vignette as a replacement of the pixel color.
  84406. */
  84407. get: function () {
  84408. return this._VIGNETTEMODE_OPAQUE;
  84409. },
  84410. enumerable: true,
  84411. configurable: true
  84412. });
  84413. /**
  84414. * Default tone mapping applied in BabylonJS.
  84415. */
  84416. ImageProcessingConfiguration.TONEMAPPING_STANDARD = 0;
  84417. /**
  84418. * ACES Tone mapping (used by default in unreal and unity). This can help getting closer
  84419. * to other engines rendering to increase portability.
  84420. */
  84421. ImageProcessingConfiguration.TONEMAPPING_ACES = 1;
  84422. // Static constants associated to the image processing.
  84423. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  84424. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  84425. __decorate([
  84426. BABYLON.serializeAsColorCurves()
  84427. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  84428. __decorate([
  84429. BABYLON.serialize()
  84430. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  84431. __decorate([
  84432. BABYLON.serializeAsTexture()
  84433. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  84434. __decorate([
  84435. BABYLON.serialize()
  84436. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  84437. __decorate([
  84438. BABYLON.serialize()
  84439. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  84440. __decorate([
  84441. BABYLON.serialize()
  84442. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  84443. __decorate([
  84444. BABYLON.serialize()
  84445. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  84446. __decorate([
  84447. BABYLON.serialize()
  84448. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  84449. __decorate([
  84450. BABYLON.serialize()
  84451. ], ImageProcessingConfiguration.prototype, "_toneMappingType", void 0);
  84452. __decorate([
  84453. BABYLON.serialize()
  84454. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  84455. __decorate([
  84456. BABYLON.serialize()
  84457. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  84458. __decorate([
  84459. BABYLON.serialize()
  84460. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  84461. __decorate([
  84462. BABYLON.serialize()
  84463. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  84464. __decorate([
  84465. BABYLON.serialize()
  84466. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  84467. __decorate([
  84468. BABYLON.serializeAsColor4()
  84469. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  84470. __decorate([
  84471. BABYLON.serialize()
  84472. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  84473. __decorate([
  84474. BABYLON.serialize()
  84475. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  84476. __decorate([
  84477. BABYLON.serialize()
  84478. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  84479. __decorate([
  84480. BABYLON.serialize()
  84481. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  84482. __decorate([
  84483. BABYLON.serialize()
  84484. ], ImageProcessingConfiguration.prototype, "_isEnabled", void 0);
  84485. return ImageProcessingConfiguration;
  84486. }());
  84487. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  84488. })(BABYLON || (BABYLON = {}));
  84489. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  84490. var BABYLON;
  84491. (function (BABYLON) {
  84492. /**
  84493. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  84494. * It can help converting any input color in a desired output one. This can then be used to create effects
  84495. * from sepia, black and white to sixties or futuristic rendering...
  84496. *
  84497. * The only supported format is currently 3dl.
  84498. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  84499. */
  84500. var ColorGradingTexture = /** @class */ (function (_super) {
  84501. __extends(ColorGradingTexture, _super);
  84502. /**
  84503. * Instantiates a ColorGradingTexture from the following parameters.
  84504. *
  84505. * @param url The location of the color gradind data (currently only supporting 3dl)
  84506. * @param scene The scene the texture will be used in
  84507. */
  84508. function ColorGradingTexture(url, scene) {
  84509. var _this = _super.call(this, scene) || this;
  84510. if (!url) {
  84511. return _this;
  84512. }
  84513. _this._engine = scene.getEngine();
  84514. _this._textureMatrix = BABYLON.Matrix.Identity();
  84515. _this.name = url;
  84516. _this.url = url;
  84517. _this.hasAlpha = false;
  84518. _this.isCube = false;
  84519. _this.is3D = _this._engine.webGLVersion > 1;
  84520. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  84521. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  84522. _this.wrapR = BABYLON.Texture.CLAMP_ADDRESSMODE;
  84523. _this.anisotropicFilteringLevel = 1;
  84524. _this._texture = _this._getFromCache(url, true);
  84525. if (!_this._texture) {
  84526. if (!scene.useDelayedTextureLoading) {
  84527. _this.loadTexture();
  84528. }
  84529. else {
  84530. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  84531. }
  84532. }
  84533. return _this;
  84534. }
  84535. /**
  84536. * Returns the texture matrix used in most of the material.
  84537. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  84538. */
  84539. ColorGradingTexture.prototype.getTextureMatrix = function () {
  84540. return this._textureMatrix;
  84541. };
  84542. /**
  84543. * Occurs when the file being loaded is a .3dl LUT file.
  84544. */
  84545. ColorGradingTexture.prototype.load3dlTexture = function () {
  84546. var engine = this._engine;
  84547. var texture;
  84548. if (engine.webGLVersion === 1) {
  84549. texture = engine.createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  84550. }
  84551. else {
  84552. texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  84553. }
  84554. this._texture = texture;
  84555. var callback = function (text) {
  84556. if (typeof text !== "string") {
  84557. return;
  84558. }
  84559. var data = null;
  84560. var tempData = null;
  84561. var line;
  84562. var lines = text.split('\n');
  84563. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  84564. var maxColor = 0;
  84565. for (var i = 0; i < lines.length; i++) {
  84566. line = lines[i];
  84567. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  84568. continue;
  84569. if (line.indexOf('#') === 0)
  84570. continue;
  84571. var words = line.split(" ");
  84572. if (size === 0) {
  84573. // Number of space + one
  84574. size = words.length;
  84575. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  84576. tempData = new Float32Array(size * size * size * 4);
  84577. continue;
  84578. }
  84579. if (size != 0) {
  84580. var r = Math.max(parseInt(words[0]), 0);
  84581. var g = Math.max(parseInt(words[1]), 0);
  84582. var b = Math.max(parseInt(words[2]), 0);
  84583. maxColor = Math.max(r, maxColor);
  84584. maxColor = Math.max(g, maxColor);
  84585. maxColor = Math.max(b, maxColor);
  84586. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  84587. if (tempData) {
  84588. tempData[pixelStorageIndex + 0] = r;
  84589. tempData[pixelStorageIndex + 1] = g;
  84590. tempData[pixelStorageIndex + 2] = b;
  84591. }
  84592. pixelIndexSlice++;
  84593. if (pixelIndexSlice % size == 0) {
  84594. pixelIndexH++;
  84595. pixelIndexSlice = 0;
  84596. if (pixelIndexH % size == 0) {
  84597. pixelIndexW++;
  84598. pixelIndexH = 0;
  84599. }
  84600. }
  84601. }
  84602. }
  84603. if (tempData && data) {
  84604. for (var i = 0; i < tempData.length; i++) {
  84605. if (i > 0 && (i + 1) % 4 === 0) {
  84606. data[i] = 255;
  84607. }
  84608. else {
  84609. var value = tempData[i];
  84610. data[i] = (value / maxColor * 255);
  84611. }
  84612. }
  84613. }
  84614. if (texture.is3D) {
  84615. texture.updateSize(size, size, size);
  84616. engine.updateRawTexture3D(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  84617. }
  84618. else {
  84619. texture.updateSize(size * size, size);
  84620. engine.updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  84621. }
  84622. };
  84623. var scene = this.getScene();
  84624. if (scene) {
  84625. scene._loadFile(this.url, callback);
  84626. }
  84627. else {
  84628. this._engine._loadFile(this.url, callback);
  84629. }
  84630. return this._texture;
  84631. };
  84632. /**
  84633. * Starts the loading process of the texture.
  84634. */
  84635. ColorGradingTexture.prototype.loadTexture = function () {
  84636. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  84637. this.load3dlTexture();
  84638. }
  84639. };
  84640. /**
  84641. * Clones the color gradind texture.
  84642. */
  84643. ColorGradingTexture.prototype.clone = function () {
  84644. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  84645. // Base texture
  84646. newTexture.level = this.level;
  84647. return newTexture;
  84648. };
  84649. /**
  84650. * Called during delayed load for textures.
  84651. */
  84652. ColorGradingTexture.prototype.delayLoad = function () {
  84653. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  84654. return;
  84655. }
  84656. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  84657. this._texture = this._getFromCache(this.url, true);
  84658. if (!this._texture) {
  84659. this.loadTexture();
  84660. }
  84661. };
  84662. /**
  84663. * Parses a color grading texture serialized by Babylon.
  84664. * @param parsedTexture The texture information being parsedTexture
  84665. * @param scene The scene to load the texture in
  84666. * @param rootUrl The root url of the data assets to load
  84667. * @return A color gradind texture
  84668. */
  84669. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  84670. var texture = null;
  84671. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  84672. texture = new ColorGradingTexture(parsedTexture.name, scene);
  84673. texture.name = parsedTexture.name;
  84674. texture.level = parsedTexture.level;
  84675. }
  84676. return texture;
  84677. };
  84678. /**
  84679. * Serializes the LUT texture to json format.
  84680. */
  84681. ColorGradingTexture.prototype.serialize = function () {
  84682. if (!this.name) {
  84683. return null;
  84684. }
  84685. var serializationObject = {};
  84686. serializationObject.name = this.name;
  84687. serializationObject.level = this.level;
  84688. serializationObject.customType = "BABYLON.ColorGradingTexture";
  84689. return serializationObject;
  84690. };
  84691. /**
  84692. * Empty line regex stored for GC.
  84693. */
  84694. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  84695. return ColorGradingTexture;
  84696. }(BABYLON.BaseTexture));
  84697. BABYLON.ColorGradingTexture = ColorGradingTexture;
  84698. })(BABYLON || (BABYLON = {}));
  84699. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  84700. var BABYLON;
  84701. (function (BABYLON) {
  84702. /**
  84703. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  84704. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  84705. * 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;
  84706. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  84707. */
  84708. var ColorCurves = /** @class */ (function () {
  84709. function ColorCurves() {
  84710. this._dirty = true;
  84711. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  84712. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  84713. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  84714. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  84715. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  84716. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  84717. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  84718. this._globalHue = 30;
  84719. this._globalDensity = 0;
  84720. this._globalSaturation = 0;
  84721. this._globalExposure = 0;
  84722. this._highlightsHue = 30;
  84723. this._highlightsDensity = 0;
  84724. this._highlightsSaturation = 0;
  84725. this._highlightsExposure = 0;
  84726. this._midtonesHue = 30;
  84727. this._midtonesDensity = 0;
  84728. this._midtonesSaturation = 0;
  84729. this._midtonesExposure = 0;
  84730. this._shadowsHue = 30;
  84731. this._shadowsDensity = 0;
  84732. this._shadowsSaturation = 0;
  84733. this._shadowsExposure = 0;
  84734. }
  84735. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  84736. /**
  84737. * Gets the global Hue value.
  84738. * 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).
  84739. */
  84740. get: function () {
  84741. return this._globalHue;
  84742. },
  84743. /**
  84744. * Sets the global Hue value.
  84745. * 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).
  84746. */
  84747. set: function (value) {
  84748. this._globalHue = value;
  84749. this._dirty = true;
  84750. },
  84751. enumerable: true,
  84752. configurable: true
  84753. });
  84754. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  84755. /**
  84756. * Gets the global Density value.
  84757. * 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.
  84758. * Values less than zero provide a filter of opposite hue.
  84759. */
  84760. get: function () {
  84761. return this._globalDensity;
  84762. },
  84763. /**
  84764. * Sets the global Density value.
  84765. * 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.
  84766. * Values less than zero provide a filter of opposite hue.
  84767. */
  84768. set: function (value) {
  84769. this._globalDensity = value;
  84770. this._dirty = true;
  84771. },
  84772. enumerable: true,
  84773. configurable: true
  84774. });
  84775. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  84776. /**
  84777. * Gets the global Saturation value.
  84778. * 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.
  84779. */
  84780. get: function () {
  84781. return this._globalSaturation;
  84782. },
  84783. /**
  84784. * Sets the global Saturation value.
  84785. * 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.
  84786. */
  84787. set: function (value) {
  84788. this._globalSaturation = value;
  84789. this._dirty = true;
  84790. },
  84791. enumerable: true,
  84792. configurable: true
  84793. });
  84794. Object.defineProperty(ColorCurves.prototype, "globalExposure", {
  84795. /**
  84796. * Gets the global Exposure value.
  84797. * 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.
  84798. */
  84799. get: function () {
  84800. return this._globalExposure;
  84801. },
  84802. /**
  84803. * Sets the global Exposure value.
  84804. * 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.
  84805. */
  84806. set: function (value) {
  84807. this._globalExposure = value;
  84808. this._dirty = true;
  84809. },
  84810. enumerable: true,
  84811. configurable: true
  84812. });
  84813. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  84814. /**
  84815. * Gets the highlights Hue value.
  84816. * 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).
  84817. */
  84818. get: function () {
  84819. return this._highlightsHue;
  84820. },
  84821. /**
  84822. * Sets the highlights Hue value.
  84823. * 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).
  84824. */
  84825. set: function (value) {
  84826. this._highlightsHue = value;
  84827. this._dirty = true;
  84828. },
  84829. enumerable: true,
  84830. configurable: true
  84831. });
  84832. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  84833. /**
  84834. * Gets the highlights Density value.
  84835. * 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.
  84836. * Values less than zero provide a filter of opposite hue.
  84837. */
  84838. get: function () {
  84839. return this._highlightsDensity;
  84840. },
  84841. /**
  84842. * Sets the highlights Density value.
  84843. * 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.
  84844. * Values less than zero provide a filter of opposite hue.
  84845. */
  84846. set: function (value) {
  84847. this._highlightsDensity = value;
  84848. this._dirty = true;
  84849. },
  84850. enumerable: true,
  84851. configurable: true
  84852. });
  84853. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  84854. /**
  84855. * Gets the highlights Saturation value.
  84856. * 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.
  84857. */
  84858. get: function () {
  84859. return this._highlightsSaturation;
  84860. },
  84861. /**
  84862. * Sets the highlights Saturation value.
  84863. * 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.
  84864. */
  84865. set: function (value) {
  84866. this._highlightsSaturation = value;
  84867. this._dirty = true;
  84868. },
  84869. enumerable: true,
  84870. configurable: true
  84871. });
  84872. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  84873. /**
  84874. * Gets the highlights Exposure value.
  84875. * 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.
  84876. */
  84877. get: function () {
  84878. return this._highlightsExposure;
  84879. },
  84880. /**
  84881. * Sets the highlights Exposure value.
  84882. * 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.
  84883. */
  84884. set: function (value) {
  84885. this._highlightsExposure = value;
  84886. this._dirty = true;
  84887. },
  84888. enumerable: true,
  84889. configurable: true
  84890. });
  84891. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  84892. /**
  84893. * Gets the midtones Hue value.
  84894. * 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).
  84895. */
  84896. get: function () {
  84897. return this._midtonesHue;
  84898. },
  84899. /**
  84900. * Sets the midtones Hue value.
  84901. * 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).
  84902. */
  84903. set: function (value) {
  84904. this._midtonesHue = value;
  84905. this._dirty = true;
  84906. },
  84907. enumerable: true,
  84908. configurable: true
  84909. });
  84910. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  84911. /**
  84912. * Gets the midtones Density value.
  84913. * 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.
  84914. * Values less than zero provide a filter of opposite hue.
  84915. */
  84916. get: function () {
  84917. return this._midtonesDensity;
  84918. },
  84919. /**
  84920. * Sets the midtones Density value.
  84921. * 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.
  84922. * Values less than zero provide a filter of opposite hue.
  84923. */
  84924. set: function (value) {
  84925. this._midtonesDensity = value;
  84926. this._dirty = true;
  84927. },
  84928. enumerable: true,
  84929. configurable: true
  84930. });
  84931. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  84932. /**
  84933. * Gets the midtones Saturation value.
  84934. * 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.
  84935. */
  84936. get: function () {
  84937. return this._midtonesSaturation;
  84938. },
  84939. /**
  84940. * Sets the midtones Saturation value.
  84941. * 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.
  84942. */
  84943. set: function (value) {
  84944. this._midtonesSaturation = value;
  84945. this._dirty = true;
  84946. },
  84947. enumerable: true,
  84948. configurable: true
  84949. });
  84950. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  84951. /**
  84952. * Gets the midtones Exposure value.
  84953. * 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.
  84954. */
  84955. get: function () {
  84956. return this._midtonesExposure;
  84957. },
  84958. /**
  84959. * Sets the midtones Exposure value.
  84960. * 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.
  84961. */
  84962. set: function (value) {
  84963. this._midtonesExposure = value;
  84964. this._dirty = true;
  84965. },
  84966. enumerable: true,
  84967. configurable: true
  84968. });
  84969. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  84970. /**
  84971. * Gets the shadows Hue value.
  84972. * 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).
  84973. */
  84974. get: function () {
  84975. return this._shadowsHue;
  84976. },
  84977. /**
  84978. * Sets the shadows Hue value.
  84979. * 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).
  84980. */
  84981. set: function (value) {
  84982. this._shadowsHue = value;
  84983. this._dirty = true;
  84984. },
  84985. enumerable: true,
  84986. configurable: true
  84987. });
  84988. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  84989. /**
  84990. * Gets the shadows Density value.
  84991. * 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.
  84992. * Values less than zero provide a filter of opposite hue.
  84993. */
  84994. get: function () {
  84995. return this._shadowsDensity;
  84996. },
  84997. /**
  84998. * Sets the shadows Density value.
  84999. * 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.
  85000. * Values less than zero provide a filter of opposite hue.
  85001. */
  85002. set: function (value) {
  85003. this._shadowsDensity = value;
  85004. this._dirty = true;
  85005. },
  85006. enumerable: true,
  85007. configurable: true
  85008. });
  85009. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  85010. /**
  85011. * Gets the shadows Saturation value.
  85012. * 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.
  85013. */
  85014. get: function () {
  85015. return this._shadowsSaturation;
  85016. },
  85017. /**
  85018. * Sets the shadows Saturation value.
  85019. * 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.
  85020. */
  85021. set: function (value) {
  85022. this._shadowsSaturation = value;
  85023. this._dirty = true;
  85024. },
  85025. enumerable: true,
  85026. configurable: true
  85027. });
  85028. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  85029. /**
  85030. * Gets the shadows Exposure value.
  85031. * 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.
  85032. */
  85033. get: function () {
  85034. return this._shadowsExposure;
  85035. },
  85036. /**
  85037. * Sets the shadows Exposure value.
  85038. * 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.
  85039. */
  85040. set: function (value) {
  85041. this._shadowsExposure = value;
  85042. this._dirty = true;
  85043. },
  85044. enumerable: true,
  85045. configurable: true
  85046. });
  85047. ColorCurves.prototype.getClassName = function () {
  85048. return "ColorCurves";
  85049. };
  85050. /**
  85051. * Binds the color curves to the shader.
  85052. * @param colorCurves The color curve to bind
  85053. * @param effect The effect to bind to
  85054. */
  85055. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  85056. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  85057. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  85058. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  85059. if (colorCurves._dirty) {
  85060. colorCurves._dirty = false;
  85061. // Fill in global info.
  85062. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  85063. // Compute highlights info.
  85064. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  85065. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  85066. // Compute midtones info.
  85067. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  85068. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  85069. // Compute shadows info.
  85070. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  85071. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  85072. // Compute deltas (neutral is midtones).
  85073. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  85074. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  85075. }
  85076. if (effect) {
  85077. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  85078. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  85079. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  85080. }
  85081. };
  85082. /**
  85083. * Prepare the list of uniforms associated with the ColorCurves effects.
  85084. * @param uniformsList The list of uniforms used in the effect
  85085. */
  85086. ColorCurves.PrepareUniforms = function (uniformsList) {
  85087. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  85088. };
  85089. /**
  85090. * Returns color grading data based on a hue, density, saturation and exposure value.
  85091. * @param filterHue The hue of the color filter.
  85092. * @param filterDensity The density of the color filter.
  85093. * @param saturation The saturation.
  85094. * @param exposure The exposure.
  85095. * @param result The result data container.
  85096. */
  85097. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  85098. if (hue == null) {
  85099. return;
  85100. }
  85101. hue = ColorCurves.clamp(hue, 0, 360);
  85102. density = ColorCurves.clamp(density, -100, 100);
  85103. saturation = ColorCurves.clamp(saturation, -100, 100);
  85104. exposure = ColorCurves.clamp(exposure, -100, 100);
  85105. // Remap the slider/config filter density with non-linear mapping and also scale by half
  85106. // so that the maximum filter density is only 50% control. This provides fine control
  85107. // for small values and reasonable range.
  85108. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  85109. density *= 0.5;
  85110. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  85111. if (density < 0) {
  85112. density *= -1;
  85113. hue = (hue + 180) % 360;
  85114. }
  85115. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  85116. result.scaleToRef(2, result);
  85117. result.a = 1 + 0.01 * saturation;
  85118. };
  85119. /**
  85120. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  85121. * @param value The input slider value in range [-100,100].
  85122. * @returns Adjusted value.
  85123. */
  85124. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  85125. value /= 100;
  85126. var x = Math.abs(value);
  85127. x = Math.pow(x, 2);
  85128. if (value < 0) {
  85129. x *= -1;
  85130. }
  85131. x *= 100;
  85132. return x;
  85133. };
  85134. /**
  85135. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  85136. * @param hue The hue (H) input.
  85137. * @param saturation The saturation (S) input.
  85138. * @param brightness The brightness (B) input.
  85139. * @result An RGBA color represented as Vector4.
  85140. */
  85141. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  85142. var h = ColorCurves.clamp(hue, 0, 360);
  85143. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  85144. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  85145. if (s === 0) {
  85146. result.r = v;
  85147. result.g = v;
  85148. result.b = v;
  85149. }
  85150. else {
  85151. // sector 0 to 5
  85152. h /= 60;
  85153. var i = Math.floor(h);
  85154. // fractional part of h
  85155. var f = h - i;
  85156. var p = v * (1 - s);
  85157. var q = v * (1 - s * f);
  85158. var t = v * (1 - s * (1 - f));
  85159. switch (i) {
  85160. case 0:
  85161. result.r = v;
  85162. result.g = t;
  85163. result.b = p;
  85164. break;
  85165. case 1:
  85166. result.r = q;
  85167. result.g = v;
  85168. result.b = p;
  85169. break;
  85170. case 2:
  85171. result.r = p;
  85172. result.g = v;
  85173. result.b = t;
  85174. break;
  85175. case 3:
  85176. result.r = p;
  85177. result.g = q;
  85178. result.b = v;
  85179. break;
  85180. case 4:
  85181. result.r = t;
  85182. result.g = p;
  85183. result.b = v;
  85184. break;
  85185. default: // case 5:
  85186. result.r = v;
  85187. result.g = p;
  85188. result.b = q;
  85189. break;
  85190. }
  85191. }
  85192. result.a = 1;
  85193. };
  85194. /**
  85195. * Returns a value clamped between min and max
  85196. * @param value The value to clamp
  85197. * @param min The minimum of value
  85198. * @param max The maximum of value
  85199. * @returns The clamped value.
  85200. */
  85201. ColorCurves.clamp = function (value, min, max) {
  85202. return Math.min(Math.max(value, min), max);
  85203. };
  85204. /**
  85205. * Clones the current color curve instance.
  85206. * @return The cloned curves
  85207. */
  85208. ColorCurves.prototype.clone = function () {
  85209. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  85210. };
  85211. /**
  85212. * Serializes the current color curve instance to a json representation.
  85213. * @return a JSON representation
  85214. */
  85215. ColorCurves.prototype.serialize = function () {
  85216. return BABYLON.SerializationHelper.Serialize(this);
  85217. };
  85218. /**
  85219. * Parses the color curve from a json representation.
  85220. * @param source the JSON source to parse
  85221. * @return The parsed curves
  85222. */
  85223. ColorCurves.Parse = function (source) {
  85224. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  85225. };
  85226. __decorate([
  85227. BABYLON.serialize()
  85228. ], ColorCurves.prototype, "_globalHue", void 0);
  85229. __decorate([
  85230. BABYLON.serialize()
  85231. ], ColorCurves.prototype, "_globalDensity", void 0);
  85232. __decorate([
  85233. BABYLON.serialize()
  85234. ], ColorCurves.prototype, "_globalSaturation", void 0);
  85235. __decorate([
  85236. BABYLON.serialize()
  85237. ], ColorCurves.prototype, "_globalExposure", void 0);
  85238. __decorate([
  85239. BABYLON.serialize()
  85240. ], ColorCurves.prototype, "_highlightsHue", void 0);
  85241. __decorate([
  85242. BABYLON.serialize()
  85243. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  85244. __decorate([
  85245. BABYLON.serialize()
  85246. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  85247. __decorate([
  85248. BABYLON.serialize()
  85249. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  85250. __decorate([
  85251. BABYLON.serialize()
  85252. ], ColorCurves.prototype, "_midtonesHue", void 0);
  85253. __decorate([
  85254. BABYLON.serialize()
  85255. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  85256. __decorate([
  85257. BABYLON.serialize()
  85258. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  85259. __decorate([
  85260. BABYLON.serialize()
  85261. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  85262. return ColorCurves;
  85263. }());
  85264. BABYLON.ColorCurves = ColorCurves;
  85265. })(BABYLON || (BABYLON = {}));
  85266. //# sourceMappingURL=babylon.colorCurves.js.map
  85267. var BABYLON;
  85268. (function (BABYLON) {
  85269. var RefractionPostProcess = /** @class */ (function (_super) {
  85270. __extends(RefractionPostProcess, _super);
  85271. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  85272. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  85273. _this.color = color;
  85274. _this.depth = depth;
  85275. _this.colorLevel = colorLevel;
  85276. _this._ownRefractionTexture = true;
  85277. _this.onActivateObservable.add(function (cam) {
  85278. _this._refTexture = _this._refTexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  85279. });
  85280. _this.onApplyObservable.add(function (effect) {
  85281. effect.setColor3("baseColor", _this.color);
  85282. effect.setFloat("depth", _this.depth);
  85283. effect.setFloat("colorLevel", _this.colorLevel);
  85284. effect.setTexture("refractionSampler", _this._refTexture);
  85285. });
  85286. return _this;
  85287. }
  85288. Object.defineProperty(RefractionPostProcess.prototype, "refractionTexture", {
  85289. /**
  85290. * Gets or sets the refraction texture
  85291. * Please note that you are responsible for disposing the texture if you set it manually
  85292. */
  85293. get: function () {
  85294. return this._refTexture;
  85295. },
  85296. set: function (value) {
  85297. if (this._refTexture && this._ownRefractionTexture) {
  85298. this._refTexture.dispose();
  85299. }
  85300. this._refTexture = value;
  85301. this._ownRefractionTexture = false;
  85302. },
  85303. enumerable: true,
  85304. configurable: true
  85305. });
  85306. // Methods
  85307. RefractionPostProcess.prototype.dispose = function (camera) {
  85308. if (this._refTexture && this._ownRefractionTexture) {
  85309. this._refTexture.dispose();
  85310. this._refTexture = null;
  85311. }
  85312. _super.prototype.dispose.call(this, camera);
  85313. };
  85314. return RefractionPostProcess;
  85315. }(BABYLON.PostProcess));
  85316. BABYLON.RefractionPostProcess = RefractionPostProcess;
  85317. })(BABYLON || (BABYLON = {}));
  85318. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  85319. var BABYLON;
  85320. (function (BABYLON) {
  85321. var BlackAndWhitePostProcess = /** @class */ (function (_super) {
  85322. __extends(BlackAndWhitePostProcess, _super);
  85323. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  85324. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  85325. _this.degree = 1;
  85326. _this.onApplyObservable.add(function (effect) {
  85327. effect.setFloat("degree", _this.degree);
  85328. });
  85329. return _this;
  85330. }
  85331. return BlackAndWhitePostProcess;
  85332. }(BABYLON.PostProcess));
  85333. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  85334. })(BABYLON || (BABYLON = {}));
  85335. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  85336. var BABYLON;
  85337. (function (BABYLON) {
  85338. /**
  85339. * The ConvolutionPostProcess applies a 3x3 kernel to every pixel of the
  85340. * input texture to perform effects such as edge detection or sharpening
  85341. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  85342. */
  85343. var ConvolutionPostProcess = /** @class */ (function (_super) {
  85344. __extends(ConvolutionPostProcess, _super);
  85345. /**
  85346. * Creates a new instance ConvolutionPostProcess
  85347. * @param name The name of the effect.
  85348. * @param kernel Array of 9 values corrisponding to the 3x3 kernel to be applied
  85349. * @param options The required width/height ratio to downsize to before computing the render pass.
  85350. * @param camera The camera to apply the render pass to.
  85351. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  85352. * @param engine The engine which the post process will be applied. (default: current engine)
  85353. * @param reusable If the post process can be reused on the same frame. (default: false)
  85354. * @param textureType Type of textures used when performing the post process. (default: 0)
  85355. */
  85356. function ConvolutionPostProcess(name,
  85357. /** Array of 9 values corrisponding to the 3x3 kernel to be applied */
  85358. kernel, options, camera, samplingMode, engine, reusable, textureType) {
  85359. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  85360. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  85361. _this.kernel = kernel;
  85362. _this.onApply = function (effect) {
  85363. effect.setFloat2("screenSize", _this.width, _this.height);
  85364. effect.setArray("kernel", _this.kernel);
  85365. };
  85366. return _this;
  85367. }
  85368. // Statics
  85369. /**
  85370. * Edge detection 0 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  85371. */
  85372. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  85373. /**
  85374. * Edge detection 1 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  85375. */
  85376. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  85377. /**
  85378. * Edge detection 2 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  85379. */
  85380. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  85381. /**
  85382. * Kernel to sharpen an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  85383. */
  85384. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  85385. /**
  85386. * Kernel to emboss an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  85387. */
  85388. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  85389. /**
  85390. * Kernel to blur an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  85391. */
  85392. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  85393. return ConvolutionPostProcess;
  85394. }(BABYLON.PostProcess));
  85395. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  85396. })(BABYLON || (BABYLON = {}));
  85397. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  85398. var BABYLON;
  85399. (function (BABYLON) {
  85400. var FilterPostProcess = /** @class */ (function (_super) {
  85401. __extends(FilterPostProcess, _super);
  85402. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  85403. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  85404. _this.kernelMatrix = kernelMatrix;
  85405. _this.onApply = function (effect) {
  85406. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  85407. };
  85408. return _this;
  85409. }
  85410. return FilterPostProcess;
  85411. }(BABYLON.PostProcess));
  85412. BABYLON.FilterPostProcess = FilterPostProcess;
  85413. })(BABYLON || (BABYLON = {}));
  85414. //# sourceMappingURL=babylon.filterPostProcess.js.map
  85415. var BABYLON;
  85416. (function (BABYLON) {
  85417. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  85418. var VolumetricLightScatteringPostProcess = /** @class */ (function (_super) {
  85419. __extends(VolumetricLightScatteringPostProcess, _super);
  85420. /**
  85421. * @constructor
  85422. * @param {string} name - The post-process name
  85423. * @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)
  85424. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  85425. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  85426. * @param {number} samples - The post-process quality, default 100
  85427. * @param {number} samplingMode - The post-process filtering mode
  85428. * @param {BABYLON.Engine} engine - The babylon engine
  85429. * @param {boolean} reusable - If the post-process is reusable
  85430. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null a "scene" must be provided
  85431. */
  85432. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  85433. if (samples === void 0) { samples = 100; }
  85434. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  85435. 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;
  85436. _this._screenCoordinates = BABYLON.Vector2.Zero();
  85437. /**
  85438. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  85439. */
  85440. _this.customMeshPosition = BABYLON.Vector3.Zero();
  85441. /**
  85442. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  85443. */
  85444. _this.useCustomMeshPosition = false;
  85445. /**
  85446. * If the post-process should inverse the light scattering direction
  85447. */
  85448. _this.invert = true;
  85449. /**
  85450. * Array containing the excluded meshes not rendered in the internal pass
  85451. */
  85452. _this.excludedMeshes = new Array();
  85453. /**
  85454. * Controls the overall intensity of the post-process
  85455. */
  85456. _this.exposure = 0.3;
  85457. /**
  85458. * Dissipates each sample's contribution in range [0, 1]
  85459. */
  85460. _this.decay = 0.96815;
  85461. /**
  85462. * Controls the overall intensity of each sample
  85463. */
  85464. _this.weight = 0.58767;
  85465. /**
  85466. * Controls the density of each sample
  85467. */
  85468. _this.density = 0.926;
  85469. scene = ((camera === null) ? scene : camera.getScene()); // parameter "scene" can be null.
  85470. engine = scene.getEngine();
  85471. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  85472. // Configure mesh
  85473. _this.mesh = ((mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene));
  85474. // Configure
  85475. _this._createPass(scene, ratio.passRatio || ratio);
  85476. _this.onActivate = function (camera) {
  85477. if (!_this.isSupported) {
  85478. _this.dispose(camera);
  85479. }
  85480. _this.onActivate = null;
  85481. };
  85482. _this.onApplyObservable.add(function (effect) {
  85483. _this._updateMeshScreenCoordinates(scene);
  85484. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  85485. effect.setFloat("exposure", _this.exposure);
  85486. effect.setFloat("decay", _this.decay);
  85487. effect.setFloat("weight", _this.weight);
  85488. effect.setFloat("density", _this.density);
  85489. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  85490. });
  85491. return _this;
  85492. }
  85493. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  85494. get: function () {
  85495. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  85496. return false;
  85497. },
  85498. set: function (useDiffuseColor) {
  85499. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  85500. },
  85501. enumerable: true,
  85502. configurable: true
  85503. });
  85504. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  85505. return "VolumetricLightScatteringPostProcess";
  85506. };
  85507. VolumetricLightScatteringPostProcess.prototype._isReady = function (subMesh, useInstances) {
  85508. var mesh = subMesh.getMesh();
  85509. // Render this.mesh as default
  85510. if (mesh === this.mesh && mesh.material) {
  85511. return mesh.material.isReady(mesh);
  85512. }
  85513. var defines = [];
  85514. var attribs = [BABYLON.VertexBuffer.PositionKind];
  85515. var material = subMesh.getMaterial();
  85516. // Alpha test
  85517. if (material) {
  85518. if (material.needAlphaTesting()) {
  85519. defines.push("#define ALPHATEST");
  85520. }
  85521. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  85522. attribs.push(BABYLON.VertexBuffer.UVKind);
  85523. defines.push("#define UV1");
  85524. }
  85525. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  85526. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  85527. defines.push("#define UV2");
  85528. }
  85529. }
  85530. // Bones
  85531. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  85532. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  85533. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  85534. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  85535. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  85536. }
  85537. else {
  85538. defines.push("#define NUM_BONE_INFLUENCERS 0");
  85539. }
  85540. // Instances
  85541. if (useInstances) {
  85542. defines.push("#define INSTANCES");
  85543. attribs.push("world0");
  85544. attribs.push("world1");
  85545. attribs.push("world2");
  85546. attribs.push("world3");
  85547. }
  85548. // Get correct effect
  85549. var join = defines.join("\n");
  85550. if (this._cachedDefines !== join) {
  85551. this._cachedDefines = join;
  85552. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  85553. }
  85554. return this._volumetricLightScatteringPass.isReady();
  85555. };
  85556. /**
  85557. * Sets the new light position for light scattering effect
  85558. * @param {BABYLON.Vector3} The new custom light position
  85559. */
  85560. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  85561. this.customMeshPosition = position;
  85562. };
  85563. /**
  85564. * Returns the light position for light scattering effect
  85565. * @return {BABYLON.Vector3} The custom light position
  85566. */
  85567. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  85568. return this.customMeshPosition;
  85569. };
  85570. /**
  85571. * Disposes the internal assets and detaches the post-process from the camera
  85572. */
  85573. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  85574. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  85575. if (rttIndex !== -1) {
  85576. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  85577. }
  85578. this._volumetricLightScatteringRTT.dispose();
  85579. _super.prototype.dispose.call(this, camera);
  85580. };
  85581. /**
  85582. * Returns the render target texture used by the post-process
  85583. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  85584. */
  85585. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  85586. return this._volumetricLightScatteringRTT;
  85587. };
  85588. // Private methods
  85589. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  85590. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  85591. return true;
  85592. }
  85593. return false;
  85594. };
  85595. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  85596. var _this = this;
  85597. var engine = scene.getEngine();
  85598. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  85599. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  85600. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  85601. this._volumetricLightScatteringRTT.renderList = null;
  85602. this._volumetricLightScatteringRTT.renderParticles = false;
  85603. this._volumetricLightScatteringRTT.ignoreCameraViewport = true;
  85604. var camera = this.getCamera();
  85605. if (camera) {
  85606. camera.customRenderTargets.push(this._volumetricLightScatteringRTT);
  85607. }
  85608. else {
  85609. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  85610. }
  85611. // Custom render function for submeshes
  85612. var renderSubMesh = function (subMesh) {
  85613. var mesh = subMesh.getRenderingMesh();
  85614. if (_this._meshExcluded(mesh)) {
  85615. return;
  85616. }
  85617. var material = subMesh.getMaterial();
  85618. if (!material) {
  85619. return;
  85620. }
  85621. var scene = mesh.getScene();
  85622. var engine = scene.getEngine();
  85623. // Culling
  85624. engine.setState(material.backFaceCulling);
  85625. // Managing instances
  85626. var batch = mesh._getInstancesRenderList(subMesh._id);
  85627. if (batch.mustReturn) {
  85628. return;
  85629. }
  85630. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  85631. if (_this._isReady(subMesh, hardwareInstancedRendering)) {
  85632. var effect = _this._volumetricLightScatteringPass;
  85633. if (mesh === _this.mesh) {
  85634. if (subMesh.effect) {
  85635. effect = subMesh.effect;
  85636. }
  85637. else {
  85638. effect = material.getEffect();
  85639. }
  85640. }
  85641. engine.enableEffect(effect);
  85642. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  85643. if (mesh === _this.mesh) {
  85644. material.bind(mesh.getWorldMatrix(), mesh);
  85645. }
  85646. else {
  85647. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  85648. // Alpha test
  85649. if (material && material.needAlphaTesting()) {
  85650. var alphaTexture = material.getAlphaTestTexture();
  85651. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  85652. if (alphaTexture) {
  85653. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  85654. }
  85655. }
  85656. // Bones
  85657. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  85658. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  85659. }
  85660. }
  85661. // Draw
  85662. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  85663. }
  85664. };
  85665. // Render target texture callbacks
  85666. var savedSceneClearColor;
  85667. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  85668. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  85669. savedSceneClearColor = scene.clearColor;
  85670. scene.clearColor = sceneClearColor;
  85671. });
  85672. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  85673. scene.clearColor = savedSceneClearColor;
  85674. });
  85675. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  85676. var engine = scene.getEngine();
  85677. var index;
  85678. if (depthOnlySubMeshes.length) {
  85679. engine.setColorWrite(false);
  85680. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  85681. renderSubMesh(depthOnlySubMeshes.data[index]);
  85682. }
  85683. engine.setColorWrite(true);
  85684. }
  85685. for (index = 0; index < opaqueSubMeshes.length; index++) {
  85686. renderSubMesh(opaqueSubMeshes.data[index]);
  85687. }
  85688. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  85689. renderSubMesh(alphaTestSubMeshes.data[index]);
  85690. }
  85691. if (transparentSubMeshes.length) {
  85692. // Sort sub meshes
  85693. for (index = 0; index < transparentSubMeshes.length; index++) {
  85694. var submesh = transparentSubMeshes.data[index];
  85695. var boundingInfo = submesh.getBoundingInfo();
  85696. if (boundingInfo && scene.activeCamera) {
  85697. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  85698. submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  85699. }
  85700. }
  85701. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  85702. sortedArray.sort(function (a, b) {
  85703. // Alpha index first
  85704. if (a._alphaIndex > b._alphaIndex) {
  85705. return 1;
  85706. }
  85707. if (a._alphaIndex < b._alphaIndex) {
  85708. return -1;
  85709. }
  85710. // Then distance to camera
  85711. if (a._distanceToCamera < b._distanceToCamera) {
  85712. return 1;
  85713. }
  85714. if (a._distanceToCamera > b._distanceToCamera) {
  85715. return -1;
  85716. }
  85717. return 0;
  85718. });
  85719. // Render sub meshes
  85720. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  85721. for (index = 0; index < sortedArray.length; index++) {
  85722. renderSubMesh(sortedArray[index]);
  85723. }
  85724. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  85725. }
  85726. };
  85727. };
  85728. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  85729. var transform = scene.getTransformMatrix();
  85730. var meshPosition;
  85731. if (this.useCustomMeshPosition) {
  85732. meshPosition = this.customMeshPosition;
  85733. }
  85734. else if (this.attachedNode) {
  85735. meshPosition = this.attachedNode.position;
  85736. }
  85737. else {
  85738. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  85739. }
  85740. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  85741. this._screenCoordinates.x = pos.x / this._viewPort.width;
  85742. this._screenCoordinates.y = pos.y / this._viewPort.height;
  85743. if (this.invert)
  85744. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  85745. };
  85746. // Static methods
  85747. /**
  85748. * Creates a default mesh for the Volumeric Light Scattering post-process
  85749. * @param {string} The mesh name
  85750. * @param {BABYLON.Scene} The scene where to create the mesh
  85751. * @return {BABYLON.Mesh} the default mesh
  85752. */
  85753. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  85754. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  85755. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  85756. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  85757. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  85758. mesh.material = material;
  85759. return mesh;
  85760. };
  85761. __decorate([
  85762. BABYLON.serializeAsVector3()
  85763. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  85764. __decorate([
  85765. BABYLON.serialize()
  85766. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  85767. __decorate([
  85768. BABYLON.serialize()
  85769. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  85770. __decorate([
  85771. BABYLON.serializeAsMeshReference()
  85772. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  85773. __decorate([
  85774. BABYLON.serialize()
  85775. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  85776. __decorate([
  85777. BABYLON.serialize()
  85778. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  85779. __decorate([
  85780. BABYLON.serialize()
  85781. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  85782. __decorate([
  85783. BABYLON.serialize()
  85784. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  85785. __decorate([
  85786. BABYLON.serialize()
  85787. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  85788. return VolumetricLightScatteringPostProcess;
  85789. }(BABYLON.PostProcess));
  85790. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  85791. })(BABYLON || (BABYLON = {}));
  85792. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  85793. //
  85794. // This post-process allows the modification of rendered colors by using
  85795. // a 'look-up table' (LUT). This effect is also called Color Grading.
  85796. //
  85797. // The object needs to be provided an url to a texture containing the color
  85798. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  85799. // Use an image editing software to tweak the LUT to match your needs.
  85800. //
  85801. // For an example of a color LUT, see here:
  85802. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  85803. // For explanations on color grading, see here:
  85804. // http://udn.epicgames.com/Three/ColorGrading.html
  85805. //
  85806. var BABYLON;
  85807. (function (BABYLON) {
  85808. var ColorCorrectionPostProcess = /** @class */ (function (_super) {
  85809. __extends(ColorCorrectionPostProcess, _super);
  85810. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  85811. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  85812. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  85813. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  85814. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  85815. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  85816. _this.onApply = function (effect) {
  85817. effect.setTexture("colorTable", _this._colorTableTexture);
  85818. };
  85819. return _this;
  85820. }
  85821. return ColorCorrectionPostProcess;
  85822. }(BABYLON.PostProcess));
  85823. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  85824. })(BABYLON || (BABYLON = {}));
  85825. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  85826. var BABYLON;
  85827. (function (BABYLON) {
  85828. /** Defines operator used for tonemapping */
  85829. var TonemappingOperator;
  85830. (function (TonemappingOperator) {
  85831. /** Hable */
  85832. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  85833. /** Reinhard */
  85834. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  85835. /** HejiDawson */
  85836. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  85837. /** Photographic */
  85838. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  85839. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  85840. ;
  85841. /**
  85842. * Defines a post process to apply tone mapping
  85843. */
  85844. var TonemapPostProcess = /** @class */ (function (_super) {
  85845. __extends(TonemapPostProcess, _super);
  85846. /**
  85847. * Creates a new TonemapPostProcess
  85848. * @param name defines the name of the postprocess
  85849. * @param _operator defines the operator to use
  85850. * @param exposureAdjustment defines the required exposure adjustement
  85851. * @param camera defines the camera to use (can be null)
  85852. * @param samplingMode defines the required sampling mode (BABYLON.Texture.BILINEAR_SAMPLINGMODE by default)
  85853. * @param engine defines the hosting engine (can be ignore if camera is set)
  85854. * @param textureFormat defines the texture format to use (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  85855. */
  85856. function TonemapPostProcess(name, _operator,
  85857. /** Defines the required exposure adjustement */
  85858. exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  85859. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  85860. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  85861. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, null, textureFormat) || this;
  85862. _this._operator = _operator;
  85863. _this.exposureAdjustment = exposureAdjustment;
  85864. var defines = "#define ";
  85865. if (_this._operator === TonemappingOperator.Hable)
  85866. defines += "HABLE_TONEMAPPING";
  85867. else if (_this._operator === TonemappingOperator.Reinhard)
  85868. defines += "REINHARD_TONEMAPPING";
  85869. else if (_this._operator === TonemappingOperator.HejiDawson)
  85870. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  85871. else if (_this._operator === TonemappingOperator.Photographic)
  85872. defines += "PHOTOGRAPHIC_TONEMAPPING";
  85873. //sadly a second call to create the effect.
  85874. _this.updateEffect(defines);
  85875. _this.onApply = function (effect) {
  85876. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  85877. };
  85878. return _this;
  85879. }
  85880. return TonemapPostProcess;
  85881. }(BABYLON.PostProcess));
  85882. BABYLON.TonemapPostProcess = TonemapPostProcess;
  85883. })(BABYLON || (BABYLON = {}));
  85884. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  85885. var BABYLON;
  85886. (function (BABYLON) {
  85887. var DisplayPassPostProcess = /** @class */ (function (_super) {
  85888. __extends(DisplayPassPostProcess, _super);
  85889. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  85890. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  85891. }
  85892. return DisplayPassPostProcess;
  85893. }(BABYLON.PostProcess));
  85894. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  85895. })(BABYLON || (BABYLON = {}));
  85896. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  85897. var BABYLON;
  85898. (function (BABYLON) {
  85899. var HighlightsPostProcess = /** @class */ (function (_super) {
  85900. __extends(HighlightsPostProcess, _super);
  85901. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  85902. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  85903. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  85904. }
  85905. return HighlightsPostProcess;
  85906. }(BABYLON.PostProcess));
  85907. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  85908. })(BABYLON || (BABYLON = {}));
  85909. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  85910. var BABYLON;
  85911. (function (BABYLON) {
  85912. var ImageProcessingPostProcess = /** @class */ (function (_super) {
  85913. __extends(ImageProcessingPostProcess, _super);
  85914. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, imageProcessingConfiguration) {
  85915. if (camera === void 0) { camera = null; }
  85916. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  85917. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  85918. _this._fromLinearSpace = true;
  85919. /**
  85920. * Defines cache preventing GC.
  85921. */
  85922. _this._defines = {
  85923. IMAGEPROCESSING: false,
  85924. VIGNETTE: false,
  85925. VIGNETTEBLENDMODEMULTIPLY: false,
  85926. VIGNETTEBLENDMODEOPAQUE: false,
  85927. TONEMAPPING: false,
  85928. TONEMAPPING_ACES: false,
  85929. CONTRAST: false,
  85930. COLORCURVES: false,
  85931. COLORGRADING: false,
  85932. COLORGRADING3D: false,
  85933. FROMLINEARSPACE: false,
  85934. SAMPLER3DGREENDEPTH: false,
  85935. SAMPLER3DBGRMAP: false,
  85936. IMAGEPROCESSINGPOSTPROCESS: false,
  85937. EXPOSURE: false,
  85938. };
  85939. // Setup the configuration as forced by the constructor. This would then not force the
  85940. // scene materials output in linear space and let untouched the default forward pass.
  85941. if (imageProcessingConfiguration) {
  85942. imageProcessingConfiguration.applyByPostProcess = true;
  85943. _this._attachImageProcessingConfiguration(imageProcessingConfiguration, true);
  85944. // This will cause the shader to be compiled
  85945. _this.fromLinearSpace = false;
  85946. }
  85947. // Setup the default processing configuration to the scene.
  85948. else {
  85949. _this._attachImageProcessingConfiguration(null, true);
  85950. _this.imageProcessingConfiguration.applyByPostProcess = true;
  85951. }
  85952. _this.onApply = function (effect) {
  85953. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  85954. };
  85955. return _this;
  85956. }
  85957. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  85958. /**
  85959. * Gets the image processing configuration used either in this material.
  85960. */
  85961. get: function () {
  85962. return this._imageProcessingConfiguration;
  85963. },
  85964. /**
  85965. * Sets the Default image processing configuration used either in the this material.
  85966. *
  85967. * If sets to null, the scene one is in use.
  85968. */
  85969. set: function (value) {
  85970. this._attachImageProcessingConfiguration(value);
  85971. },
  85972. enumerable: true,
  85973. configurable: true
  85974. });
  85975. /**
  85976. * Attaches a new image processing configuration to the PBR Material.
  85977. * @param configuration
  85978. */
  85979. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  85980. var _this = this;
  85981. if (doNotBuild === void 0) { doNotBuild = false; }
  85982. if (configuration === this._imageProcessingConfiguration) {
  85983. return;
  85984. }
  85985. // Detaches observer.
  85986. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  85987. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  85988. }
  85989. // Pick the scene configuration if needed.
  85990. if (!configuration) {
  85991. var scene = null;
  85992. var engine = this.getEngine();
  85993. var camera = this.getCamera();
  85994. if (camera) {
  85995. scene = camera.getScene();
  85996. }
  85997. else if (engine && engine.scenes) {
  85998. var scenes = engine.scenes;
  85999. scene = scenes[scenes.length - 1];
  86000. }
  86001. else {
  86002. scene = BABYLON.Engine.LastCreatedScene;
  86003. }
  86004. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  86005. }
  86006. else {
  86007. this._imageProcessingConfiguration = configuration;
  86008. }
  86009. // Attaches observer.
  86010. if (this._imageProcessingConfiguration) {
  86011. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  86012. _this._updateParameters();
  86013. });
  86014. }
  86015. // Ensure the effect will be rebuilt.
  86016. if (!doNotBuild) {
  86017. this._updateParameters();
  86018. }
  86019. };
  86020. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  86021. /**
  86022. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  86023. */
  86024. get: function () {
  86025. return this.imageProcessingConfiguration.colorCurves;
  86026. },
  86027. /**
  86028. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  86029. */
  86030. set: function (value) {
  86031. this.imageProcessingConfiguration.colorCurves = value;
  86032. },
  86033. enumerable: true,
  86034. configurable: true
  86035. });
  86036. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  86037. /**
  86038. * Gets wether the color curves effect is enabled.
  86039. */
  86040. get: function () {
  86041. return this.imageProcessingConfiguration.colorCurvesEnabled;
  86042. },
  86043. /**
  86044. * Sets wether the color curves effect is enabled.
  86045. */
  86046. set: function (value) {
  86047. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  86048. },
  86049. enumerable: true,
  86050. configurable: true
  86051. });
  86052. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  86053. /**
  86054. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  86055. */
  86056. get: function () {
  86057. return this.imageProcessingConfiguration.colorGradingTexture;
  86058. },
  86059. /**
  86060. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  86061. */
  86062. set: function (value) {
  86063. this.imageProcessingConfiguration.colorGradingTexture = value;
  86064. },
  86065. enumerable: true,
  86066. configurable: true
  86067. });
  86068. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  86069. /**
  86070. * Gets wether the color grading effect is enabled.
  86071. */
  86072. get: function () {
  86073. return this.imageProcessingConfiguration.colorGradingEnabled;
  86074. },
  86075. /**
  86076. * Gets wether the color grading effect is enabled.
  86077. */
  86078. set: function (value) {
  86079. this.imageProcessingConfiguration.colorGradingEnabled = value;
  86080. },
  86081. enumerable: true,
  86082. configurable: true
  86083. });
  86084. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  86085. /**
  86086. * Gets exposure used in the effect.
  86087. */
  86088. get: function () {
  86089. return this.imageProcessingConfiguration.exposure;
  86090. },
  86091. /**
  86092. * Sets exposure used in the effect.
  86093. */
  86094. set: function (value) {
  86095. this.imageProcessingConfiguration.exposure = value;
  86096. },
  86097. enumerable: true,
  86098. configurable: true
  86099. });
  86100. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  86101. /**
  86102. * Gets wether tonemapping is enabled or not.
  86103. */
  86104. get: function () {
  86105. return this._imageProcessingConfiguration.toneMappingEnabled;
  86106. },
  86107. /**
  86108. * Sets wether tonemapping is enabled or not
  86109. */
  86110. set: function (value) {
  86111. this._imageProcessingConfiguration.toneMappingEnabled = value;
  86112. },
  86113. enumerable: true,
  86114. configurable: true
  86115. });
  86116. ;
  86117. ;
  86118. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  86119. /**
  86120. * Gets contrast used in the effect.
  86121. */
  86122. get: function () {
  86123. return this.imageProcessingConfiguration.contrast;
  86124. },
  86125. /**
  86126. * Sets contrast used in the effect.
  86127. */
  86128. set: function (value) {
  86129. this.imageProcessingConfiguration.contrast = value;
  86130. },
  86131. enumerable: true,
  86132. configurable: true
  86133. });
  86134. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  86135. /**
  86136. * Gets Vignette stretch size.
  86137. */
  86138. get: function () {
  86139. return this.imageProcessingConfiguration.vignetteStretch;
  86140. },
  86141. /**
  86142. * Sets Vignette stretch size.
  86143. */
  86144. set: function (value) {
  86145. this.imageProcessingConfiguration.vignetteStretch = value;
  86146. },
  86147. enumerable: true,
  86148. configurable: true
  86149. });
  86150. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  86151. /**
  86152. * Gets Vignette centre X Offset.
  86153. */
  86154. get: function () {
  86155. return this.imageProcessingConfiguration.vignetteCentreX;
  86156. },
  86157. /**
  86158. * Sets Vignette centre X Offset.
  86159. */
  86160. set: function (value) {
  86161. this.imageProcessingConfiguration.vignetteCentreX = value;
  86162. },
  86163. enumerable: true,
  86164. configurable: true
  86165. });
  86166. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  86167. /**
  86168. * Gets Vignette centre Y Offset.
  86169. */
  86170. get: function () {
  86171. return this.imageProcessingConfiguration.vignetteCentreY;
  86172. },
  86173. /**
  86174. * Sets Vignette centre Y Offset.
  86175. */
  86176. set: function (value) {
  86177. this.imageProcessingConfiguration.vignetteCentreY = value;
  86178. },
  86179. enumerable: true,
  86180. configurable: true
  86181. });
  86182. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  86183. /**
  86184. * Gets Vignette weight or intensity of the vignette effect.
  86185. */
  86186. get: function () {
  86187. return this.imageProcessingConfiguration.vignetteWeight;
  86188. },
  86189. /**
  86190. * Sets Vignette weight or intensity of the vignette effect.
  86191. */
  86192. set: function (value) {
  86193. this.imageProcessingConfiguration.vignetteWeight = value;
  86194. },
  86195. enumerable: true,
  86196. configurable: true
  86197. });
  86198. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  86199. /**
  86200. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  86201. * if vignetteEnabled is set to true.
  86202. */
  86203. get: function () {
  86204. return this.imageProcessingConfiguration.vignetteColor;
  86205. },
  86206. /**
  86207. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  86208. * if vignetteEnabled is set to true.
  86209. */
  86210. set: function (value) {
  86211. this.imageProcessingConfiguration.vignetteColor = value;
  86212. },
  86213. enumerable: true,
  86214. configurable: true
  86215. });
  86216. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  86217. /**
  86218. * Gets Camera field of view used by the Vignette effect.
  86219. */
  86220. get: function () {
  86221. return this.imageProcessingConfiguration.vignetteCameraFov;
  86222. },
  86223. /**
  86224. * Sets Camera field of view used by the Vignette effect.
  86225. */
  86226. set: function (value) {
  86227. this.imageProcessingConfiguration.vignetteCameraFov = value;
  86228. },
  86229. enumerable: true,
  86230. configurable: true
  86231. });
  86232. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  86233. /**
  86234. * Gets the vignette blend mode allowing different kind of effect.
  86235. */
  86236. get: function () {
  86237. return this.imageProcessingConfiguration.vignetteBlendMode;
  86238. },
  86239. /**
  86240. * Sets the vignette blend mode allowing different kind of effect.
  86241. */
  86242. set: function (value) {
  86243. this.imageProcessingConfiguration.vignetteBlendMode = value;
  86244. },
  86245. enumerable: true,
  86246. configurable: true
  86247. });
  86248. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  86249. /**
  86250. * Gets wether the vignette effect is enabled.
  86251. */
  86252. get: function () {
  86253. return this.imageProcessingConfiguration.vignetteEnabled;
  86254. },
  86255. /**
  86256. * Sets wether the vignette effect is enabled.
  86257. */
  86258. set: function (value) {
  86259. this.imageProcessingConfiguration.vignetteEnabled = value;
  86260. },
  86261. enumerable: true,
  86262. configurable: true
  86263. });
  86264. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  86265. /**
  86266. * Gets wether the input of the processing is in Gamma or Linear Space.
  86267. */
  86268. get: function () {
  86269. return this._fromLinearSpace;
  86270. },
  86271. /**
  86272. * Sets wether the input of the processing is in Gamma or Linear Space.
  86273. */
  86274. set: function (value) {
  86275. if (this._fromLinearSpace === value) {
  86276. return;
  86277. }
  86278. this._fromLinearSpace = value;
  86279. this._updateParameters();
  86280. },
  86281. enumerable: true,
  86282. configurable: true
  86283. });
  86284. ImageProcessingPostProcess.prototype.getClassName = function () {
  86285. return "ImageProcessingPostProcess";
  86286. };
  86287. ImageProcessingPostProcess.prototype._updateParameters = function () {
  86288. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  86289. this.imageProcessingConfiguration.prepareDefines(this._defines, true);
  86290. var defines = "";
  86291. for (var define in this._defines) {
  86292. if (this._defines[define]) {
  86293. defines += "#define " + define + ";\r\n";
  86294. }
  86295. }
  86296. var samplers = ["textureSampler"];
  86297. var uniforms = ["scale"];
  86298. if (BABYLON.ImageProcessingConfiguration) {
  86299. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  86300. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  86301. }
  86302. this.updateEffect(defines, uniforms, samplers);
  86303. };
  86304. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  86305. _super.prototype.dispose.call(this, camera);
  86306. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  86307. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  86308. }
  86309. if (this._imageProcessingConfiguration) {
  86310. this.imageProcessingConfiguration.applyByPostProcess = false;
  86311. }
  86312. };
  86313. __decorate([
  86314. BABYLON.serialize()
  86315. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  86316. return ImageProcessingPostProcess;
  86317. }(BABYLON.PostProcess));
  86318. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  86319. })(BABYLON || (BABYLON = {}));
  86320. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  86321. var BABYLON;
  86322. (function (BABYLON) {
  86323. /**
  86324. * Class used to store bone information
  86325. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  86326. */
  86327. var Bone = /** @class */ (function (_super) {
  86328. __extends(Bone, _super);
  86329. /**
  86330. * Create a new bone
  86331. * @param name defines the bone name
  86332. * @param skeleton defines the parent skeleton
  86333. * @param parentBone defines the parent (can be null if the bone is the root)
  86334. * @param localMatrix defines the local matrix
  86335. * @param restPose defines the rest pose matrix
  86336. * @param baseMatrix defines the base matrix
  86337. * @param index defines index of the bone in the hiearchy
  86338. */
  86339. function Bone(
  86340. /**
  86341. * defines the bone name
  86342. */
  86343. name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  86344. if (parentBone === void 0) { parentBone = null; }
  86345. if (localMatrix === void 0) { localMatrix = null; }
  86346. if (restPose === void 0) { restPose = null; }
  86347. if (baseMatrix === void 0) { baseMatrix = null; }
  86348. if (index === void 0) { index = null; }
  86349. var _this = _super.call(this, name, skeleton.getScene()) || this;
  86350. _this.name = name;
  86351. /**
  86352. * Gets the list of child bones
  86353. */
  86354. _this.children = new Array();
  86355. /** Gets the animations associated with this bone */
  86356. _this.animations = new Array();
  86357. /**
  86358. * @hidden Internal only
  86359. * Set this value to map this bone to a different index in the transform matrices
  86360. * Set this value to -1 to exclude the bone from the transform matrices
  86361. */
  86362. _this._index = null;
  86363. _this._absoluteTransform = new BABYLON.Matrix();
  86364. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  86365. _this._scalingDeterminant = 1;
  86366. _this._worldTransform = new BABYLON.Matrix();
  86367. _this._needToDecompose = true;
  86368. _this._needToCompose = false;
  86369. _this._skeleton = skeleton;
  86370. _this._localMatrix = localMatrix ? localMatrix.clone() : BABYLON.Matrix.Identity();
  86371. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  86372. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  86373. _this._index = index;
  86374. skeleton.bones.push(_this);
  86375. _this.setParent(parentBone, false);
  86376. if (baseMatrix || localMatrix) {
  86377. _this._updateDifferenceMatrix();
  86378. }
  86379. return _this;
  86380. }
  86381. Object.defineProperty(Bone.prototype, "_matrix", {
  86382. /** @hidden */
  86383. get: function () {
  86384. this._compose();
  86385. return this._localMatrix;
  86386. },
  86387. /** @hidden */
  86388. set: function (value) {
  86389. this._localMatrix.copyFrom(value);
  86390. this._needToDecompose = true;
  86391. },
  86392. enumerable: true,
  86393. configurable: true
  86394. });
  86395. // Members
  86396. /**
  86397. * Gets the parent skeleton
  86398. * @returns a skeleton
  86399. */
  86400. Bone.prototype.getSkeleton = function () {
  86401. return this._skeleton;
  86402. };
  86403. /**
  86404. * Gets parent bone
  86405. * @returns a bone or null if the bone is the root of the bone hierarchy
  86406. */
  86407. Bone.prototype.getParent = function () {
  86408. return this._parent;
  86409. };
  86410. /**
  86411. * Sets the parent bone
  86412. * @param parent defines the parent (can be null if the bone is the root)
  86413. * @param updateDifferenceMatrix defines if the difference matrix must be updated
  86414. */
  86415. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  86416. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  86417. if (this._parent === parent) {
  86418. return;
  86419. }
  86420. if (this._parent) {
  86421. var index = this._parent.children.indexOf(this);
  86422. if (index !== -1) {
  86423. this._parent.children.splice(index, 1);
  86424. }
  86425. }
  86426. this._parent = parent;
  86427. if (this._parent) {
  86428. this._parent.children.push(this);
  86429. }
  86430. if (updateDifferenceMatrix) {
  86431. this._updateDifferenceMatrix();
  86432. }
  86433. this.markAsDirty();
  86434. };
  86435. /**
  86436. * Gets the local matrix
  86437. * @returns a matrix
  86438. */
  86439. Bone.prototype.getLocalMatrix = function () {
  86440. this._compose();
  86441. return this._localMatrix;
  86442. };
  86443. /**
  86444. * Gets the base matrix (initial matrix which remains unchanged)
  86445. * @returns a matrix
  86446. */
  86447. Bone.prototype.getBaseMatrix = function () {
  86448. return this._baseMatrix;
  86449. };
  86450. /**
  86451. * Gets the rest pose matrix
  86452. * @returns a matrix
  86453. */
  86454. Bone.prototype.getRestPose = function () {
  86455. return this._restPose;
  86456. };
  86457. /**
  86458. * Gets a matrix used to store world matrix (ie. the matrix sent to shaders)
  86459. */
  86460. Bone.prototype.getWorldMatrix = function () {
  86461. return this._worldTransform;
  86462. };
  86463. /**
  86464. * Sets the local matrix to rest pose matrix
  86465. */
  86466. Bone.prototype.returnToRest = function () {
  86467. this.updateMatrix(this._restPose.clone());
  86468. };
  86469. /**
  86470. * Gets the inverse of the absolute transform matrix.
  86471. * This matrix will be multiplied by local matrix to get the difference matrix (ie. the difference between original state and current state)
  86472. * @returns a matrix
  86473. */
  86474. Bone.prototype.getInvertedAbsoluteTransform = function () {
  86475. return this._invertedAbsoluteTransform;
  86476. };
  86477. /**
  86478. * Gets the absolute transform matrix (ie base matrix * parent world matrix)
  86479. * @returns a matrix
  86480. */
  86481. Bone.prototype.getAbsoluteTransform = function () {
  86482. return this._absoluteTransform;
  86483. };
  86484. Object.defineProperty(Bone.prototype, "position", {
  86485. // Properties (matches AbstractMesh properties)
  86486. /** Gets or sets current position (in local space) */
  86487. get: function () {
  86488. this._decompose();
  86489. return this._localPosition;
  86490. },
  86491. set: function (newPosition) {
  86492. this._decompose();
  86493. this._localPosition.copyFrom(newPosition);
  86494. this._markAsDirtyAndCompose();
  86495. },
  86496. enumerable: true,
  86497. configurable: true
  86498. });
  86499. Object.defineProperty(Bone.prototype, "rotation", {
  86500. /** Gets or sets current rotation (in local space) */
  86501. get: function () {
  86502. return this.getRotation();
  86503. },
  86504. set: function (newRotation) {
  86505. this.setRotation(newRotation);
  86506. },
  86507. enumerable: true,
  86508. configurable: true
  86509. });
  86510. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  86511. /** Gets or sets current rotation quaternion (in local space) */
  86512. get: function () {
  86513. this._decompose();
  86514. return this._localRotation;
  86515. },
  86516. set: function (newRotation) {
  86517. this.setRotationQuaternion(newRotation);
  86518. },
  86519. enumerable: true,
  86520. configurable: true
  86521. });
  86522. Object.defineProperty(Bone.prototype, "scaling", {
  86523. /** Gets or sets current scaling (in local space) */
  86524. get: function () {
  86525. return this.getScale();
  86526. },
  86527. set: function (newScaling) {
  86528. this.setScale(newScaling);
  86529. },
  86530. enumerable: true,
  86531. configurable: true
  86532. });
  86533. Object.defineProperty(Bone.prototype, "animationPropertiesOverride", {
  86534. /**
  86535. * Gets the animation properties override
  86536. */
  86537. get: function () {
  86538. return this._skeleton.animationPropertiesOverride;
  86539. },
  86540. enumerable: true,
  86541. configurable: true
  86542. });
  86543. // Methods
  86544. Bone.prototype._decompose = function () {
  86545. if (!this._needToDecompose) {
  86546. return;
  86547. }
  86548. this._needToDecompose = false;
  86549. if (!this._localScaling) {
  86550. this._localScaling = BABYLON.Vector3.Zero();
  86551. this._localRotation = BABYLON.Quaternion.Zero();
  86552. this._localPosition = BABYLON.Vector3.Zero();
  86553. }
  86554. this._localMatrix.decompose(this._localScaling, this._localRotation, this._localPosition);
  86555. };
  86556. Bone.prototype._compose = function () {
  86557. if (!this._needToCompose) {
  86558. return;
  86559. }
  86560. this._needToCompose = false;
  86561. BABYLON.Matrix.ComposeToRef(this._localScaling, this._localRotation, this._localPosition, this._localMatrix);
  86562. };
  86563. /**
  86564. * Update the base and local matrices
  86565. * @param matrix defines the new base or local matrix
  86566. * @param updateDifferenceMatrix defines if the difference matrix must be updated
  86567. * @param updateLocalMatrix defines if the local matrix should be updated
  86568. */
  86569. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix, updateLocalMatrix) {
  86570. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  86571. if (updateLocalMatrix === void 0) { updateLocalMatrix = true; }
  86572. this._baseMatrix.copyFrom(matrix);
  86573. if (updateDifferenceMatrix) {
  86574. this._updateDifferenceMatrix();
  86575. }
  86576. if (updateLocalMatrix) {
  86577. this._localMatrix.copyFrom(matrix);
  86578. this._markAsDirtyAndDecompose();
  86579. }
  86580. else {
  86581. this.markAsDirty();
  86582. }
  86583. };
  86584. /** @hidden */
  86585. Bone.prototype._updateDifferenceMatrix = function (rootMatrix, updateChildren) {
  86586. if (updateChildren === void 0) { updateChildren = true; }
  86587. if (!rootMatrix) {
  86588. rootMatrix = this._baseMatrix;
  86589. }
  86590. if (this._parent) {
  86591. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  86592. }
  86593. else {
  86594. this._absoluteTransform.copyFrom(rootMatrix);
  86595. }
  86596. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  86597. if (updateChildren) {
  86598. for (var index = 0; index < this.children.length; index++) {
  86599. this.children[index]._updateDifferenceMatrix();
  86600. }
  86601. }
  86602. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  86603. };
  86604. /**
  86605. * Flag the bone as dirty (Forcing it to update everything)
  86606. */
  86607. Bone.prototype.markAsDirty = function () {
  86608. this._currentRenderId++;
  86609. this._childRenderId++;
  86610. this._skeleton._markAsDirty();
  86611. };
  86612. Bone.prototype._markAsDirtyAndCompose = function () {
  86613. this.markAsDirty();
  86614. this._needToCompose = true;
  86615. };
  86616. Bone.prototype._markAsDirtyAndDecompose = function () {
  86617. this.markAsDirty();
  86618. this._needToDecompose = true;
  86619. };
  86620. /**
  86621. * Copy an animation range from another bone
  86622. * @param source defines the source bone
  86623. * @param rangeName defines the range name to copy
  86624. * @param frameOffset defines the frame offset
  86625. * @param rescaleAsRequired defines if rescaling must be applied if required
  86626. * @param skelDimensionsRatio defines the scaling ratio
  86627. * @returns true if operation was successful
  86628. */
  86629. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  86630. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  86631. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  86632. // all animation may be coming from a library skeleton, so may need to create animation
  86633. if (this.animations.length === 0) {
  86634. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  86635. this.animations[0].setKeys([]);
  86636. }
  86637. // get animation info / verify there is such a range from the source bone
  86638. var sourceRange = source.animations[0].getRange(rangeName);
  86639. if (!sourceRange) {
  86640. return false;
  86641. }
  86642. var from = sourceRange.from;
  86643. var to = sourceRange.to;
  86644. var sourceKeys = source.animations[0].getKeys();
  86645. // rescaling prep
  86646. var sourceBoneLength = source.length;
  86647. var sourceParent = source.getParent();
  86648. var parent = this.getParent();
  86649. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  86650. var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1;
  86651. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  86652. var destKeys = this.animations[0].getKeys();
  86653. // loop vars declaration
  86654. var orig;
  86655. var origTranslation;
  86656. var mat;
  86657. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  86658. orig = sourceKeys[key];
  86659. if (orig.frame >= from && orig.frame <= to) {
  86660. if (rescaleAsRequired) {
  86661. mat = orig.value.clone();
  86662. // scale based on parent ratio, when bone has parent
  86663. if (parentScalingReqd) {
  86664. origTranslation = mat.getTranslation();
  86665. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  86666. // scale based on skeleton dimension ratio when root bone, and value is passed
  86667. }
  86668. else if (dimensionsScalingReqd && skelDimensionsRatio) {
  86669. origTranslation = mat.getTranslation();
  86670. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  86671. // use original when root bone, and no data for skelDimensionsRatio
  86672. }
  86673. else {
  86674. mat = orig.value;
  86675. }
  86676. }
  86677. else {
  86678. mat = orig.value;
  86679. }
  86680. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  86681. }
  86682. }
  86683. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  86684. return true;
  86685. };
  86686. /**
  86687. * Translate the bone in local or world space
  86688. * @param vec The amount to translate the bone
  86689. * @param space The space that the translation is in
  86690. * @param mesh The mesh that this bone is attached to. This is only used in world space
  86691. */
  86692. Bone.prototype.translate = function (vec, space, mesh) {
  86693. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  86694. var lm = this.getLocalMatrix();
  86695. if (space == BABYLON.Space.LOCAL) {
  86696. lm.m[12] += vec.x;
  86697. lm.m[13] += vec.y;
  86698. lm.m[14] += vec.z;
  86699. }
  86700. else {
  86701. var wm = null;
  86702. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  86703. if (mesh) {
  86704. wm = mesh.getWorldMatrix();
  86705. }
  86706. this._skeleton.computeAbsoluteTransforms();
  86707. var tmat = Bone._tmpMats[0];
  86708. var tvec = Bone._tmpVecs[0];
  86709. if (this._parent) {
  86710. if (mesh && wm) {
  86711. tmat.copyFrom(this._parent.getAbsoluteTransform());
  86712. tmat.multiplyToRef(wm, tmat);
  86713. }
  86714. else {
  86715. tmat.copyFrom(this._parent.getAbsoluteTransform());
  86716. }
  86717. }
  86718. tmat.m[12] = 0;
  86719. tmat.m[13] = 0;
  86720. tmat.m[14] = 0;
  86721. tmat.invert();
  86722. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  86723. lm.m[12] += tvec.x;
  86724. lm.m[13] += tvec.y;
  86725. lm.m[14] += tvec.z;
  86726. }
  86727. this._markAsDirtyAndDecompose();
  86728. };
  86729. /**
  86730. * Set the postion of the bone in local or world space
  86731. * @param position The position to set the bone
  86732. * @param space The space that the position is in
  86733. * @param mesh The mesh that this bone is attached to. This is only used in world space
  86734. */
  86735. Bone.prototype.setPosition = function (position, space, mesh) {
  86736. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  86737. var lm = this.getLocalMatrix();
  86738. if (space == BABYLON.Space.LOCAL) {
  86739. lm.m[12] = position.x;
  86740. lm.m[13] = position.y;
  86741. lm.m[14] = position.z;
  86742. }
  86743. else {
  86744. var wm = null;
  86745. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  86746. if (mesh) {
  86747. wm = mesh.getWorldMatrix();
  86748. }
  86749. this._skeleton.computeAbsoluteTransforms();
  86750. var tmat = Bone._tmpMats[0];
  86751. var vec = Bone._tmpVecs[0];
  86752. if (this._parent) {
  86753. if (mesh && wm) {
  86754. tmat.copyFrom(this._parent.getAbsoluteTransform());
  86755. tmat.multiplyToRef(wm, tmat);
  86756. }
  86757. else {
  86758. tmat.copyFrom(this._parent.getAbsoluteTransform());
  86759. }
  86760. }
  86761. tmat.invert();
  86762. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  86763. lm.m[12] = vec.x;
  86764. lm.m[13] = vec.y;
  86765. lm.m[14] = vec.z;
  86766. }
  86767. this._markAsDirtyAndDecompose();
  86768. };
  86769. /**
  86770. * Set the absolute position of the bone (world space)
  86771. * @param position The position to set the bone
  86772. * @param mesh The mesh that this bone is attached to
  86773. */
  86774. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  86775. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  86776. };
  86777. /**
  86778. * Scale the bone on the x, y and z axes (in local space)
  86779. * @param x The amount to scale the bone on the x axis
  86780. * @param y The amount to scale the bone on the y axis
  86781. * @param z The amount to scale the bone on the z axis
  86782. * @param scaleChildren sets this to true if children of the bone should be scaled as well (false by default)
  86783. */
  86784. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  86785. if (scaleChildren === void 0) { scaleChildren = false; }
  86786. var locMat = this.getLocalMatrix();
  86787. // Apply new scaling on top of current local matrix
  86788. var scaleMat = Bone._tmpMats[0];
  86789. BABYLON.Matrix.ScalingToRef(x, y, z, scaleMat);
  86790. scaleMat.multiplyToRef(locMat, locMat);
  86791. // Invert scaling matrix and apply the inverse to all children
  86792. scaleMat.invert();
  86793. for (var _i = 0, _a = this.children; _i < _a.length; _i++) {
  86794. var child = _a[_i];
  86795. var cm = child.getLocalMatrix();
  86796. cm.multiplyToRef(scaleMat, cm);
  86797. cm.m[12] *= x;
  86798. cm.m[13] *= y;
  86799. cm.m[14] *= z;
  86800. child._markAsDirtyAndDecompose();
  86801. }
  86802. this._markAsDirtyAndDecompose();
  86803. if (scaleChildren) {
  86804. for (var _b = 0, _c = this.children; _b < _c.length; _b++) {
  86805. var child = _c[_b];
  86806. child.scale(x, y, z, scaleChildren);
  86807. }
  86808. }
  86809. };
  86810. /**
  86811. * Set the bone scaling in local space
  86812. * @param scale defines the scaling vector
  86813. */
  86814. Bone.prototype.setScale = function (scale) {
  86815. this._decompose();
  86816. this._localScaling.copyFrom(scale);
  86817. this._markAsDirtyAndCompose();
  86818. };
  86819. /**
  86820. * Gets the current scaling in local space
  86821. * @returns the current scaling vector
  86822. */
  86823. Bone.prototype.getScale = function () {
  86824. this._decompose();
  86825. return this._localScaling;
  86826. };
  86827. /**
  86828. * Gets the current scaling in local space and stores it in a target vector
  86829. * @param result defines the target vector
  86830. */
  86831. Bone.prototype.getScaleToRef = function (result) {
  86832. this._decompose();
  86833. result.copyFrom(this._localScaling);
  86834. };
  86835. /**
  86836. * Set the yaw, pitch, and roll of the bone in local or world space
  86837. * @param yaw The rotation of the bone on the y axis
  86838. * @param pitch The rotation of the bone on the x axis
  86839. * @param roll The rotation of the bone on the z axis
  86840. * @param space The space that the axes of rotation are in
  86841. * @param mesh The mesh that this bone is attached to. This is only used in world space
  86842. */
  86843. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  86844. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  86845. if (space === BABYLON.Space.LOCAL) {
  86846. var quat = Bone._tmpQuat;
  86847. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, quat);
  86848. this.setRotationQuaternion(quat, space, mesh);
  86849. return;
  86850. }
  86851. var rotMatInv = Bone._tmpMats[0];
  86852. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  86853. return;
  86854. }
  86855. var rotMat = Bone._tmpMats[1];
  86856. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  86857. rotMatInv.multiplyToRef(rotMat, rotMat);
  86858. this._rotateWithMatrix(rotMat, space, mesh);
  86859. };
  86860. /**
  86861. * Add a rotation to the bone on an axis in local or world space
  86862. * @param axis The axis to rotate the bone on
  86863. * @param amount The amount to rotate the bone
  86864. * @param space The space that the axis is in
  86865. * @param mesh The mesh that this bone is attached to. This is only used in world space
  86866. */
  86867. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  86868. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  86869. var rmat = Bone._tmpMats[0];
  86870. rmat.m[12] = 0;
  86871. rmat.m[13] = 0;
  86872. rmat.m[14] = 0;
  86873. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  86874. this._rotateWithMatrix(rmat, space, mesh);
  86875. };
  86876. /**
  86877. * Set the rotation of the bone to a particular axis angle in local or world space
  86878. * @param axis The axis to rotate the bone on
  86879. * @param angle The angle that the bone should be rotated to
  86880. * @param space The space that the axis is in
  86881. * @param mesh The mesh that this bone is attached to. This is only used in world space
  86882. */
  86883. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  86884. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  86885. if (space === BABYLON.Space.LOCAL) {
  86886. var quat = Bone._tmpQuat;
  86887. BABYLON.Quaternion.RotationAxisToRef(axis, angle, quat);
  86888. this.setRotationQuaternion(quat, space, mesh);
  86889. return;
  86890. }
  86891. var rotMatInv = Bone._tmpMats[0];
  86892. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  86893. return;
  86894. }
  86895. var rotMat = Bone._tmpMats[1];
  86896. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  86897. rotMatInv.multiplyToRef(rotMat, rotMat);
  86898. this._rotateWithMatrix(rotMat, space, mesh);
  86899. };
  86900. /**
  86901. * Set the euler rotation of the bone in local of world space
  86902. * @param rotation The euler rotation that the bone should be set to
  86903. * @param space The space that the rotation is in
  86904. * @param mesh The mesh that this bone is attached to. This is only used in world space
  86905. */
  86906. Bone.prototype.setRotation = function (rotation, space, mesh) {
  86907. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  86908. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  86909. };
  86910. /**
  86911. * Set the quaternion rotation of the bone in local of world space
  86912. * @param quat The quaternion rotation that the bone should be set to
  86913. * @param space The space that the rotation is in
  86914. * @param mesh The mesh that this bone is attached to. This is only used in world space
  86915. */
  86916. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  86917. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  86918. if (space === BABYLON.Space.LOCAL) {
  86919. this._decompose();
  86920. this._localRotation.copyFrom(quat);
  86921. this._markAsDirtyAndCompose();
  86922. return;
  86923. }
  86924. var rotMatInv = Bone._tmpMats[0];
  86925. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  86926. return;
  86927. }
  86928. var rotMat = Bone._tmpMats[1];
  86929. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  86930. rotMatInv.multiplyToRef(rotMat, rotMat);
  86931. this._rotateWithMatrix(rotMat, space, mesh);
  86932. };
  86933. /**
  86934. * Set the rotation matrix of the bone in local of world space
  86935. * @param rotMat The rotation matrix that the bone should be set to
  86936. * @param space The space that the rotation is in
  86937. * @param mesh The mesh that this bone is attached to. This is only used in world space
  86938. */
  86939. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  86940. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  86941. if (space === BABYLON.Space.LOCAL) {
  86942. var quat = Bone._tmpQuat;
  86943. BABYLON.Quaternion.FromRotationMatrixToRef(rotMat, quat);
  86944. this.setRotationQuaternion(quat, space, mesh);
  86945. return;
  86946. }
  86947. var rotMatInv = Bone._tmpMats[0];
  86948. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  86949. return;
  86950. }
  86951. var rotMat2 = Bone._tmpMats[1];
  86952. rotMat2.copyFrom(rotMat);
  86953. rotMatInv.multiplyToRef(rotMat, rotMat2);
  86954. this._rotateWithMatrix(rotMat2, space, mesh);
  86955. };
  86956. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  86957. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  86958. var lmat = this.getLocalMatrix();
  86959. var lx = lmat.m[12];
  86960. var ly = lmat.m[13];
  86961. var lz = lmat.m[14];
  86962. var parent = this.getParent();
  86963. var parentScale = Bone._tmpMats[3];
  86964. var parentScaleInv = Bone._tmpMats[4];
  86965. if (parent && space == BABYLON.Space.WORLD) {
  86966. if (mesh) {
  86967. parentScale.copyFrom(mesh.getWorldMatrix());
  86968. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  86969. }
  86970. else {
  86971. parentScale.copyFrom(parent.getAbsoluteTransform());
  86972. }
  86973. parentScaleInv.copyFrom(parentScale);
  86974. parentScaleInv.invert();
  86975. lmat.multiplyToRef(parentScale, lmat);
  86976. lmat.multiplyToRef(rmat, lmat);
  86977. lmat.multiplyToRef(parentScaleInv, lmat);
  86978. }
  86979. else {
  86980. if (space == BABYLON.Space.WORLD && mesh) {
  86981. parentScale.copyFrom(mesh.getWorldMatrix());
  86982. parentScaleInv.copyFrom(parentScale);
  86983. parentScaleInv.invert();
  86984. lmat.multiplyToRef(parentScale, lmat);
  86985. lmat.multiplyToRef(rmat, lmat);
  86986. lmat.multiplyToRef(parentScaleInv, lmat);
  86987. }
  86988. else {
  86989. lmat.multiplyToRef(rmat, lmat);
  86990. }
  86991. }
  86992. lmat.m[12] = lx;
  86993. lmat.m[13] = ly;
  86994. lmat.m[14] = lz;
  86995. this.computeAbsoluteTransforms();
  86996. this._markAsDirtyAndDecompose();
  86997. };
  86998. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, mesh) {
  86999. var scaleMatrix = Bone._tmpMats[2];
  87000. rotMatInv.copyFrom(this.getAbsoluteTransform());
  87001. if (mesh) {
  87002. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  87003. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, scaleMatrix);
  87004. }
  87005. rotMatInv.invert();
  87006. if (isNaN(rotMatInv.m[0])) {
  87007. // Matrix failed to invert.
  87008. // This can happen if scale is zero for example.
  87009. return false;
  87010. }
  87011. scaleMatrix.m[0] *= this._scalingDeterminant;
  87012. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  87013. return true;
  87014. };
  87015. /**
  87016. * Get the position of the bone in local or world space
  87017. * @param space The space that the returned position is in
  87018. * @param mesh The mesh that this bone is attached to. This is only used in world space
  87019. * @returns The position of the bone
  87020. */
  87021. Bone.prototype.getPosition = function (space, mesh) {
  87022. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  87023. if (mesh === void 0) { mesh = null; }
  87024. var pos = BABYLON.Vector3.Zero();
  87025. this.getPositionToRef(space, mesh, pos);
  87026. return pos;
  87027. };
  87028. /**
  87029. * Copy the position of the bone to a vector3 in local or world space
  87030. * @param space The space that the returned position is in
  87031. * @param mesh The mesh that this bone is attached to. This is only used in world space
  87032. * @param result The vector3 to copy the position to
  87033. */
  87034. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  87035. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  87036. if (space == BABYLON.Space.LOCAL) {
  87037. var lm = this.getLocalMatrix();
  87038. result.x = lm.m[12];
  87039. result.y = lm.m[13];
  87040. result.z = lm.m[14];
  87041. }
  87042. else {
  87043. var wm = null;
  87044. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  87045. if (mesh) {
  87046. wm = mesh.getWorldMatrix();
  87047. }
  87048. this._skeleton.computeAbsoluteTransforms();
  87049. var tmat = Bone._tmpMats[0];
  87050. if (mesh && wm) {
  87051. tmat.copyFrom(this.getAbsoluteTransform());
  87052. tmat.multiplyToRef(wm, tmat);
  87053. }
  87054. else {
  87055. tmat = this.getAbsoluteTransform();
  87056. }
  87057. result.x = tmat.m[12];
  87058. result.y = tmat.m[13];
  87059. result.z = tmat.m[14];
  87060. }
  87061. };
  87062. /**
  87063. * Get the absolute position of the bone (world space)
  87064. * @param mesh The mesh that this bone is attached to
  87065. * @returns The absolute position of the bone
  87066. */
  87067. Bone.prototype.getAbsolutePosition = function (mesh) {
  87068. if (mesh === void 0) { mesh = null; }
  87069. var pos = BABYLON.Vector3.Zero();
  87070. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  87071. return pos;
  87072. };
  87073. /**
  87074. * Copy the absolute position of the bone (world space) to the result param
  87075. * @param mesh The mesh that this bone is attached to
  87076. * @param result The vector3 to copy the absolute position to
  87077. */
  87078. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  87079. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  87080. };
  87081. /**
  87082. * Compute the absolute transforms of this bone and its children
  87083. */
  87084. Bone.prototype.computeAbsoluteTransforms = function () {
  87085. this._compose();
  87086. if (this._parent) {
  87087. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  87088. }
  87089. else {
  87090. this._absoluteTransform.copyFrom(this._localMatrix);
  87091. var poseMatrix = this._skeleton.getPoseMatrix();
  87092. if (poseMatrix) {
  87093. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  87094. }
  87095. }
  87096. var children = this.children;
  87097. var len = children.length;
  87098. for (var i = 0; i < len; i++) {
  87099. children[i].computeAbsoluteTransforms();
  87100. }
  87101. };
  87102. /**
  87103. * Get the world direction from an axis that is in the local space of the bone
  87104. * @param localAxis The local direction that is used to compute the world direction
  87105. * @param mesh The mesh that this bone is attached to
  87106. * @returns The world direction
  87107. */
  87108. Bone.prototype.getDirection = function (localAxis, mesh) {
  87109. if (mesh === void 0) { mesh = null; }
  87110. var result = BABYLON.Vector3.Zero();
  87111. this.getDirectionToRef(localAxis, mesh, result);
  87112. return result;
  87113. };
  87114. /**
  87115. * Copy the world direction to a vector3 from an axis that is in the local space of the bone
  87116. * @param localAxis The local direction that is used to compute the world direction
  87117. * @param mesh The mesh that this bone is attached to
  87118. * @param result The vector3 that the world direction will be copied to
  87119. */
  87120. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  87121. if (mesh === void 0) { mesh = null; }
  87122. var wm = null;
  87123. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  87124. if (mesh) {
  87125. wm = mesh.getWorldMatrix();
  87126. }
  87127. this._skeleton.computeAbsoluteTransforms();
  87128. var mat = Bone._tmpMats[0];
  87129. mat.copyFrom(this.getAbsoluteTransform());
  87130. if (mesh && wm) {
  87131. mat.multiplyToRef(wm, mat);
  87132. }
  87133. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  87134. result.normalize();
  87135. };
  87136. /**
  87137. * Get the euler rotation of the bone in local or world space
  87138. * @param space The space that the rotation should be in
  87139. * @param mesh The mesh that this bone is attached to. This is only used in world space
  87140. * @returns The euler rotation
  87141. */
  87142. Bone.prototype.getRotation = function (space, mesh) {
  87143. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  87144. if (mesh === void 0) { mesh = null; }
  87145. var result = BABYLON.Vector3.Zero();
  87146. this.getRotationToRef(space, mesh, result);
  87147. return result;
  87148. };
  87149. /**
  87150. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space
  87151. * @param space The space that the rotation should be in
  87152. * @param mesh The mesh that this bone is attached to. This is only used in world space
  87153. * @param result The vector3 that the rotation should be copied to
  87154. */
  87155. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  87156. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  87157. if (mesh === void 0) { mesh = null; }
  87158. var quat = Bone._tmpQuat;
  87159. this.getRotationQuaternionToRef(space, mesh, quat);
  87160. quat.toEulerAnglesToRef(result);
  87161. };
  87162. /**
  87163. * Get the quaternion rotation of the bone in either local or world space
  87164. * @param space The space that the rotation should be in
  87165. * @param mesh The mesh that this bone is attached to. This is only used in world space
  87166. * @returns The quaternion rotation
  87167. */
  87168. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  87169. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  87170. if (mesh === void 0) { mesh = null; }
  87171. var result = BABYLON.Quaternion.Identity();
  87172. this.getRotationQuaternionToRef(space, mesh, result);
  87173. return result;
  87174. };
  87175. /**
  87176. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space
  87177. * @param space The space that the rotation should be in
  87178. * @param mesh The mesh that this bone is attached to. This is only used in world space
  87179. * @param result The quaternion that the rotation should be copied to
  87180. */
  87181. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  87182. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  87183. if (mesh === void 0) { mesh = null; }
  87184. if (space == BABYLON.Space.LOCAL) {
  87185. this._decompose();
  87186. result.copyFrom(this._localRotation);
  87187. }
  87188. else {
  87189. var mat = Bone._tmpMats[0];
  87190. var amat = this.getAbsoluteTransform();
  87191. if (mesh) {
  87192. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  87193. }
  87194. else {
  87195. mat.copyFrom(amat);
  87196. }
  87197. mat.m[0] *= this._scalingDeterminant;
  87198. mat.m[1] *= this._scalingDeterminant;
  87199. mat.m[2] *= this._scalingDeterminant;
  87200. mat.decompose(undefined, result, undefined);
  87201. }
  87202. };
  87203. /**
  87204. * Get the rotation matrix of the bone in local or world space
  87205. * @param space The space that the rotation should be in
  87206. * @param mesh The mesh that this bone is attached to. This is only used in world space
  87207. * @returns The rotation matrix
  87208. */
  87209. Bone.prototype.getRotationMatrix = function (space, mesh) {
  87210. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  87211. var result = BABYLON.Matrix.Identity();
  87212. this.getRotationMatrixToRef(space, mesh, result);
  87213. return result;
  87214. };
  87215. /**
  87216. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space
  87217. * @param space The space that the rotation should be in
  87218. * @param mesh The mesh that this bone is attached to. This is only used in world space
  87219. * @param result The quaternion that the rotation should be copied to
  87220. */
  87221. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  87222. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  87223. if (space == BABYLON.Space.LOCAL) {
  87224. this.getLocalMatrix().getRotationMatrixToRef(result);
  87225. }
  87226. else {
  87227. var mat = Bone._tmpMats[0];
  87228. var amat = this.getAbsoluteTransform();
  87229. if (mesh) {
  87230. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  87231. }
  87232. else {
  87233. mat.copyFrom(amat);
  87234. }
  87235. mat.m[0] *= this._scalingDeterminant;
  87236. mat.m[1] *= this._scalingDeterminant;
  87237. mat.m[2] *= this._scalingDeterminant;
  87238. mat.getRotationMatrixToRef(result);
  87239. }
  87240. };
  87241. /**
  87242. * Get the world position of a point that is in the local space of the bone
  87243. * @param position The local position
  87244. * @param mesh The mesh that this bone is attached to
  87245. * @returns The world position
  87246. */
  87247. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  87248. if (mesh === void 0) { mesh = null; }
  87249. var result = BABYLON.Vector3.Zero();
  87250. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  87251. return result;
  87252. };
  87253. /**
  87254. * Get the world position of a point that is in the local space of the bone and copy it to the result param
  87255. * @param position The local position
  87256. * @param mesh The mesh that this bone is attached to
  87257. * @param result The vector3 that the world position should be copied to
  87258. */
  87259. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  87260. if (mesh === void 0) { mesh = null; }
  87261. var wm = null;
  87262. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  87263. if (mesh) {
  87264. wm = mesh.getWorldMatrix();
  87265. }
  87266. this._skeleton.computeAbsoluteTransforms();
  87267. var tmat = Bone._tmpMats[0];
  87268. if (mesh && wm) {
  87269. tmat.copyFrom(this.getAbsoluteTransform());
  87270. tmat.multiplyToRef(wm, tmat);
  87271. }
  87272. else {
  87273. tmat = this.getAbsoluteTransform();
  87274. }
  87275. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  87276. };
  87277. /**
  87278. * Get the local position of a point that is in world space
  87279. * @param position The world position
  87280. * @param mesh The mesh that this bone is attached to
  87281. * @returns The local position
  87282. */
  87283. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  87284. if (mesh === void 0) { mesh = null; }
  87285. var result = BABYLON.Vector3.Zero();
  87286. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  87287. return result;
  87288. };
  87289. /**
  87290. * Get the local position of a point that is in world space and copy it to the result param
  87291. * @param position The world position
  87292. * @param mesh The mesh that this bone is attached to
  87293. * @param result The vector3 that the local position should be copied to
  87294. */
  87295. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  87296. if (mesh === void 0) { mesh = null; }
  87297. var wm = null;
  87298. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  87299. if (mesh) {
  87300. wm = mesh.getWorldMatrix();
  87301. }
  87302. this._skeleton.computeAbsoluteTransforms();
  87303. var tmat = Bone._tmpMats[0];
  87304. tmat.copyFrom(this.getAbsoluteTransform());
  87305. if (mesh && wm) {
  87306. tmat.multiplyToRef(wm, tmat);
  87307. }
  87308. tmat.invert();
  87309. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  87310. };
  87311. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  87312. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  87313. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  87314. return Bone;
  87315. }(BABYLON.Node));
  87316. BABYLON.Bone = Bone;
  87317. })(BABYLON || (BABYLON = {}));
  87318. //# sourceMappingURL=babylon.bone.js.map
  87319. var BABYLON;
  87320. (function (BABYLON) {
  87321. /**
  87322. * Class used to apply inverse kinematics to bones
  87323. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#boneikcontroller
  87324. */
  87325. var BoneIKController = /** @class */ (function () {
  87326. /**
  87327. * Creates a new BoneIKController
  87328. * @param mesh defines the mesh to control
  87329. * @param bone defines the bone to control
  87330. * @param options defines options to set up the controller
  87331. */
  87332. function BoneIKController(mesh, bone, options) {
  87333. /**
  87334. * Gets or sets the target position
  87335. */
  87336. this.targetPosition = BABYLON.Vector3.Zero();
  87337. /**
  87338. * Gets or sets the pole target position
  87339. */
  87340. this.poleTargetPosition = BABYLON.Vector3.Zero();
  87341. /**
  87342. * Gets or sets the pole target local offset
  87343. */
  87344. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  87345. /**
  87346. * Gets or sets the pole angle
  87347. */
  87348. this.poleAngle = 0;
  87349. /**
  87350. * 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)
  87351. */
  87352. this.slerpAmount = 1;
  87353. this._bone1Quat = BABYLON.Quaternion.Identity();
  87354. this._bone1Mat = BABYLON.Matrix.Identity();
  87355. this._bone2Ang = Math.PI;
  87356. this._maxAngle = Math.PI;
  87357. this._rightHandedSystem = false;
  87358. this._bendAxis = BABYLON.Vector3.Right();
  87359. this._slerping = false;
  87360. this._adjustRoll = 0;
  87361. this._bone2 = bone;
  87362. this._bone1 = bone.getParent();
  87363. if (!this._bone1) {
  87364. return;
  87365. }
  87366. this.mesh = mesh;
  87367. var bonePos = bone.getPosition();
  87368. if (bone.getAbsoluteTransform().determinant() > 0) {
  87369. this._rightHandedSystem = true;
  87370. this._bendAxis.x = 0;
  87371. this._bendAxis.y = 0;
  87372. this._bendAxis.z = -1;
  87373. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  87374. this._adjustRoll = Math.PI * .5;
  87375. this._bendAxis.z = 1;
  87376. }
  87377. }
  87378. if (this._bone1.length) {
  87379. var boneScale1 = this._bone1.getScale();
  87380. var boneScale2 = this._bone2.getScale();
  87381. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  87382. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  87383. }
  87384. else if (this._bone1.children[0]) {
  87385. mesh.computeWorldMatrix(true);
  87386. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  87387. var pos2 = this._bone2.getAbsolutePosition(mesh);
  87388. var pos3 = this._bone1.getAbsolutePosition(mesh);
  87389. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  87390. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  87391. }
  87392. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  87393. this.maxAngle = Math.PI;
  87394. if (options) {
  87395. if (options.targetMesh) {
  87396. this.targetMesh = options.targetMesh;
  87397. this.targetMesh.computeWorldMatrix(true);
  87398. }
  87399. if (options.poleTargetMesh) {
  87400. this.poleTargetMesh = options.poleTargetMesh;
  87401. this.poleTargetMesh.computeWorldMatrix(true);
  87402. }
  87403. else if (options.poleTargetBone) {
  87404. this.poleTargetBone = options.poleTargetBone;
  87405. }
  87406. else if (this._bone1.getParent()) {
  87407. this.poleTargetBone = this._bone1.getParent();
  87408. }
  87409. if (options.poleTargetLocalOffset) {
  87410. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  87411. }
  87412. if (options.poleAngle) {
  87413. this.poleAngle = options.poleAngle;
  87414. }
  87415. if (options.bendAxis) {
  87416. this._bendAxis.copyFrom(options.bendAxis);
  87417. }
  87418. if (options.maxAngle) {
  87419. this.maxAngle = options.maxAngle;
  87420. }
  87421. if (options.slerpAmount) {
  87422. this.slerpAmount = options.slerpAmount;
  87423. }
  87424. }
  87425. }
  87426. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  87427. /**
  87428. * Gets or sets maximum allowed angle
  87429. */
  87430. get: function () {
  87431. return this._maxAngle;
  87432. },
  87433. set: function (value) {
  87434. this._setMaxAngle(value);
  87435. },
  87436. enumerable: true,
  87437. configurable: true
  87438. });
  87439. BoneIKController.prototype._setMaxAngle = function (ang) {
  87440. if (ang < 0) {
  87441. ang = 0;
  87442. }
  87443. if (ang > Math.PI || ang == undefined) {
  87444. ang = Math.PI;
  87445. }
  87446. this._maxAngle = ang;
  87447. var a = this._bone1Length;
  87448. var b = this._bone2Length;
  87449. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  87450. };
  87451. /**
  87452. * Force the controller to update the bones
  87453. */
  87454. BoneIKController.prototype.update = function () {
  87455. var bone1 = this._bone1;
  87456. if (!bone1) {
  87457. return;
  87458. }
  87459. var target = this.targetPosition;
  87460. var poleTarget = this.poleTargetPosition;
  87461. var mat1 = BoneIKController._tmpMats[0];
  87462. var mat2 = BoneIKController._tmpMats[1];
  87463. if (this.targetMesh) {
  87464. target.copyFrom(this.targetMesh.getAbsolutePosition());
  87465. }
  87466. if (this.poleTargetBone) {
  87467. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  87468. }
  87469. else if (this.poleTargetMesh) {
  87470. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  87471. }
  87472. var bonePos = BoneIKController._tmpVecs[0];
  87473. var zaxis = BoneIKController._tmpVecs[1];
  87474. var xaxis = BoneIKController._tmpVecs[2];
  87475. var yaxis = BoneIKController._tmpVecs[3];
  87476. var upAxis = BoneIKController._tmpVecs[4];
  87477. var _tmpQuat = BoneIKController._tmpQuat;
  87478. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  87479. poleTarget.subtractToRef(bonePos, upAxis);
  87480. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  87481. upAxis.y = 1;
  87482. }
  87483. else {
  87484. upAxis.normalize();
  87485. }
  87486. target.subtractToRef(bonePos, yaxis);
  87487. yaxis.normalize();
  87488. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  87489. zaxis.normalize();
  87490. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  87491. xaxis.normalize();
  87492. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  87493. var a = this._bone1Length;
  87494. var b = this._bone2Length;
  87495. var c = BABYLON.Vector3.Distance(bonePos, target);
  87496. if (this._maxReach > 0) {
  87497. c = Math.min(this._maxReach, c);
  87498. }
  87499. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  87500. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  87501. if (acosa > 1) {
  87502. acosa = 1;
  87503. }
  87504. if (acosb > 1) {
  87505. acosb = 1;
  87506. }
  87507. if (acosa < -1) {
  87508. acosa = -1;
  87509. }
  87510. if (acosb < -1) {
  87511. acosb = -1;
  87512. }
  87513. var angA = Math.acos(acosa);
  87514. var angB = Math.acos(acosb);
  87515. var angC = -angA - angB;
  87516. if (this._rightHandedSystem) {
  87517. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  87518. mat2.multiplyToRef(mat1, mat1);
  87519. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  87520. mat2.multiplyToRef(mat1, mat1);
  87521. }
  87522. else {
  87523. var _tmpVec = BoneIKController._tmpVecs[5];
  87524. _tmpVec.copyFrom(this._bendAxis);
  87525. _tmpVec.x *= -1;
  87526. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  87527. mat2.multiplyToRef(mat1, mat1);
  87528. }
  87529. if (this.poleAngle) {
  87530. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  87531. mat1.multiplyToRef(mat2, mat1);
  87532. }
  87533. if (this._bone1) {
  87534. if (this.slerpAmount < 1) {
  87535. if (!this._slerping) {
  87536. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  87537. }
  87538. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  87539. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  87540. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  87541. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  87542. this._slerping = true;
  87543. }
  87544. else {
  87545. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  87546. this._bone1Mat.copyFrom(mat1);
  87547. this._slerping = false;
  87548. }
  87549. }
  87550. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  87551. this._bone2Ang = angC;
  87552. };
  87553. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  87554. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  87555. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  87556. return BoneIKController;
  87557. }());
  87558. BABYLON.BoneIKController = BoneIKController;
  87559. })(BABYLON || (BABYLON = {}));
  87560. //# sourceMappingURL=babylon.boneIKController.js.map
  87561. var BABYLON;
  87562. (function (BABYLON) {
  87563. /**
  87564. * Class used to make a bone look toward a point in space
  87565. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#bonelookcontroller
  87566. */
  87567. var BoneLookController = /** @class */ (function () {
  87568. /**
  87569. * Create a BoneLookController
  87570. * @param mesh the mesh that the bone belongs to
  87571. * @param bone the bone that will be looking to the target
  87572. * @param target the target Vector3 to look at
  87573. * @param settings optional settings:
  87574. * * maxYaw: the maximum angle the bone will yaw to
  87575. * * minYaw: the minimum angle the bone will yaw to
  87576. * * maxPitch: the maximum angle the bone will pitch to
  87577. * * minPitch: the minimum angle the bone will yaw to
  87578. * * slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  87579. * * upAxis: the up axis of the coordinate system
  87580. * * upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  87581. * * yawAxis: set yawAxis if the bone does not yaw on the y axis
  87582. * * pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  87583. * * adjustYaw: used to make an adjustment to the yaw of the bone
  87584. * * adjustPitch: used to make an adjustment to the pitch of the bone
  87585. * * adjustRoll: used to make an adjustment to the roll of the bone
  87586. **/
  87587. function BoneLookController(mesh, bone, target, options) {
  87588. /**
  87589. * The up axis of the coordinate system that is used when the bone is rotated
  87590. */
  87591. this.upAxis = BABYLON.Vector3.Up();
  87592. /**
  87593. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD
  87594. */
  87595. this.upAxisSpace = BABYLON.Space.LOCAL;
  87596. /**
  87597. * Used to make an adjustment to the yaw of the bone
  87598. */
  87599. this.adjustYaw = 0;
  87600. /**
  87601. * Used to make an adjustment to the pitch of the bone
  87602. */
  87603. this.adjustPitch = 0;
  87604. /**
  87605. * Used to make an adjustment to the roll of the bone
  87606. */
  87607. this.adjustRoll = 0;
  87608. /**
  87609. * 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)
  87610. */
  87611. this.slerpAmount = 1;
  87612. this._boneQuat = BABYLON.Quaternion.Identity();
  87613. this._slerping = false;
  87614. this._firstFrameSkipped = false;
  87615. this._fowardAxis = BABYLON.Vector3.Forward();
  87616. this.mesh = mesh;
  87617. this.bone = bone;
  87618. this.target = target;
  87619. if (options) {
  87620. if (options.adjustYaw) {
  87621. this.adjustYaw = options.adjustYaw;
  87622. }
  87623. if (options.adjustPitch) {
  87624. this.adjustPitch = options.adjustPitch;
  87625. }
  87626. if (options.adjustRoll) {
  87627. this.adjustRoll = options.adjustRoll;
  87628. }
  87629. if (options.maxYaw != null) {
  87630. this.maxYaw = options.maxYaw;
  87631. }
  87632. else {
  87633. this.maxYaw = Math.PI;
  87634. }
  87635. if (options.minYaw != null) {
  87636. this.minYaw = options.minYaw;
  87637. }
  87638. else {
  87639. this.minYaw = -Math.PI;
  87640. }
  87641. if (options.maxPitch != null) {
  87642. this.maxPitch = options.maxPitch;
  87643. }
  87644. else {
  87645. this.maxPitch = Math.PI;
  87646. }
  87647. if (options.minPitch != null) {
  87648. this.minPitch = options.minPitch;
  87649. }
  87650. else {
  87651. this.minPitch = -Math.PI;
  87652. }
  87653. if (options.slerpAmount != null) {
  87654. this.slerpAmount = options.slerpAmount;
  87655. }
  87656. if (options.upAxis != null) {
  87657. this.upAxis = options.upAxis;
  87658. }
  87659. if (options.upAxisSpace != null) {
  87660. this.upAxisSpace = options.upAxisSpace;
  87661. }
  87662. if (options.yawAxis != null || options.pitchAxis != null) {
  87663. var newYawAxis = BABYLON.Axis.Y;
  87664. var newPitchAxis = BABYLON.Axis.X;
  87665. if (options.yawAxis != null) {
  87666. newYawAxis = options.yawAxis.clone();
  87667. newYawAxis.normalize();
  87668. }
  87669. if (options.pitchAxis != null) {
  87670. newPitchAxis = options.pitchAxis.clone();
  87671. newPitchAxis.normalize();
  87672. }
  87673. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  87674. this._transformYawPitch = BABYLON.Matrix.Identity();
  87675. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  87676. this._transformYawPitchInv = this._transformYawPitch.clone();
  87677. this._transformYawPitch.invert();
  87678. }
  87679. }
  87680. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  87681. this.upAxisSpace = BABYLON.Space.LOCAL;
  87682. }
  87683. }
  87684. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  87685. /**
  87686. * Gets or sets the minimum yaw angle that the bone can look to
  87687. */
  87688. get: function () {
  87689. return this._minYaw;
  87690. },
  87691. set: function (value) {
  87692. this._minYaw = value;
  87693. this._minYawSin = Math.sin(value);
  87694. this._minYawCos = Math.cos(value);
  87695. if (this._maxYaw != null) {
  87696. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  87697. this._yawRange = this._maxYaw - this._minYaw;
  87698. }
  87699. },
  87700. enumerable: true,
  87701. configurable: true
  87702. });
  87703. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  87704. /**
  87705. * Gets or sets the maximum yaw angle that the bone can look to
  87706. */
  87707. get: function () {
  87708. return this._maxYaw;
  87709. },
  87710. set: function (value) {
  87711. this._maxYaw = value;
  87712. this._maxYawSin = Math.sin(value);
  87713. this._maxYawCos = Math.cos(value);
  87714. if (this._minYaw != null) {
  87715. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  87716. this._yawRange = this._maxYaw - this._minYaw;
  87717. }
  87718. },
  87719. enumerable: true,
  87720. configurable: true
  87721. });
  87722. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  87723. /**
  87724. * Gets or sets the minimum pitch angle that the bone can look to
  87725. */
  87726. get: function () {
  87727. return this._minPitch;
  87728. },
  87729. set: function (value) {
  87730. this._minPitch = value;
  87731. this._minPitchTan = Math.tan(value);
  87732. },
  87733. enumerable: true,
  87734. configurable: true
  87735. });
  87736. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  87737. /**
  87738. * Gets or sets the maximum pitch angle that the bone can look to
  87739. */
  87740. get: function () {
  87741. return this._maxPitch;
  87742. },
  87743. set: function (value) {
  87744. this._maxPitch = value;
  87745. this._maxPitchTan = Math.tan(value);
  87746. },
  87747. enumerable: true,
  87748. configurable: true
  87749. });
  87750. /**
  87751. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender())
  87752. */
  87753. BoneLookController.prototype.update = function () {
  87754. //skip the first frame when slerping so that the mesh rotation is correct
  87755. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  87756. this._firstFrameSkipped = true;
  87757. return;
  87758. }
  87759. var bone = this.bone;
  87760. var bonePos = BoneLookController._tmpVecs[0];
  87761. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  87762. var target = this.target;
  87763. var _tmpMat1 = BoneLookController._tmpMats[0];
  87764. var _tmpMat2 = BoneLookController._tmpMats[1];
  87765. var mesh = this.mesh;
  87766. var parentBone = bone.getParent();
  87767. var upAxis = BoneLookController._tmpVecs[1];
  87768. upAxis.copyFrom(this.upAxis);
  87769. if (this.upAxisSpace == BABYLON.Space.BONE && parentBone) {
  87770. if (this._transformYawPitch) {
  87771. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  87772. }
  87773. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  87774. }
  87775. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  87776. mesh.getDirectionToRef(upAxis, upAxis);
  87777. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  87778. upAxis.normalize();
  87779. }
  87780. }
  87781. var checkYaw = false;
  87782. var checkPitch = false;
  87783. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  87784. checkYaw = true;
  87785. }
  87786. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  87787. checkPitch = true;
  87788. }
  87789. if (checkYaw || checkPitch) {
  87790. var spaceMat = BoneLookController._tmpMats[2];
  87791. var spaceMatInv = BoneLookController._tmpMats[3];
  87792. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1 && parentBone) {
  87793. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  87794. }
  87795. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  87796. spaceMat.copyFrom(mesh.getWorldMatrix());
  87797. }
  87798. else {
  87799. var forwardAxis = BoneLookController._tmpVecs[2];
  87800. forwardAxis.copyFrom(this._fowardAxis);
  87801. if (this._transformYawPitch) {
  87802. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  87803. }
  87804. if (parentBone) {
  87805. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  87806. }
  87807. else {
  87808. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  87809. }
  87810. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  87811. rightAxis.normalize();
  87812. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  87813. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  87814. }
  87815. spaceMat.invertToRef(spaceMatInv);
  87816. var xzlen = null;
  87817. if (checkPitch) {
  87818. var localTarget = BoneLookController._tmpVecs[3];
  87819. target.subtractToRef(bonePos, localTarget);
  87820. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  87821. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  87822. var pitch = Math.atan2(localTarget.y, xzlen);
  87823. var newPitch = pitch;
  87824. if (pitch > this._maxPitch) {
  87825. localTarget.y = this._maxPitchTan * xzlen;
  87826. newPitch = this._maxPitch;
  87827. }
  87828. else if (pitch < this._minPitch) {
  87829. localTarget.y = this._minPitchTan * xzlen;
  87830. newPitch = this._minPitch;
  87831. }
  87832. if (pitch != newPitch) {
  87833. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  87834. localTarget.addInPlace(bonePos);
  87835. target = localTarget;
  87836. }
  87837. }
  87838. if (checkYaw) {
  87839. var localTarget = BoneLookController._tmpVecs[4];
  87840. target.subtractToRef(bonePos, localTarget);
  87841. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  87842. var yaw = Math.atan2(localTarget.x, localTarget.z);
  87843. var newYaw = yaw;
  87844. if (yaw > this._maxYaw || yaw < this._minYaw) {
  87845. if (xzlen == null) {
  87846. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  87847. }
  87848. if (this._yawRange > Math.PI) {
  87849. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  87850. localTarget.z = this._maxYawCos * xzlen;
  87851. localTarget.x = this._maxYawSin * xzlen;
  87852. newYaw = this._maxYaw;
  87853. }
  87854. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  87855. localTarget.z = this._minYawCos * xzlen;
  87856. localTarget.x = this._minYawSin * xzlen;
  87857. newYaw = this._minYaw;
  87858. }
  87859. }
  87860. else {
  87861. if (yaw > this._maxYaw) {
  87862. localTarget.z = this._maxYawCos * xzlen;
  87863. localTarget.x = this._maxYawSin * xzlen;
  87864. newYaw = this._maxYaw;
  87865. }
  87866. else if (yaw < this._minYaw) {
  87867. localTarget.z = this._minYawCos * xzlen;
  87868. localTarget.x = this._minYawSin * xzlen;
  87869. newYaw = this._minYaw;
  87870. }
  87871. }
  87872. }
  87873. if (this._slerping && this._yawRange > Math.PI) {
  87874. //are we going to be crossing into the min/max region?
  87875. var boneFwd = BoneLookController._tmpVecs[8];
  87876. boneFwd.copyFrom(BABYLON.Axis.Z);
  87877. if (this._transformYawPitch) {
  87878. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  87879. }
  87880. var boneRotMat = BoneLookController._tmpMats[4];
  87881. this._boneQuat.toRotationMatrix(boneRotMat);
  87882. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  87883. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  87884. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  87885. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  87886. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  87887. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  87888. if (angBtwTar > angBtwMidYaw) {
  87889. if (xzlen == null) {
  87890. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  87891. }
  87892. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  87893. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  87894. if (angBtwMin < angBtwMax) {
  87895. newYaw = boneYaw + Math.PI * .75;
  87896. localTarget.z = Math.cos(newYaw) * xzlen;
  87897. localTarget.x = Math.sin(newYaw) * xzlen;
  87898. }
  87899. else {
  87900. newYaw = boneYaw - Math.PI * .75;
  87901. localTarget.z = Math.cos(newYaw) * xzlen;
  87902. localTarget.x = Math.sin(newYaw) * xzlen;
  87903. }
  87904. }
  87905. }
  87906. if (yaw != newYaw) {
  87907. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  87908. localTarget.addInPlace(bonePos);
  87909. target = localTarget;
  87910. }
  87911. }
  87912. }
  87913. var zaxis = BoneLookController._tmpVecs[5];
  87914. var xaxis = BoneLookController._tmpVecs[6];
  87915. var yaxis = BoneLookController._tmpVecs[7];
  87916. var _tmpQuat = BoneLookController._tmpQuat;
  87917. target.subtractToRef(bonePos, zaxis);
  87918. zaxis.normalize();
  87919. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  87920. xaxis.normalize();
  87921. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  87922. yaxis.normalize();
  87923. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  87924. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  87925. return;
  87926. }
  87927. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  87928. return;
  87929. }
  87930. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  87931. return;
  87932. }
  87933. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  87934. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  87935. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  87936. }
  87937. if (this.slerpAmount < 1) {
  87938. if (!this._slerping) {
  87939. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  87940. }
  87941. if (this._transformYawPitch) {
  87942. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  87943. }
  87944. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  87945. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  87946. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  87947. this._slerping = true;
  87948. }
  87949. else {
  87950. if (this._transformYawPitch) {
  87951. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  87952. }
  87953. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  87954. this._slerping = false;
  87955. }
  87956. };
  87957. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  87958. var angDiff = ang2 - ang1;
  87959. angDiff %= Math.PI * 2;
  87960. if (angDiff > Math.PI) {
  87961. angDiff -= Math.PI * 2;
  87962. }
  87963. else if (angDiff < -Math.PI) {
  87964. angDiff += Math.PI * 2;
  87965. }
  87966. return angDiff;
  87967. };
  87968. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  87969. ang1 %= (2 * Math.PI);
  87970. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  87971. ang2 %= (2 * Math.PI);
  87972. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  87973. var ab = 0;
  87974. if (ang1 < ang2) {
  87975. ab = ang2 - ang1;
  87976. }
  87977. else {
  87978. ab = ang1 - ang2;
  87979. }
  87980. if (ab > Math.PI) {
  87981. ab = Math.PI * 2 - ab;
  87982. }
  87983. return ab;
  87984. };
  87985. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  87986. ang %= (2 * Math.PI);
  87987. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  87988. ang1 %= (2 * Math.PI);
  87989. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  87990. ang2 %= (2 * Math.PI);
  87991. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  87992. if (ang1 < ang2) {
  87993. if (ang > ang1 && ang < ang2) {
  87994. return true;
  87995. }
  87996. }
  87997. else {
  87998. if (ang > ang2 && ang < ang1) {
  87999. return true;
  88000. }
  88001. }
  88002. return false;
  88003. };
  88004. 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()];
  88005. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  88006. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  88007. return BoneLookController;
  88008. }());
  88009. BABYLON.BoneLookController = BoneLookController;
  88010. })(BABYLON || (BABYLON = {}));
  88011. //# sourceMappingURL=babylon.boneLookController.js.map
  88012. var BABYLON;
  88013. (function (BABYLON) {
  88014. /**
  88015. * Class used to handle skinning animations
  88016. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  88017. */
  88018. var Skeleton = /** @class */ (function () {
  88019. /**
  88020. * Creates a new skeleton
  88021. * @param name defines the skeleton name
  88022. * @param id defines the skeleton Id
  88023. * @param scene defines the hosting scene
  88024. */
  88025. function Skeleton(
  88026. /** defines the skeleton name */
  88027. name,
  88028. /** defines the skeleton Id */
  88029. id, scene) {
  88030. this.name = name;
  88031. this.id = id;
  88032. /**
  88033. * Gets the list of child bones
  88034. */
  88035. this.bones = new Array();
  88036. /**
  88037. * Gets a boolean indicating if the root matrix is provided by meshes or by the current skeleton (this is the default value)
  88038. */
  88039. this.needInitialSkinMatrix = false;
  88040. this._isDirty = true;
  88041. this._meshesWithPoseMatrix = new Array();
  88042. this._identity = BABYLON.Matrix.Identity();
  88043. this._ranges = {};
  88044. this._lastAbsoluteTransformsUpdateId = -1;
  88045. /**
  88046. * Specifies if the skeleton should be serialized
  88047. */
  88048. this.doNotSerialize = false;
  88049. this._animationPropertiesOverride = null;
  88050. // Events
  88051. /**
  88052. * An observable triggered before computing the skeleton's matrices
  88053. */
  88054. this.onBeforeComputeObservable = new BABYLON.Observable();
  88055. this.bones = [];
  88056. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  88057. scene.skeletons.push(this);
  88058. //make sure it will recalculate the matrix next time prepare is called.
  88059. this._isDirty = true;
  88060. }
  88061. Object.defineProperty(Skeleton.prototype, "animationPropertiesOverride", {
  88062. /**
  88063. * Gets or sets the animation properties override
  88064. */
  88065. get: function () {
  88066. if (!this._animationPropertiesOverride) {
  88067. return this._scene.animationPropertiesOverride;
  88068. }
  88069. return this._animationPropertiesOverride;
  88070. },
  88071. set: function (value) {
  88072. this._animationPropertiesOverride = value;
  88073. },
  88074. enumerable: true,
  88075. configurable: true
  88076. });
  88077. // Members
  88078. /**
  88079. * Gets the list of transform matrices to send to shaders (one matrix per bone)
  88080. * @param mesh defines the mesh to use to get the root matrix (if needInitialSkinMatrix === true)
  88081. * @returns a Float32Array containing matrices data
  88082. */
  88083. Skeleton.prototype.getTransformMatrices = function (mesh) {
  88084. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  88085. return mesh._bonesTransformMatrices;
  88086. }
  88087. if (!this._transformMatrices) {
  88088. this.prepare();
  88089. }
  88090. return this._transformMatrices;
  88091. };
  88092. /**
  88093. * Gets the current hosting scene
  88094. * @returns a scene object
  88095. */
  88096. Skeleton.prototype.getScene = function () {
  88097. return this._scene;
  88098. };
  88099. // Methods
  88100. /**
  88101. * Gets a string representing the current skeleton data
  88102. * @param fullDetails defines a boolean indicating if we want a verbose version
  88103. * @returns a string representing the current skeleton data
  88104. */
  88105. Skeleton.prototype.toString = function (fullDetails) {
  88106. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  88107. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  88108. if (fullDetails) {
  88109. ret += ", Ranges: {";
  88110. var first = true;
  88111. for (var name_1 in this._ranges) {
  88112. if (first) {
  88113. ret += ", ";
  88114. first = false;
  88115. }
  88116. ret += name_1;
  88117. }
  88118. ret += "}";
  88119. }
  88120. return ret;
  88121. };
  88122. /**
  88123. * Get bone's index searching by name
  88124. * @param name defines bone's name to search for
  88125. * @return the indice of the bone. Returns -1 if not found
  88126. */
  88127. Skeleton.prototype.getBoneIndexByName = function (name) {
  88128. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  88129. if (this.bones[boneIndex].name === name) {
  88130. return boneIndex;
  88131. }
  88132. }
  88133. return -1;
  88134. };
  88135. /**
  88136. * Creater a new animation range
  88137. * @param name defines the name of the range
  88138. * @param from defines the start key
  88139. * @param to defines the end key
  88140. */
  88141. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  88142. // check name not already in use
  88143. if (!this._ranges[name]) {
  88144. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  88145. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  88146. if (this.bones[i].animations[0]) {
  88147. this.bones[i].animations[0].createRange(name, from, to);
  88148. }
  88149. }
  88150. }
  88151. };
  88152. /**
  88153. * Delete a specific animation range
  88154. * @param name defines the name of the range
  88155. * @param deleteFrames defines if frames must be removed as well
  88156. */
  88157. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  88158. if (deleteFrames === void 0) { deleteFrames = true; }
  88159. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  88160. if (this.bones[i].animations[0]) {
  88161. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  88162. }
  88163. }
  88164. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  88165. };
  88166. /**
  88167. * Gets a specific animation range
  88168. * @param name defines the name of the range to look for
  88169. * @returns the requested animation range or null if not found
  88170. */
  88171. Skeleton.prototype.getAnimationRange = function (name) {
  88172. return this._ranges[name];
  88173. };
  88174. /**
  88175. * Gets the list of all animation ranges defined on this skeleton
  88176. * @returns an array
  88177. */
  88178. Skeleton.prototype.getAnimationRanges = function () {
  88179. var animationRanges = [];
  88180. var name;
  88181. var i = 0;
  88182. for (name in this._ranges) {
  88183. animationRanges[i] = this._ranges[name];
  88184. i++;
  88185. }
  88186. return animationRanges;
  88187. };
  88188. /**
  88189. * Copy animation range from a source skeleton.
  88190. * This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  88191. * @param source defines the source skeleton
  88192. * @param name defines the name of the range to copy
  88193. * @param rescaleAsRequired defines if rescaling must be applied if required
  88194. * @returns true if operation was successful
  88195. */
  88196. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  88197. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  88198. if (this._ranges[name] || !source.getAnimationRange(name)) {
  88199. return false;
  88200. }
  88201. var ret = true;
  88202. var frameOffset = this._getHighestAnimationFrame() + 1;
  88203. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  88204. var boneDict = {};
  88205. var sourceBones = source.bones;
  88206. var nBones;
  88207. var i;
  88208. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  88209. boneDict[sourceBones[i].name] = sourceBones[i];
  88210. }
  88211. if (this.bones.length !== sourceBones.length) {
  88212. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  88213. ret = false;
  88214. }
  88215. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  88216. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  88217. var boneName = this.bones[i].name;
  88218. var sourceBone = boneDict[boneName];
  88219. if (sourceBone) {
  88220. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  88221. }
  88222. else {
  88223. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  88224. ret = false;
  88225. }
  88226. }
  88227. // do not call createAnimationRange(), since it also is done to bones, which was already done
  88228. var range = source.getAnimationRange(name);
  88229. if (range) {
  88230. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  88231. }
  88232. return ret;
  88233. };
  88234. /**
  88235. * Forces the skeleton to go to rest pose
  88236. */
  88237. Skeleton.prototype.returnToRest = function () {
  88238. for (var index = 0; index < this.bones.length; index++) {
  88239. this.bones[index].returnToRest();
  88240. }
  88241. };
  88242. Skeleton.prototype._getHighestAnimationFrame = function () {
  88243. var ret = 0;
  88244. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  88245. if (this.bones[i].animations[0]) {
  88246. var highest = this.bones[i].animations[0].getHighestFrame();
  88247. if (ret < highest) {
  88248. ret = highest;
  88249. }
  88250. }
  88251. }
  88252. return ret;
  88253. };
  88254. /**
  88255. * Begin a specific animation range
  88256. * @param name defines the name of the range to start
  88257. * @param loop defines if looping must be turned on (false by default)
  88258. * @param speedRatio defines the speed ratio to apply (1 by default)
  88259. * @param onAnimationEnd defines a callback which will be called when animation will end
  88260. * @returns a new animatable
  88261. */
  88262. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  88263. var range = this.getAnimationRange(name);
  88264. if (!range) {
  88265. return null;
  88266. }
  88267. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  88268. };
  88269. /** @hidden */
  88270. Skeleton.prototype._markAsDirty = function () {
  88271. this._isDirty = true;
  88272. };
  88273. /** @hidden */
  88274. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  88275. this._meshesWithPoseMatrix.push(mesh);
  88276. };
  88277. /** @hidden */
  88278. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  88279. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  88280. if (index > -1) {
  88281. this._meshesWithPoseMatrix.splice(index, 1);
  88282. }
  88283. };
  88284. /** @hidden */
  88285. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  88286. this.onBeforeComputeObservable.notifyObservers(this);
  88287. for (var index = 0; index < this.bones.length; index++) {
  88288. var bone = this.bones[index];
  88289. var parentBone = bone.getParent();
  88290. if (parentBone) {
  88291. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  88292. }
  88293. else {
  88294. if (initialSkinMatrix) {
  88295. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  88296. }
  88297. else {
  88298. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  88299. }
  88300. }
  88301. if (bone._index !== -1) {
  88302. var mappedIndex = bone._index === null ? index : bone._index;
  88303. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  88304. }
  88305. }
  88306. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  88307. };
  88308. /**
  88309. * Build all resources required to render a skeleton
  88310. */
  88311. Skeleton.prototype.prepare = function () {
  88312. if (!this._isDirty) {
  88313. return;
  88314. }
  88315. if (this.needInitialSkinMatrix) {
  88316. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  88317. var mesh = this._meshesWithPoseMatrix[index];
  88318. var poseMatrix = mesh.getPoseMatrix();
  88319. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  88320. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  88321. }
  88322. if (this._synchronizedWithMesh !== mesh) {
  88323. this._synchronizedWithMesh = mesh;
  88324. // Prepare bones
  88325. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  88326. var bone = this.bones[boneIndex];
  88327. if (!bone.getParent()) {
  88328. var matrix = bone.getBaseMatrix();
  88329. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  88330. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  88331. }
  88332. }
  88333. }
  88334. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  88335. }
  88336. }
  88337. else {
  88338. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  88339. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  88340. }
  88341. this._computeTransformMatrices(this._transformMatrices, null);
  88342. }
  88343. this._isDirty = false;
  88344. this._scene._activeBones.addCount(this.bones.length, false);
  88345. };
  88346. /**
  88347. * Gets the list of animatables currently running for this skeleton
  88348. * @returns an array of animatables
  88349. */
  88350. Skeleton.prototype.getAnimatables = function () {
  88351. if (!this._animatables || this._animatables.length !== this.bones.length) {
  88352. this._animatables = [];
  88353. for (var index = 0; index < this.bones.length; index++) {
  88354. this._animatables.push(this.bones[index]);
  88355. }
  88356. }
  88357. return this._animatables;
  88358. };
  88359. /**
  88360. * Clone the current skeleton
  88361. * @param name defines the name of the new skeleton
  88362. * @param id defines the id of the enw skeleton
  88363. * @returns the new skeleton
  88364. */
  88365. Skeleton.prototype.clone = function (name, id) {
  88366. var result = new Skeleton(name, id || name, this._scene);
  88367. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  88368. for (var index = 0; index < this.bones.length; index++) {
  88369. var source = this.bones[index];
  88370. var parentBone = null;
  88371. var parent_1 = source.getParent();
  88372. if (parent_1) {
  88373. var parentIndex = this.bones.indexOf(parent_1);
  88374. parentBone = result.bones[parentIndex];
  88375. }
  88376. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  88377. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  88378. }
  88379. if (this._ranges) {
  88380. result._ranges = {};
  88381. for (var rangeName in this._ranges) {
  88382. var range = this._ranges[rangeName];
  88383. if (range) {
  88384. result._ranges[rangeName] = range.clone();
  88385. }
  88386. }
  88387. }
  88388. this._isDirty = true;
  88389. return result;
  88390. };
  88391. /**
  88392. * Enable animation blending for this skeleton
  88393. * @param blendingSpeed defines the blending speed to apply
  88394. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  88395. */
  88396. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  88397. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  88398. this.bones.forEach(function (bone) {
  88399. bone.animations.forEach(function (animation) {
  88400. animation.enableBlending = true;
  88401. animation.blendingSpeed = blendingSpeed;
  88402. });
  88403. });
  88404. };
  88405. /**
  88406. * Releases all resources associated with the current skeleton
  88407. */
  88408. Skeleton.prototype.dispose = function () {
  88409. this._meshesWithPoseMatrix = [];
  88410. // Animations
  88411. this.getScene().stopAnimation(this);
  88412. // Remove from scene
  88413. this.getScene().removeSkeleton(this);
  88414. };
  88415. /**
  88416. * Serialize the skeleton in a JSON object
  88417. * @returns a JSON object
  88418. */
  88419. Skeleton.prototype.serialize = function () {
  88420. var serializationObject = {};
  88421. serializationObject.name = this.name;
  88422. serializationObject.id = this.id;
  88423. if (this.dimensionsAtRest) {
  88424. serializationObject.dimensionsAtRest = this.dimensionsAtRest.asArray();
  88425. }
  88426. serializationObject.bones = [];
  88427. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  88428. for (var index = 0; index < this.bones.length; index++) {
  88429. var bone = this.bones[index];
  88430. var parent_2 = bone.getParent();
  88431. var serializedBone = {
  88432. parentBoneIndex: parent_2 ? this.bones.indexOf(parent_2) : -1,
  88433. name: bone.name,
  88434. matrix: bone.getBaseMatrix().toArray(),
  88435. rest: bone.getRestPose().toArray()
  88436. };
  88437. serializationObject.bones.push(serializedBone);
  88438. if (bone.length) {
  88439. serializedBone.length = bone.length;
  88440. }
  88441. if (bone.metadata) {
  88442. serializedBone.metadata = bone.metadata;
  88443. }
  88444. if (bone.animations && bone.animations.length > 0) {
  88445. serializedBone.animation = bone.animations[0].serialize();
  88446. }
  88447. serializationObject.ranges = [];
  88448. for (var name in this._ranges) {
  88449. var source = this._ranges[name];
  88450. if (!source) {
  88451. continue;
  88452. }
  88453. var range = {};
  88454. range.name = name;
  88455. range.from = source.from;
  88456. range.to = source.to;
  88457. serializationObject.ranges.push(range);
  88458. }
  88459. }
  88460. return serializationObject;
  88461. };
  88462. /**
  88463. * Creates a new skeleton from serialized data
  88464. * @param parsedSkeleton defines the serialized data
  88465. * @param scene defines the hosting scene
  88466. * @returns a new skeleton
  88467. */
  88468. Skeleton.Parse = function (parsedSkeleton, scene) {
  88469. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  88470. if (parsedSkeleton.dimensionsAtRest) {
  88471. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  88472. }
  88473. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  88474. var index;
  88475. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  88476. var parsedBone = parsedSkeleton.bones[index];
  88477. var parentBone = null;
  88478. if (parsedBone.parentBoneIndex > -1) {
  88479. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  88480. }
  88481. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  88482. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  88483. if (parsedBone.id !== undefined && parsedBone.id !== null) {
  88484. bone.id = parsedBone.id;
  88485. }
  88486. if (parsedBone.length) {
  88487. bone.length = parsedBone.length;
  88488. }
  88489. if (parsedBone.metadata) {
  88490. bone.metadata = parsedBone.metadata;
  88491. }
  88492. if (parsedBone.animation) {
  88493. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  88494. }
  88495. }
  88496. // placed after bones, so createAnimationRange can cascade down
  88497. if (parsedSkeleton.ranges) {
  88498. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  88499. var data = parsedSkeleton.ranges[index];
  88500. skeleton.createAnimationRange(data.name, data.from, data.to);
  88501. }
  88502. }
  88503. return skeleton;
  88504. };
  88505. /**
  88506. * Compute all node absolute transforms
  88507. * @param forceUpdate defines if computation must be done even if cache is up to date
  88508. */
  88509. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  88510. if (forceUpdate === void 0) { forceUpdate = false; }
  88511. var renderId = this._scene.getRenderId();
  88512. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  88513. this.bones[0].computeAbsoluteTransforms();
  88514. this._lastAbsoluteTransformsUpdateId = renderId;
  88515. }
  88516. };
  88517. /**
  88518. * Gets the root pose matrix
  88519. * @returns a matrix
  88520. */
  88521. Skeleton.prototype.getPoseMatrix = function () {
  88522. var poseMatrix = null;
  88523. if (this._meshesWithPoseMatrix.length > 0) {
  88524. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  88525. }
  88526. return poseMatrix;
  88527. };
  88528. /**
  88529. * Sorts bones per internal index
  88530. */
  88531. Skeleton.prototype.sortBones = function () {
  88532. var bones = new Array();
  88533. var visited = new Array(this.bones.length);
  88534. for (var index = 0; index < this.bones.length; index++) {
  88535. this._sortBones(index, bones, visited);
  88536. }
  88537. this.bones = bones;
  88538. };
  88539. Skeleton.prototype._sortBones = function (index, bones, visited) {
  88540. if (visited[index]) {
  88541. return;
  88542. }
  88543. visited[index] = true;
  88544. var bone = this.bones[index];
  88545. if (bone._index === undefined) {
  88546. bone._index = index;
  88547. }
  88548. var parentBone = bone.getParent();
  88549. if (parentBone) {
  88550. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  88551. }
  88552. bones.push(bone);
  88553. };
  88554. return Skeleton;
  88555. }());
  88556. BABYLON.Skeleton = Skeleton;
  88557. })(BABYLON || (BABYLON = {}));
  88558. //# sourceMappingURL=babylon.skeleton.js.map
  88559. var BABYLON;
  88560. (function (BABYLON) {
  88561. ;
  88562. /**
  88563. * This groups tools to convert HDR texture to native colors array.
  88564. */
  88565. var HDRTools = /** @class */ (function () {
  88566. function HDRTools() {
  88567. }
  88568. HDRTools.Ldexp = function (mantissa, exponent) {
  88569. if (exponent > 1023) {
  88570. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  88571. }
  88572. if (exponent < -1074) {
  88573. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  88574. }
  88575. return mantissa * Math.pow(2, exponent);
  88576. };
  88577. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  88578. if (exponent > 0) { /*nonzero pixel*/
  88579. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  88580. float32array[index + 0] = red * exponent;
  88581. float32array[index + 1] = green * exponent;
  88582. float32array[index + 2] = blue * exponent;
  88583. }
  88584. else {
  88585. float32array[index + 0] = 0;
  88586. float32array[index + 1] = 0;
  88587. float32array[index + 2] = 0;
  88588. }
  88589. };
  88590. HDRTools.readStringLine = function (uint8array, startIndex) {
  88591. var line = "";
  88592. var character = "";
  88593. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  88594. character = String.fromCharCode(uint8array[i]);
  88595. if (character == "\n") {
  88596. break;
  88597. }
  88598. line += character;
  88599. }
  88600. return line;
  88601. };
  88602. /**
  88603. * Reads header information from an RGBE texture stored in a native array.
  88604. * More information on this format are available here:
  88605. * https://en.wikipedia.org/wiki/RGBE_image_format
  88606. *
  88607. * @param uint8array The binary file stored in native array.
  88608. * @return The header information.
  88609. */
  88610. HDRTools.RGBE_ReadHeader = function (uint8array) {
  88611. var height = 0;
  88612. var width = 0;
  88613. var line = this.readStringLine(uint8array, 0);
  88614. if (line[0] != '#' || line[1] != '?') {
  88615. throw "Bad HDR Format.";
  88616. }
  88617. var endOfHeader = false;
  88618. var findFormat = false;
  88619. var lineIndex = 0;
  88620. do {
  88621. lineIndex += (line.length + 1);
  88622. line = this.readStringLine(uint8array, lineIndex);
  88623. if (line == "FORMAT=32-bit_rle_rgbe") {
  88624. findFormat = true;
  88625. }
  88626. else if (line.length == 0) {
  88627. endOfHeader = true;
  88628. }
  88629. } while (!endOfHeader);
  88630. if (!findFormat) {
  88631. throw "HDR Bad header format, unsupported FORMAT";
  88632. }
  88633. lineIndex += (line.length + 1);
  88634. line = this.readStringLine(uint8array, lineIndex);
  88635. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  88636. var match = sizeRegexp.exec(line);
  88637. // TODO. Support +Y and -X if needed.
  88638. if (!match || match.length < 3) {
  88639. throw "HDR Bad header format, no size";
  88640. }
  88641. width = parseInt(match[2]);
  88642. height = parseInt(match[1]);
  88643. if (width < 8 || width > 0x7fff) {
  88644. throw "HDR Bad header format, unsupported size";
  88645. }
  88646. lineIndex += (line.length + 1);
  88647. return {
  88648. height: height,
  88649. width: width,
  88650. dataPosition: lineIndex
  88651. };
  88652. };
  88653. /**
  88654. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  88655. * This RGBE texture needs to store the information as a panorama.
  88656. *
  88657. * More information on this format are available here:
  88658. * https://en.wikipedia.org/wiki/RGBE_image_format
  88659. *
  88660. * @param buffer The binary file stored in an array buffer.
  88661. * @param size The expected size of the extracted cubemap.
  88662. * @return The Cube Map information.
  88663. */
  88664. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  88665. var uint8array = new Uint8Array(buffer);
  88666. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  88667. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  88668. var cubeMapData = BABYLON.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  88669. return cubeMapData;
  88670. };
  88671. /**
  88672. * Returns the pixels data extracted from an RGBE texture.
  88673. * This pixels will be stored left to right up to down in the R G B order in one array.
  88674. *
  88675. * More information on this format are available here:
  88676. * https://en.wikipedia.org/wiki/RGBE_image_format
  88677. *
  88678. * @param uint8array The binary file stored in an array buffer.
  88679. * @param hdrInfo The header information of the file.
  88680. * @return The pixels data in RGB right to left up to down order.
  88681. */
  88682. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  88683. // Keep for multi format supports.
  88684. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  88685. };
  88686. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  88687. var num_scanlines = hdrInfo.height;
  88688. var scanline_width = hdrInfo.width;
  88689. var a, b, c, d, count;
  88690. var dataIndex = hdrInfo.dataPosition;
  88691. var index = 0, endIndex = 0, i = 0;
  88692. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  88693. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  88694. // 3 channels of 4 bytes per pixel in float.
  88695. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  88696. var resultArray = new Float32Array(resultBuffer);
  88697. // read in each successive scanline
  88698. while (num_scanlines > 0) {
  88699. a = uint8array[dataIndex++];
  88700. b = uint8array[dataIndex++];
  88701. c = uint8array[dataIndex++];
  88702. d = uint8array[dataIndex++];
  88703. if (a != 2 || b != 2 || (c & 0x80)) {
  88704. // this file is not run length encoded
  88705. throw "HDR Bad header format, not RLE";
  88706. }
  88707. if (((c << 8) | d) != scanline_width) {
  88708. throw "HDR Bad header format, wrong scan line width";
  88709. }
  88710. index = 0;
  88711. // read each of the four channels for the scanline into the buffer
  88712. for (i = 0; i < 4; i++) {
  88713. endIndex = (i + 1) * scanline_width;
  88714. while (index < endIndex) {
  88715. a = uint8array[dataIndex++];
  88716. b = uint8array[dataIndex++];
  88717. if (a > 128) {
  88718. // a run of the same value
  88719. count = a - 128;
  88720. if ((count == 0) || (count > endIndex - index)) {
  88721. throw "HDR Bad Format, bad scanline data (run)";
  88722. }
  88723. while (count-- > 0) {
  88724. scanLineArray[index++] = b;
  88725. }
  88726. }
  88727. else {
  88728. // a non-run
  88729. count = a;
  88730. if ((count == 0) || (count > endIndex - index)) {
  88731. throw "HDR Bad Format, bad scanline data (non-run)";
  88732. }
  88733. scanLineArray[index++] = b;
  88734. if (--count > 0) {
  88735. for (var j = 0; j < count; j++) {
  88736. scanLineArray[index++] = uint8array[dataIndex++];
  88737. }
  88738. }
  88739. }
  88740. }
  88741. }
  88742. // now convert data from buffer into floats
  88743. for (i = 0; i < scanline_width; i++) {
  88744. a = scanLineArray[i];
  88745. b = scanLineArray[i + scanline_width];
  88746. c = scanLineArray[i + 2 * scanline_width];
  88747. d = scanLineArray[i + 3 * scanline_width];
  88748. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  88749. }
  88750. num_scanlines--;
  88751. }
  88752. return resultArray;
  88753. };
  88754. return HDRTools;
  88755. }());
  88756. BABYLON.HDRTools = HDRTools;
  88757. })(BABYLON || (BABYLON = {}));
  88758. //# sourceMappingURL=babylon.hdr.js.map
  88759. var BABYLON;
  88760. (function (BABYLON) {
  88761. /**
  88762. * This represents a texture coming from an HDR input.
  88763. *
  88764. * The only supported format is currently panorama picture stored in RGBE format.
  88765. * Example of such files can be found on HDRLib: http://hdrlib.com/
  88766. */
  88767. var HDRCubeTexture = /** @class */ (function (_super) {
  88768. __extends(HDRCubeTexture, _super);
  88769. /**
  88770. * Instantiates an HDRTexture from the following parameters.
  88771. *
  88772. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  88773. * @param scene The scene the texture will be used in
  88774. * @param size The cubemap desired size (the more it increases the longer the generation will be)
  88775. * @param noMipmap Forces to not generate the mipmap if true
  88776. * @param generateHarmonics Specifies whether you want to extract the polynomial harmonics during the generation process
  88777. * @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)
  88778. * @param reserved Reserved flag for internal use.
  88779. */
  88780. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, gammaSpace, reserved, onLoad, onError) {
  88781. if (noMipmap === void 0) { noMipmap = false; }
  88782. if (generateHarmonics === void 0) { generateHarmonics = true; }
  88783. if (gammaSpace === void 0) { gammaSpace = false; }
  88784. if (reserved === void 0) { reserved = false; }
  88785. if (onLoad === void 0) { onLoad = null; }
  88786. if (onError === void 0) { onError = null; }
  88787. var _this = _super.call(this, scene) || this;
  88788. _this._generateHarmonics = true;
  88789. _this._onLoad = null;
  88790. _this._onError = null;
  88791. /**
  88792. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  88793. */
  88794. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  88795. _this._isBlocking = true;
  88796. _this._rotationY = 0;
  88797. /**
  88798. * Gets or sets the center of the bounding box associated with the cube texture
  88799. * It must define where the camera used to render the texture was set
  88800. */
  88801. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  88802. if (!url) {
  88803. return _this;
  88804. }
  88805. _this.name = url;
  88806. _this.url = url;
  88807. _this.hasAlpha = false;
  88808. _this.isCube = true;
  88809. _this._textureMatrix = BABYLON.Matrix.Identity();
  88810. _this._onLoad = onLoad;
  88811. _this._onError = onError;
  88812. _this.gammaSpace = gammaSpace;
  88813. _this._noMipmap = noMipmap;
  88814. _this._size = size;
  88815. _this._texture = _this._getFromCache(url, _this._noMipmap);
  88816. if (!_this._texture) {
  88817. if (!scene.useDelayedTextureLoading) {
  88818. _this.loadTexture();
  88819. }
  88820. else {
  88821. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  88822. }
  88823. }
  88824. return _this;
  88825. }
  88826. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  88827. /**
  88828. * Gets wether or not the texture is blocking during loading.
  88829. */
  88830. get: function () {
  88831. return this._isBlocking;
  88832. },
  88833. /**
  88834. * Sets wether or not the texture is blocking during loading.
  88835. */
  88836. set: function (value) {
  88837. this._isBlocking = value;
  88838. },
  88839. enumerable: true,
  88840. configurable: true
  88841. });
  88842. Object.defineProperty(HDRCubeTexture.prototype, "rotationY", {
  88843. /**
  88844. * Gets texture matrix rotation angle around Y axis radians.
  88845. */
  88846. get: function () {
  88847. return this._rotationY;
  88848. },
  88849. /**
  88850. * Sets texture matrix rotation angle around Y axis in radians.
  88851. */
  88852. set: function (value) {
  88853. this._rotationY = value;
  88854. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  88855. },
  88856. enumerable: true,
  88857. configurable: true
  88858. });
  88859. Object.defineProperty(HDRCubeTexture.prototype, "boundingBoxSize", {
  88860. get: function () {
  88861. return this._boundingBoxSize;
  88862. },
  88863. /**
  88864. * Gets or sets the size of the bounding box associated with the cube texture
  88865. * When defined, the cubemap will switch to local mode
  88866. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  88867. * @example https://www.babylonjs-playground.com/#RNASML
  88868. */
  88869. set: function (value) {
  88870. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  88871. return;
  88872. }
  88873. this._boundingBoxSize = value;
  88874. var scene = this.getScene();
  88875. if (scene) {
  88876. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  88877. }
  88878. },
  88879. enumerable: true,
  88880. configurable: true
  88881. });
  88882. /**
  88883. * Occurs when the file is raw .hdr file.
  88884. */
  88885. HDRCubeTexture.prototype.loadTexture = function () {
  88886. var _this = this;
  88887. var callback = function (buffer) {
  88888. _this.lodGenerationOffset = 0.0;
  88889. _this.lodGenerationScale = 0.8;
  88890. var scene = _this.getScene();
  88891. if (!scene) {
  88892. return null;
  88893. }
  88894. // Extract the raw linear data.
  88895. var data = BABYLON.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  88896. // Generate harmonics if needed.
  88897. if (_this._generateHarmonics) {
  88898. var sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  88899. _this.sphericalPolynomial = sphericalPolynomial;
  88900. }
  88901. var results = [];
  88902. var byteArray = null;
  88903. // Push each faces.
  88904. for (var j = 0; j < 6; j++) {
  88905. // Create uintarray fallback.
  88906. if (!scene.getEngine().getCaps().textureFloat) {
  88907. // 3 channels of 1 bytes per pixel in bytes.
  88908. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  88909. byteArray = new Uint8Array(byteBuffer);
  88910. }
  88911. var dataFace = (data[HDRCubeTexture._facesMapping[j]]);
  88912. // If special cases.
  88913. if (_this.gammaSpace || byteArray) {
  88914. for (var i = 0; i < _this._size * _this._size; i++) {
  88915. // Put in gamma space if requested.
  88916. if (_this.gammaSpace) {
  88917. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  88918. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  88919. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  88920. }
  88921. // Convert to int texture for fallback.
  88922. if (byteArray) {
  88923. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  88924. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  88925. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  88926. // May use luminance instead if the result is not accurate.
  88927. var max = Math.max(Math.max(r, g), b);
  88928. if (max > 255) {
  88929. var scale = 255 / max;
  88930. r *= scale;
  88931. g *= scale;
  88932. b *= scale;
  88933. }
  88934. byteArray[(i * 3) + 0] = r;
  88935. byteArray[(i * 3) + 1] = g;
  88936. byteArray[(i * 3) + 2] = b;
  88937. }
  88938. }
  88939. }
  88940. if (byteArray) {
  88941. results.push(byteArray);
  88942. }
  88943. else {
  88944. results.push(dataFace);
  88945. }
  88946. }
  88947. return results;
  88948. };
  88949. var scene = this.getScene();
  88950. if (scene) {
  88951. 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);
  88952. }
  88953. };
  88954. HDRCubeTexture.prototype.clone = function () {
  88955. var scene = this.getScene();
  88956. if (!scene) {
  88957. return this;
  88958. }
  88959. var newTexture = new HDRCubeTexture(this.url, scene, this._size, this._noMipmap, this._generateHarmonics, this.gammaSpace);
  88960. // Base texture
  88961. newTexture.level = this.level;
  88962. newTexture.wrapU = this.wrapU;
  88963. newTexture.wrapV = this.wrapV;
  88964. newTexture.coordinatesIndex = this.coordinatesIndex;
  88965. newTexture.coordinatesMode = this.coordinatesMode;
  88966. return newTexture;
  88967. };
  88968. // Methods
  88969. HDRCubeTexture.prototype.delayLoad = function () {
  88970. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  88971. return;
  88972. }
  88973. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  88974. this._texture = this._getFromCache(this.url, this._noMipmap);
  88975. if (!this._texture) {
  88976. this.loadTexture();
  88977. }
  88978. };
  88979. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  88980. return this._textureMatrix;
  88981. };
  88982. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  88983. this._textureMatrix = value;
  88984. };
  88985. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  88986. var texture = null;
  88987. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  88988. texture = new HDRCubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace);
  88989. texture.name = parsedTexture.name;
  88990. texture.hasAlpha = parsedTexture.hasAlpha;
  88991. texture.level = parsedTexture.level;
  88992. texture.coordinatesMode = parsedTexture.coordinatesMode;
  88993. texture.isBlocking = parsedTexture.isBlocking;
  88994. }
  88995. if (texture) {
  88996. if (parsedTexture.boundingBoxPosition) {
  88997. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  88998. }
  88999. if (parsedTexture.boundingBoxSize) {
  89000. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  89001. }
  89002. if (parsedTexture.rotationY) {
  89003. texture.rotationY = parsedTexture.rotationY;
  89004. }
  89005. }
  89006. return texture;
  89007. };
  89008. HDRCubeTexture.prototype.serialize = function () {
  89009. if (!this.name) {
  89010. return null;
  89011. }
  89012. var serializationObject = {};
  89013. serializationObject.name = this.name;
  89014. serializationObject.hasAlpha = this.hasAlpha;
  89015. serializationObject.isCube = true;
  89016. serializationObject.level = this.level;
  89017. serializationObject.size = this._size;
  89018. serializationObject.coordinatesMode = this.coordinatesMode;
  89019. serializationObject.useInGammaSpace = this.gammaSpace;
  89020. serializationObject.generateHarmonics = this._generateHarmonics;
  89021. serializationObject.customType = "BABYLON.HDRCubeTexture";
  89022. serializationObject.noMipmap = this._noMipmap;
  89023. serializationObject.isBlocking = this._isBlocking;
  89024. serializationObject.rotationY = this._rotationY;
  89025. return serializationObject;
  89026. };
  89027. HDRCubeTexture._facesMapping = [
  89028. "right",
  89029. "left",
  89030. "up",
  89031. "down",
  89032. "front",
  89033. "back"
  89034. ];
  89035. return HDRCubeTexture;
  89036. }(BABYLON.BaseTexture));
  89037. BABYLON.HDRCubeTexture = HDRCubeTexture;
  89038. })(BABYLON || (BABYLON = {}));
  89039. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  89040. var BABYLON;
  89041. (function (BABYLON) {
  89042. /**
  89043. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  89044. */
  89045. var PanoramaToCubeMapTools = /** @class */ (function () {
  89046. function PanoramaToCubeMapTools() {
  89047. }
  89048. /**
  89049. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  89050. *
  89051. * @param float32Array The source data.
  89052. * @param inputWidth The width of the input panorama.
  89053. * @param inputhHeight The height of the input panorama.
  89054. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  89055. * @return The cubemap data
  89056. */
  89057. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  89058. if (!float32Array) {
  89059. throw "ConvertPanoramaToCubemap: input cannot be null";
  89060. }
  89061. if (float32Array.length != inputWidth * inputHeight * 3) {
  89062. throw "ConvertPanoramaToCubemap: input size is wrong";
  89063. }
  89064. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  89065. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  89066. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  89067. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  89068. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  89069. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  89070. return {
  89071. front: textureFront,
  89072. back: textureBack,
  89073. left: textureLeft,
  89074. right: textureRight,
  89075. up: textureUp,
  89076. down: textureDown,
  89077. size: size,
  89078. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  89079. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  89080. gammaSpace: false,
  89081. };
  89082. };
  89083. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  89084. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  89085. var textureArray = new Float32Array(buffer);
  89086. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  89087. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  89088. var dy = 1 / texSize;
  89089. var fy = 0;
  89090. for (var y = 0; y < texSize; y++) {
  89091. var xv1 = faceData[0];
  89092. var xv2 = faceData[2];
  89093. for (var x = 0; x < texSize; x++) {
  89094. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  89095. v.normalize();
  89096. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  89097. // 3 channels per pixels
  89098. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  89099. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  89100. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  89101. xv1 = xv1.add(rotDX1);
  89102. xv2 = xv2.add(rotDX2);
  89103. }
  89104. fy += dy;
  89105. }
  89106. return textureArray;
  89107. };
  89108. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  89109. var theta = Math.atan2(vDir.z, vDir.x);
  89110. var phi = Math.acos(vDir.y);
  89111. while (theta < -Math.PI)
  89112. theta += 2 * Math.PI;
  89113. while (theta > Math.PI)
  89114. theta -= 2 * Math.PI;
  89115. var dx = theta / Math.PI;
  89116. var dy = phi / Math.PI;
  89117. // recenter.
  89118. dx = dx * 0.5 + 0.5;
  89119. var px = Math.round(dx * inputWidth);
  89120. if (px < 0)
  89121. px = 0;
  89122. else if (px >= inputWidth)
  89123. px = inputWidth - 1;
  89124. var py = Math.round(dy * inputHeight);
  89125. if (py < 0)
  89126. py = 0;
  89127. else if (py >= inputHeight)
  89128. py = inputHeight - 1;
  89129. var inputY = (inputHeight - py - 1);
  89130. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  89131. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  89132. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  89133. return {
  89134. r: r,
  89135. g: g,
  89136. b: b
  89137. };
  89138. };
  89139. PanoramaToCubeMapTools.FACE_FRONT = [
  89140. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  89141. new BABYLON.Vector3(1.0, -1.0, -1.0),
  89142. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  89143. new BABYLON.Vector3(1.0, 1.0, -1.0)
  89144. ];
  89145. PanoramaToCubeMapTools.FACE_BACK = [
  89146. new BABYLON.Vector3(1.0, -1.0, 1.0),
  89147. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  89148. new BABYLON.Vector3(1.0, 1.0, 1.0),
  89149. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  89150. ];
  89151. PanoramaToCubeMapTools.FACE_RIGHT = [
  89152. new BABYLON.Vector3(1.0, -1.0, -1.0),
  89153. new BABYLON.Vector3(1.0, -1.0, 1.0),
  89154. new BABYLON.Vector3(1.0, 1.0, -1.0),
  89155. new BABYLON.Vector3(1.0, 1.0, 1.0)
  89156. ];
  89157. PanoramaToCubeMapTools.FACE_LEFT = [
  89158. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  89159. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  89160. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  89161. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  89162. ];
  89163. PanoramaToCubeMapTools.FACE_DOWN = [
  89164. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  89165. new BABYLON.Vector3(1.0, 1.0, -1.0),
  89166. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  89167. new BABYLON.Vector3(1.0, 1.0, 1.0)
  89168. ];
  89169. PanoramaToCubeMapTools.FACE_UP = [
  89170. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  89171. new BABYLON.Vector3(1.0, -1.0, 1.0),
  89172. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  89173. new BABYLON.Vector3(1.0, -1.0, -1.0)
  89174. ];
  89175. return PanoramaToCubeMapTools;
  89176. }());
  89177. BABYLON.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  89178. })(BABYLON || (BABYLON = {}));
  89179. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  89180. var BABYLON;
  89181. (function (BABYLON) {
  89182. var IndexedVector2 = /** @class */ (function (_super) {
  89183. __extends(IndexedVector2, _super);
  89184. function IndexedVector2(original, index) {
  89185. var _this = _super.call(this, original.x, original.y) || this;
  89186. _this.index = index;
  89187. return _this;
  89188. }
  89189. return IndexedVector2;
  89190. }(BABYLON.Vector2));
  89191. var PolygonPoints = /** @class */ (function () {
  89192. function PolygonPoints() {
  89193. this.elements = new Array();
  89194. }
  89195. PolygonPoints.prototype.add = function (originalPoints) {
  89196. var _this = this;
  89197. var result = new Array();
  89198. originalPoints.forEach(function (point) {
  89199. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  89200. var newPoint = new IndexedVector2(point, _this.elements.length);
  89201. result.push(newPoint);
  89202. _this.elements.push(newPoint);
  89203. }
  89204. });
  89205. return result;
  89206. };
  89207. PolygonPoints.prototype.computeBounds = function () {
  89208. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  89209. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  89210. this.elements.forEach(function (point) {
  89211. // x
  89212. if (point.x < lmin.x) {
  89213. lmin.x = point.x;
  89214. }
  89215. else if (point.x > lmax.x) {
  89216. lmax.x = point.x;
  89217. }
  89218. // y
  89219. if (point.y < lmin.y) {
  89220. lmin.y = point.y;
  89221. }
  89222. else if (point.y > lmax.y) {
  89223. lmax.y = point.y;
  89224. }
  89225. });
  89226. return {
  89227. min: lmin,
  89228. max: lmax,
  89229. width: lmax.x - lmin.x,
  89230. height: lmax.y - lmin.y
  89231. };
  89232. };
  89233. return PolygonPoints;
  89234. }());
  89235. var Polygon = /** @class */ (function () {
  89236. function Polygon() {
  89237. }
  89238. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  89239. return [
  89240. new BABYLON.Vector2(xmin, ymin),
  89241. new BABYLON.Vector2(xmax, ymin),
  89242. new BABYLON.Vector2(xmax, ymax),
  89243. new BABYLON.Vector2(xmin, ymax)
  89244. ];
  89245. };
  89246. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  89247. if (cx === void 0) { cx = 0; }
  89248. if (cy === void 0) { cy = 0; }
  89249. if (numberOfSides === void 0) { numberOfSides = 32; }
  89250. var result = new Array();
  89251. var angle = 0;
  89252. var increment = (Math.PI * 2) / numberOfSides;
  89253. for (var i = 0; i < numberOfSides; i++) {
  89254. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  89255. angle -= increment;
  89256. }
  89257. return result;
  89258. };
  89259. Polygon.Parse = function (input) {
  89260. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  89261. var i, result = [];
  89262. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  89263. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  89264. }
  89265. return result;
  89266. };
  89267. Polygon.StartingAt = function (x, y) {
  89268. return BABYLON.Path2.StartingAt(x, y);
  89269. };
  89270. return Polygon;
  89271. }());
  89272. BABYLON.Polygon = Polygon;
  89273. var PolygonMeshBuilder = /** @class */ (function () {
  89274. function PolygonMeshBuilder(name, contours, scene) {
  89275. this._points = new PolygonPoints();
  89276. this._outlinepoints = new PolygonPoints();
  89277. this._holes = new Array();
  89278. this._epoints = new Array();
  89279. this._eholes = new Array();
  89280. this._name = name;
  89281. this._scene = scene;
  89282. var points;
  89283. if (contours instanceof BABYLON.Path2) {
  89284. points = contours.getPoints();
  89285. }
  89286. else {
  89287. points = contours;
  89288. }
  89289. this._addToepoint(points);
  89290. this._points.add(points);
  89291. this._outlinepoints.add(points);
  89292. if (typeof earcut === 'undefined') {
  89293. BABYLON.Tools.Warn("Earcut was not found, the polygon will not be built.");
  89294. }
  89295. }
  89296. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  89297. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  89298. var p = points_1[_i];
  89299. this._epoints.push(p.x, p.y);
  89300. }
  89301. };
  89302. PolygonMeshBuilder.prototype.addHole = function (hole) {
  89303. this._points.add(hole);
  89304. var holepoints = new PolygonPoints();
  89305. holepoints.add(hole);
  89306. this._holes.push(holepoints);
  89307. this._eholes.push(this._epoints.length / 2);
  89308. this._addToepoint(hole);
  89309. return this;
  89310. };
  89311. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  89312. var _this = this;
  89313. if (updatable === void 0) { updatable = false; }
  89314. if (depth === void 0) { depth = 0; }
  89315. var result = new BABYLON.Mesh(this._name, this._scene);
  89316. var normals = new Array();
  89317. var positions = new Array();
  89318. var uvs = new Array();
  89319. var bounds = this._points.computeBounds();
  89320. this._points.elements.forEach(function (p) {
  89321. normals.push(0, 1.0, 0);
  89322. positions.push(p.x, 0, p.y);
  89323. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  89324. });
  89325. var indices = new Array();
  89326. var res = earcut(this._epoints, this._eholes, 2);
  89327. for (var i = 0; i < res.length; i++) {
  89328. indices.push(res[i]);
  89329. }
  89330. if (depth > 0) {
  89331. var positionscount = (positions.length / 3); //get the current pointcount
  89332. this._points.elements.forEach(function (p) {
  89333. normals.push(0, -1.0, 0);
  89334. positions.push(p.x, -depth, p.y);
  89335. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  89336. });
  89337. var totalCount = indices.length;
  89338. for (var i = 0; i < totalCount; i += 3) {
  89339. var i0 = indices[i + 0];
  89340. var i1 = indices[i + 1];
  89341. var i2 = indices[i + 2];
  89342. indices.push(i2 + positionscount);
  89343. indices.push(i1 + positionscount);
  89344. indices.push(i0 + positionscount);
  89345. }
  89346. //Add the sides
  89347. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  89348. this._holes.forEach(function (hole) {
  89349. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  89350. });
  89351. }
  89352. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  89353. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  89354. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  89355. result.setIndices(indices);
  89356. return result;
  89357. };
  89358. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  89359. var StartIndex = positions.length / 3;
  89360. var ulength = 0;
  89361. for (var i = 0; i < points.elements.length; i++) {
  89362. var p = points.elements[i];
  89363. var p1;
  89364. if ((i + 1) > points.elements.length - 1) {
  89365. p1 = points.elements[0];
  89366. }
  89367. else {
  89368. p1 = points.elements[i + 1];
  89369. }
  89370. positions.push(p.x, 0, p.y);
  89371. positions.push(p.x, -depth, p.y);
  89372. positions.push(p1.x, 0, p1.y);
  89373. positions.push(p1.x, -depth, p1.y);
  89374. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  89375. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  89376. var v3 = v2.subtract(v1);
  89377. var v4 = new BABYLON.Vector3(0, 1, 0);
  89378. var vn = BABYLON.Vector3.Cross(v3, v4);
  89379. vn = vn.normalize();
  89380. uvs.push(ulength / bounds.width, 0);
  89381. uvs.push(ulength / bounds.width, 1);
  89382. ulength += v3.length();
  89383. uvs.push((ulength / bounds.width), 0);
  89384. uvs.push((ulength / bounds.width), 1);
  89385. if (!flip) {
  89386. normals.push(-vn.x, -vn.y, -vn.z);
  89387. normals.push(-vn.x, -vn.y, -vn.z);
  89388. normals.push(-vn.x, -vn.y, -vn.z);
  89389. normals.push(-vn.x, -vn.y, -vn.z);
  89390. indices.push(StartIndex);
  89391. indices.push(StartIndex + 1);
  89392. indices.push(StartIndex + 2);
  89393. indices.push(StartIndex + 1);
  89394. indices.push(StartIndex + 3);
  89395. indices.push(StartIndex + 2);
  89396. }
  89397. else {
  89398. normals.push(vn.x, vn.y, vn.z);
  89399. normals.push(vn.x, vn.y, vn.z);
  89400. normals.push(vn.x, vn.y, vn.z);
  89401. normals.push(vn.x, vn.y, vn.z);
  89402. indices.push(StartIndex);
  89403. indices.push(StartIndex + 2);
  89404. indices.push(StartIndex + 1);
  89405. indices.push(StartIndex + 1);
  89406. indices.push(StartIndex + 2);
  89407. indices.push(StartIndex + 3);
  89408. }
  89409. StartIndex += 4;
  89410. }
  89411. ;
  89412. };
  89413. return PolygonMeshBuilder;
  89414. }());
  89415. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  89416. })(BABYLON || (BABYLON = {}));
  89417. //# sourceMappingURL=babylon.polygonMesh.js.map
  89418. var BABYLON;
  89419. (function (BABYLON) {
  89420. // Unique ID when we import meshes from Babylon to CSG
  89421. var currentCSGMeshId = 0;
  89422. // # class Vertex
  89423. // Represents a vertex of a polygon. Use your own vertex class instead of this
  89424. // one to provide additional features like texture coordinates and vertex
  89425. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  89426. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  89427. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  89428. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  89429. // is not used anywhere else.
  89430. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  89431. var Vertex = /** @class */ (function () {
  89432. function Vertex(pos, normal, uv) {
  89433. this.pos = pos;
  89434. this.normal = normal;
  89435. this.uv = uv;
  89436. }
  89437. Vertex.prototype.clone = function () {
  89438. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  89439. };
  89440. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  89441. // orientation of a polygon is flipped.
  89442. Vertex.prototype.flip = function () {
  89443. this.normal = this.normal.scale(-1);
  89444. };
  89445. // Create a new vertex between this vertex and `other` by linearly
  89446. // interpolating all properties using a parameter of `t`. Subclasses should
  89447. // override this to interpolate additional properties.
  89448. Vertex.prototype.interpolate = function (other, t) {
  89449. 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));
  89450. };
  89451. return Vertex;
  89452. }());
  89453. // # class Plane
  89454. // Represents a plane in 3D space.
  89455. var Plane = /** @class */ (function () {
  89456. function Plane(normal, w) {
  89457. this.normal = normal;
  89458. this.w = w;
  89459. }
  89460. Plane.FromPoints = function (a, b, c) {
  89461. var v0 = c.subtract(a);
  89462. var v1 = b.subtract(a);
  89463. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  89464. return null;
  89465. }
  89466. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  89467. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  89468. };
  89469. Plane.prototype.clone = function () {
  89470. return new Plane(this.normal.clone(), this.w);
  89471. };
  89472. Plane.prototype.flip = function () {
  89473. this.normal.scaleInPlace(-1);
  89474. this.w = -this.w;
  89475. };
  89476. // Split `polygon` by this plane if needed, then put the polygon or polygon
  89477. // fragments in the appropriate lists. Coplanar polygons go into either
  89478. // `coplanarFront` or `coplanarBack` depending on their orientation with
  89479. // respect to this plane. Polygons in front or in back of this plane go into
  89480. // either `front` or `back`.
  89481. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  89482. var COPLANAR = 0;
  89483. var FRONT = 1;
  89484. var BACK = 2;
  89485. var SPANNING = 3;
  89486. // Classify each point as well as the entire polygon into one of the above
  89487. // four classes.
  89488. var polygonType = 0;
  89489. var types = [];
  89490. var i;
  89491. var t;
  89492. for (i = 0; i < polygon.vertices.length; i++) {
  89493. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  89494. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  89495. polygonType |= type;
  89496. types.push(type);
  89497. }
  89498. // Put the polygon in the correct list, splitting it when necessary.
  89499. switch (polygonType) {
  89500. case COPLANAR:
  89501. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  89502. break;
  89503. case FRONT:
  89504. front.push(polygon);
  89505. break;
  89506. case BACK:
  89507. back.push(polygon);
  89508. break;
  89509. case SPANNING:
  89510. var f = [], b = [];
  89511. for (i = 0; i < polygon.vertices.length; i++) {
  89512. var j = (i + 1) % polygon.vertices.length;
  89513. var ti = types[i], tj = types[j];
  89514. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  89515. if (ti !== BACK)
  89516. f.push(vi);
  89517. if (ti !== FRONT)
  89518. b.push(ti !== BACK ? vi.clone() : vi);
  89519. if ((ti | tj) === SPANNING) {
  89520. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  89521. var v = vi.interpolate(vj, t);
  89522. f.push(v);
  89523. b.push(v.clone());
  89524. }
  89525. }
  89526. var poly;
  89527. if (f.length >= 3) {
  89528. poly = new Polygon(f, polygon.shared);
  89529. if (poly.plane)
  89530. front.push(poly);
  89531. }
  89532. if (b.length >= 3) {
  89533. poly = new Polygon(b, polygon.shared);
  89534. if (poly.plane)
  89535. back.push(poly);
  89536. }
  89537. break;
  89538. }
  89539. };
  89540. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  89541. // point is on the plane.
  89542. Plane.EPSILON = 1e-5;
  89543. return Plane;
  89544. }());
  89545. // # class Polygon
  89546. // Represents a convex polygon. The vertices used to initialize a polygon must
  89547. // be coplanar and form a convex loop.
  89548. //
  89549. // Each convex polygon has a `shared` property, which is shared between all
  89550. // polygons that are clones of each other or were split from the same polygon.
  89551. // This can be used to define per-polygon properties (such as surface color).
  89552. var Polygon = /** @class */ (function () {
  89553. function Polygon(vertices, shared) {
  89554. this.vertices = vertices;
  89555. this.shared = shared;
  89556. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  89557. }
  89558. Polygon.prototype.clone = function () {
  89559. var vertices = this.vertices.map(function (v) { return v.clone(); });
  89560. return new Polygon(vertices, this.shared);
  89561. };
  89562. Polygon.prototype.flip = function () {
  89563. this.vertices.reverse().map(function (v) { v.flip(); });
  89564. this.plane.flip();
  89565. };
  89566. return Polygon;
  89567. }());
  89568. // # class Node
  89569. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  89570. // by picking a polygon to split along. That polygon (and all other coplanar
  89571. // polygons) are added directly to that node and the other polygons are added to
  89572. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  89573. // no distinction between internal and leaf nodes.
  89574. var Node = /** @class */ (function () {
  89575. function Node(polygons) {
  89576. this.plane = null;
  89577. this.front = null;
  89578. this.back = null;
  89579. this.polygons = new Array();
  89580. if (polygons) {
  89581. this.build(polygons);
  89582. }
  89583. }
  89584. Node.prototype.clone = function () {
  89585. var node = new Node();
  89586. node.plane = this.plane && this.plane.clone();
  89587. node.front = this.front && this.front.clone();
  89588. node.back = this.back && this.back.clone();
  89589. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  89590. return node;
  89591. };
  89592. // Convert solid space to empty space and empty space to solid space.
  89593. Node.prototype.invert = function () {
  89594. for (var i = 0; i < this.polygons.length; i++) {
  89595. this.polygons[i].flip();
  89596. }
  89597. if (this.plane) {
  89598. this.plane.flip();
  89599. }
  89600. if (this.front) {
  89601. this.front.invert();
  89602. }
  89603. if (this.back) {
  89604. this.back.invert();
  89605. }
  89606. var temp = this.front;
  89607. this.front = this.back;
  89608. this.back = temp;
  89609. };
  89610. // Recursively remove all polygons in `polygons` that are inside this BSP
  89611. // tree.
  89612. Node.prototype.clipPolygons = function (polygons) {
  89613. if (!this.plane)
  89614. return polygons.slice();
  89615. var front = new Array(), back = new Array();
  89616. for (var i = 0; i < polygons.length; i++) {
  89617. this.plane.splitPolygon(polygons[i], front, back, front, back);
  89618. }
  89619. if (this.front) {
  89620. front = this.front.clipPolygons(front);
  89621. }
  89622. if (this.back) {
  89623. back = this.back.clipPolygons(back);
  89624. }
  89625. else {
  89626. back = [];
  89627. }
  89628. return front.concat(back);
  89629. };
  89630. // Remove all polygons in this BSP tree that are inside the other BSP tree
  89631. // `bsp`.
  89632. Node.prototype.clipTo = function (bsp) {
  89633. this.polygons = bsp.clipPolygons(this.polygons);
  89634. if (this.front)
  89635. this.front.clipTo(bsp);
  89636. if (this.back)
  89637. this.back.clipTo(bsp);
  89638. };
  89639. // Return a list of all polygons in this BSP tree.
  89640. Node.prototype.allPolygons = function () {
  89641. var polygons = this.polygons.slice();
  89642. if (this.front)
  89643. polygons = polygons.concat(this.front.allPolygons());
  89644. if (this.back)
  89645. polygons = polygons.concat(this.back.allPolygons());
  89646. return polygons;
  89647. };
  89648. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  89649. // new polygons are filtered down to the bottom of the tree and become new
  89650. // nodes there. Each set of polygons is partitioned using the first polygon
  89651. // (no heuristic is used to pick a good split).
  89652. Node.prototype.build = function (polygons) {
  89653. if (!polygons.length)
  89654. return;
  89655. if (!this.plane)
  89656. this.plane = polygons[0].plane.clone();
  89657. var front = new Array(), back = new Array();
  89658. for (var i = 0; i < polygons.length; i++) {
  89659. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  89660. }
  89661. if (front.length) {
  89662. if (!this.front)
  89663. this.front = new Node();
  89664. this.front.build(front);
  89665. }
  89666. if (back.length) {
  89667. if (!this.back)
  89668. this.back = new Node();
  89669. this.back.build(back);
  89670. }
  89671. };
  89672. return Node;
  89673. }());
  89674. var CSG = /** @class */ (function () {
  89675. function CSG() {
  89676. this.polygons = new Array();
  89677. }
  89678. // Convert BABYLON.Mesh to BABYLON.CSG
  89679. CSG.FromMesh = function (mesh) {
  89680. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  89681. var matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling;
  89682. if (mesh instanceof BABYLON.Mesh) {
  89683. mesh.computeWorldMatrix(true);
  89684. matrix = mesh.getWorldMatrix();
  89685. meshPosition = mesh.position.clone();
  89686. meshRotation = mesh.rotation.clone();
  89687. if (mesh.rotationQuaternion) {
  89688. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  89689. }
  89690. meshScaling = mesh.scaling.clone();
  89691. }
  89692. else {
  89693. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  89694. }
  89695. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  89696. var subMeshes = mesh.subMeshes;
  89697. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  89698. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  89699. vertices = [];
  89700. for (var j = 0; j < 3; j++) {
  89701. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  89702. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  89703. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  89704. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  89705. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  89706. vertex = new Vertex(position, normal, uv);
  89707. vertices.push(vertex);
  89708. }
  89709. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  89710. // To handle the case of degenerated triangle
  89711. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  89712. if (polygon.plane)
  89713. polygons.push(polygon);
  89714. }
  89715. }
  89716. var csg = CSG.FromPolygons(polygons);
  89717. csg.matrix = matrix;
  89718. csg.position = meshPosition;
  89719. csg.rotation = meshRotation;
  89720. csg.scaling = meshScaling;
  89721. csg.rotationQuaternion = meshRotationQuaternion;
  89722. currentCSGMeshId++;
  89723. return csg;
  89724. };
  89725. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  89726. CSG.FromPolygons = function (polygons) {
  89727. var csg = new CSG();
  89728. csg.polygons = polygons;
  89729. return csg;
  89730. };
  89731. CSG.prototype.clone = function () {
  89732. var csg = new CSG();
  89733. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  89734. csg.copyTransformAttributes(this);
  89735. return csg;
  89736. };
  89737. CSG.prototype.union = function (csg) {
  89738. var a = new Node(this.clone().polygons);
  89739. var b = new Node(csg.clone().polygons);
  89740. a.clipTo(b);
  89741. b.clipTo(a);
  89742. b.invert();
  89743. b.clipTo(a);
  89744. b.invert();
  89745. a.build(b.allPolygons());
  89746. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  89747. };
  89748. CSG.prototype.unionInPlace = function (csg) {
  89749. var a = new Node(this.polygons);
  89750. var b = new Node(csg.polygons);
  89751. a.clipTo(b);
  89752. b.clipTo(a);
  89753. b.invert();
  89754. b.clipTo(a);
  89755. b.invert();
  89756. a.build(b.allPolygons());
  89757. this.polygons = a.allPolygons();
  89758. };
  89759. CSG.prototype.subtract = function (csg) {
  89760. var a = new Node(this.clone().polygons);
  89761. var b = new Node(csg.clone().polygons);
  89762. a.invert();
  89763. a.clipTo(b);
  89764. b.clipTo(a);
  89765. b.invert();
  89766. b.clipTo(a);
  89767. b.invert();
  89768. a.build(b.allPolygons());
  89769. a.invert();
  89770. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  89771. };
  89772. CSG.prototype.subtractInPlace = function (csg) {
  89773. var a = new Node(this.polygons);
  89774. var b = new Node(csg.polygons);
  89775. a.invert();
  89776. a.clipTo(b);
  89777. b.clipTo(a);
  89778. b.invert();
  89779. b.clipTo(a);
  89780. b.invert();
  89781. a.build(b.allPolygons());
  89782. a.invert();
  89783. this.polygons = a.allPolygons();
  89784. };
  89785. CSG.prototype.intersect = function (csg) {
  89786. var a = new Node(this.clone().polygons);
  89787. var b = new Node(csg.clone().polygons);
  89788. a.invert();
  89789. b.clipTo(a);
  89790. b.invert();
  89791. a.clipTo(b);
  89792. b.clipTo(a);
  89793. a.build(b.allPolygons());
  89794. a.invert();
  89795. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  89796. };
  89797. CSG.prototype.intersectInPlace = function (csg) {
  89798. var a = new Node(this.polygons);
  89799. var b = new Node(csg.polygons);
  89800. a.invert();
  89801. b.clipTo(a);
  89802. b.invert();
  89803. a.clipTo(b);
  89804. b.clipTo(a);
  89805. a.build(b.allPolygons());
  89806. a.invert();
  89807. this.polygons = a.allPolygons();
  89808. };
  89809. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  89810. // not modified.
  89811. CSG.prototype.inverse = function () {
  89812. var csg = this.clone();
  89813. csg.inverseInPlace();
  89814. return csg;
  89815. };
  89816. CSG.prototype.inverseInPlace = function () {
  89817. this.polygons.map(function (p) { p.flip(); });
  89818. };
  89819. // This is used to keep meshes transformations so they can be restored
  89820. // when we build back a Babylon Mesh
  89821. // NB : All CSG operations are performed in world coordinates
  89822. CSG.prototype.copyTransformAttributes = function (csg) {
  89823. this.matrix = csg.matrix;
  89824. this.position = csg.position;
  89825. this.rotation = csg.rotation;
  89826. this.scaling = csg.scaling;
  89827. this.rotationQuaternion = csg.rotationQuaternion;
  89828. return this;
  89829. };
  89830. // Build Raw mesh from CSG
  89831. // Coordinates here are in world space
  89832. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  89833. var matrix = this.matrix.clone();
  89834. matrix.invert();
  89835. 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;
  89836. if (keepSubMeshes) {
  89837. // Sort Polygons, since subMeshes are indices range
  89838. polygons.sort(function (a, b) {
  89839. if (a.shared.meshId === b.shared.meshId) {
  89840. return a.shared.subMeshId - b.shared.subMeshId;
  89841. }
  89842. else {
  89843. return a.shared.meshId - b.shared.meshId;
  89844. }
  89845. });
  89846. }
  89847. for (var i = 0, il = polygons.length; i < il; i++) {
  89848. polygon = polygons[i];
  89849. // Building SubMeshes
  89850. if (!subMesh_dict[polygon.shared.meshId]) {
  89851. subMesh_dict[polygon.shared.meshId] = {};
  89852. }
  89853. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  89854. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  89855. indexStart: +Infinity,
  89856. indexEnd: -Infinity,
  89857. materialIndex: polygon.shared.materialIndex
  89858. };
  89859. }
  89860. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  89861. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  89862. polygonIndices[0] = 0;
  89863. polygonIndices[1] = j - 1;
  89864. polygonIndices[2] = j;
  89865. for (var k = 0; k < 3; k++) {
  89866. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  89867. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  89868. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  89869. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  89870. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  89871. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  89872. // Check if 2 points can be merged
  89873. if (!(typeof vertex_idx !== 'undefined' &&
  89874. normals[vertex_idx * 3] === localNormal.x &&
  89875. normals[vertex_idx * 3 + 1] === localNormal.y &&
  89876. normals[vertex_idx * 3 + 2] === localNormal.z &&
  89877. uvs[vertex_idx * 2] === uv.x &&
  89878. uvs[vertex_idx * 2 + 1] === uv.y)) {
  89879. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  89880. uvs.push(uv.x, uv.y);
  89881. normals.push(normal.x, normal.y, normal.z);
  89882. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  89883. }
  89884. indices.push(vertex_idx);
  89885. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  89886. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  89887. currentIndex++;
  89888. }
  89889. }
  89890. }
  89891. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  89892. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  89893. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  89894. mesh.setIndices(indices, null);
  89895. if (keepSubMeshes) {
  89896. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  89897. var materialIndexOffset = 0, materialMaxIndex;
  89898. mesh.subMeshes = new Array();
  89899. for (var m in subMesh_dict) {
  89900. materialMaxIndex = -1;
  89901. for (var sm in subMesh_dict[m]) {
  89902. subMesh_obj = subMesh_dict[m][sm];
  89903. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  89904. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  89905. }
  89906. materialIndexOffset += ++materialMaxIndex;
  89907. }
  89908. }
  89909. return mesh;
  89910. };
  89911. // Build Mesh from CSG taking material and transforms into account
  89912. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  89913. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  89914. mesh.material = material;
  89915. mesh.position.copyFrom(this.position);
  89916. mesh.rotation.copyFrom(this.rotation);
  89917. if (this.rotationQuaternion) {
  89918. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  89919. }
  89920. mesh.scaling.copyFrom(this.scaling);
  89921. mesh.computeWorldMatrix(true);
  89922. return mesh;
  89923. };
  89924. return CSG;
  89925. }());
  89926. BABYLON.CSG = CSG;
  89927. })(BABYLON || (BABYLON = {}));
  89928. //# sourceMappingURL=babylon.csg.js.map
  89929. var BABYLON;
  89930. (function (BABYLON) {
  89931. var LensFlare = /** @class */ (function () {
  89932. function LensFlare(size, position, color, imgUrl, system) {
  89933. this.size = size;
  89934. this.position = position;
  89935. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  89936. this.color = color || new BABYLON.Color3(1, 1, 1);
  89937. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  89938. this._system = system;
  89939. system.lensFlares.push(this);
  89940. }
  89941. LensFlare.AddFlare = function (size, position, color, imgUrl, system) {
  89942. return new LensFlare(size, position, color, imgUrl, system);
  89943. };
  89944. LensFlare.prototype.dispose = function () {
  89945. if (this.texture) {
  89946. this.texture.dispose();
  89947. }
  89948. // Remove from scene
  89949. var index = this._system.lensFlares.indexOf(this);
  89950. this._system.lensFlares.splice(index, 1);
  89951. };
  89952. ;
  89953. return LensFlare;
  89954. }());
  89955. BABYLON.LensFlare = LensFlare;
  89956. })(BABYLON || (BABYLON = {}));
  89957. //# sourceMappingURL=babylon.lensFlare.js.map
  89958. var BABYLON;
  89959. (function (BABYLON) {
  89960. // Adds the parser to the scene parsers.
  89961. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_LENSFLARESYSTEM, function (parsedData, scene, container, rootUrl) {
  89962. // Lens flares
  89963. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  89964. if (!container.lensFlareSystems) {
  89965. container.lensFlareSystems = new Array();
  89966. }
  89967. for (var index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  89968. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  89969. var lf = BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  89970. container.lensFlareSystems.push(lf);
  89971. }
  89972. }
  89973. });
  89974. BABYLON.AbstractScene.prototype.getLensFlareSystemByName = function (name) {
  89975. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  89976. if (this.lensFlareSystems[index].name === name) {
  89977. return this.lensFlareSystems[index];
  89978. }
  89979. }
  89980. return null;
  89981. };
  89982. BABYLON.AbstractScene.prototype.getLensFlareSystemByID = function (id) {
  89983. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  89984. if (this.lensFlareSystems[index].id === id) {
  89985. return this.lensFlareSystems[index];
  89986. }
  89987. }
  89988. return null;
  89989. };
  89990. BABYLON.AbstractScene.prototype.removeLensFlareSystem = function (toRemove) {
  89991. var index = this.lensFlareSystems.indexOf(toRemove);
  89992. if (index !== -1) {
  89993. this.lensFlareSystems.splice(index, 1);
  89994. }
  89995. return index;
  89996. };
  89997. BABYLON.AbstractScene.prototype.addLensFlareSystem = function (newLensFlareSystem) {
  89998. this.lensFlareSystems.push(newLensFlareSystem);
  89999. };
  90000. /**
  90001. * Defines the lens flare scene component responsible to manage any lens flares
  90002. * in a given scene.
  90003. */
  90004. var LensFlareSystemSceneComponent = /** @class */ (function () {
  90005. /**
  90006. * Creates a new instance of the component for the given scene
  90007. * @param scene Defines the scene to register the component in
  90008. */
  90009. function LensFlareSystemSceneComponent(scene) {
  90010. /**
  90011. * The component name helpfull to identify the component in the list of scene components.
  90012. */
  90013. this.name = BABYLON.SceneComponentConstants.NAME_LENSFLARESYSTEM;
  90014. this.scene = scene;
  90015. scene.lensFlareSystems = new Array();
  90016. }
  90017. /**
  90018. * Registers the component in a given scene
  90019. */
  90020. LensFlareSystemSceneComponent.prototype.register = function () {
  90021. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_LENSFLARESYSTEM, this, this._draw);
  90022. };
  90023. /**
  90024. * Rebuilds the elements related to this component in case of
  90025. * context lost for instance.
  90026. */
  90027. LensFlareSystemSceneComponent.prototype.rebuild = function () {
  90028. // Nothing to do for lens flare
  90029. };
  90030. /**
  90031. * Adds all the element from the container to the scene
  90032. * @param container the container holding the elements
  90033. */
  90034. LensFlareSystemSceneComponent.prototype.addFromContainer = function (container) {
  90035. var _this = this;
  90036. if (!container.lensFlareSystems) {
  90037. return;
  90038. }
  90039. container.lensFlareSystems.forEach(function (o) {
  90040. _this.scene.addLensFlareSystem(o);
  90041. });
  90042. };
  90043. /**
  90044. * Removes all the elements in the container from the scene
  90045. * @param container contains the elements to remove
  90046. */
  90047. LensFlareSystemSceneComponent.prototype.removeFromContainer = function (container) {
  90048. var _this = this;
  90049. if (!container.lensFlareSystems) {
  90050. return;
  90051. }
  90052. container.lensFlareSystems.forEach(function (o) {
  90053. _this.scene.removeLensFlareSystem(o);
  90054. });
  90055. };
  90056. /**
  90057. * Serializes the component data to the specified json object
  90058. * @param serializationObject The object to serialize to
  90059. */
  90060. LensFlareSystemSceneComponent.prototype.serialize = function (serializationObject) {
  90061. // Lens flares
  90062. serializationObject.lensFlareSystems = [];
  90063. var lensFlareSystems = this.scene.lensFlareSystems;
  90064. for (var _i = 0, lensFlareSystems_1 = lensFlareSystems; _i < lensFlareSystems_1.length; _i++) {
  90065. var lensFlareSystem = lensFlareSystems_1[_i];
  90066. serializationObject.lensFlareSystems.push(lensFlareSystem.serialize());
  90067. }
  90068. };
  90069. /**
  90070. * Disposes the component and the associated ressources.
  90071. */
  90072. LensFlareSystemSceneComponent.prototype.dispose = function () {
  90073. var lensFlareSystems = this.scene.lensFlareSystems;
  90074. while (lensFlareSystems.length) {
  90075. lensFlareSystems[0].dispose();
  90076. }
  90077. };
  90078. LensFlareSystemSceneComponent.prototype._draw = function (camera) {
  90079. // Lens flares
  90080. if (this.scene.lensFlaresEnabled) {
  90081. var lensFlareSystems = this.scene.lensFlareSystems;
  90082. BABYLON.Tools.StartPerformanceCounter("Lens flares", lensFlareSystems.length > 0);
  90083. for (var _i = 0, lensFlareSystems_2 = lensFlareSystems; _i < lensFlareSystems_2.length; _i++) {
  90084. var lensFlareSystem = lensFlareSystems_2[_i];
  90085. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  90086. lensFlareSystem.render();
  90087. }
  90088. }
  90089. BABYLON.Tools.EndPerformanceCounter("Lens flares", lensFlareSystems.length > 0);
  90090. }
  90091. };
  90092. return LensFlareSystemSceneComponent;
  90093. }());
  90094. BABYLON.LensFlareSystemSceneComponent = LensFlareSystemSceneComponent;
  90095. })(BABYLON || (BABYLON = {}));
  90096. //# sourceMappingURL=babylon.lensFlareSystemSceneComponent.js.map
  90097. var BABYLON;
  90098. (function (BABYLON) {
  90099. var LensFlareSystem = /** @class */ (function () {
  90100. function LensFlareSystem(name, emitter, scene) {
  90101. this.name = name;
  90102. this.lensFlares = new Array();
  90103. this.borderLimit = 300;
  90104. this.viewportBorder = 0;
  90105. this.layerMask = 0x0FFFFFFF;
  90106. this._vertexBuffers = {};
  90107. this._isEnabled = true;
  90108. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  90109. var component = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_LENSFLARESYSTEM);
  90110. if (!component) {
  90111. component = new BABYLON.LensFlareSystemSceneComponent(this._scene);
  90112. scene._addComponent(component);
  90113. }
  90114. this._emitter = emitter;
  90115. this.id = name;
  90116. scene.lensFlareSystems.push(this);
  90117. this.meshesSelectionPredicate = function (m) { return (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0)); };
  90118. var engine = scene.getEngine();
  90119. // VBO
  90120. var vertices = [];
  90121. vertices.push(1, 1);
  90122. vertices.push(-1, 1);
  90123. vertices.push(-1, -1);
  90124. vertices.push(1, -1);
  90125. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  90126. // Indices
  90127. var indices = [];
  90128. indices.push(0);
  90129. indices.push(1);
  90130. indices.push(2);
  90131. indices.push(0);
  90132. indices.push(2);
  90133. indices.push(3);
  90134. this._indexBuffer = engine.createIndexBuffer(indices);
  90135. // Effects
  90136. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  90137. }
  90138. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  90139. get: function () {
  90140. return this._isEnabled;
  90141. },
  90142. set: function (value) {
  90143. this._isEnabled = value;
  90144. },
  90145. enumerable: true,
  90146. configurable: true
  90147. });
  90148. LensFlareSystem.prototype.getScene = function () {
  90149. return this._scene;
  90150. };
  90151. LensFlareSystem.prototype.getEmitter = function () {
  90152. return this._emitter;
  90153. };
  90154. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  90155. this._emitter = newEmitter;
  90156. };
  90157. LensFlareSystem.prototype.getEmitterPosition = function () {
  90158. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  90159. };
  90160. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  90161. var position = this.getEmitterPosition();
  90162. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  90163. this._positionX = position.x;
  90164. this._positionY = position.y;
  90165. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  90166. if (this.viewportBorder > 0) {
  90167. globalViewport.x -= this.viewportBorder;
  90168. globalViewport.y -= this.viewportBorder;
  90169. globalViewport.width += this.viewportBorder * 2;
  90170. globalViewport.height += this.viewportBorder * 2;
  90171. position.x += this.viewportBorder;
  90172. position.y += this.viewportBorder;
  90173. this._positionX += this.viewportBorder;
  90174. this._positionY += this.viewportBorder;
  90175. }
  90176. if (position.z > 0) {
  90177. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  90178. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  90179. return true;
  90180. }
  90181. return true;
  90182. }
  90183. return false;
  90184. };
  90185. /** @hidden */
  90186. LensFlareSystem.prototype._isVisible = function () {
  90187. if (!this._isEnabled || !this._scene.activeCamera) {
  90188. return false;
  90189. }
  90190. var emitterPosition = this.getEmitterPosition();
  90191. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  90192. var distance = direction.length();
  90193. direction.normalize();
  90194. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  90195. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  90196. return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;
  90197. };
  90198. LensFlareSystem.prototype.render = function () {
  90199. if (!this._effect.isReady() || !this._scene.activeCamera)
  90200. return false;
  90201. var engine = this._scene.getEngine();
  90202. var viewport = this._scene.activeCamera.viewport;
  90203. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  90204. // Position
  90205. if (!this.computeEffectivePosition(globalViewport)) {
  90206. return false;
  90207. }
  90208. // Visibility
  90209. if (!this._isVisible()) {
  90210. return false;
  90211. }
  90212. // Intensity
  90213. var awayX;
  90214. var awayY;
  90215. if (this._positionX < this.borderLimit + globalViewport.x) {
  90216. awayX = this.borderLimit + globalViewport.x - this._positionX;
  90217. }
  90218. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  90219. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  90220. }
  90221. else {
  90222. awayX = 0;
  90223. }
  90224. if (this._positionY < this.borderLimit + globalViewport.y) {
  90225. awayY = this.borderLimit + globalViewport.y - this._positionY;
  90226. }
  90227. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  90228. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  90229. }
  90230. else {
  90231. awayY = 0;
  90232. }
  90233. var away = (awayX > awayY) ? awayX : awayY;
  90234. away -= this.viewportBorder;
  90235. if (away > this.borderLimit) {
  90236. away = this.borderLimit;
  90237. }
  90238. var intensity = 1.0 - (away / this.borderLimit);
  90239. if (intensity < 0) {
  90240. return false;
  90241. }
  90242. if (intensity > 1.0) {
  90243. intensity = 1.0;
  90244. }
  90245. if (this.viewportBorder > 0) {
  90246. globalViewport.x += this.viewportBorder;
  90247. globalViewport.y += this.viewportBorder;
  90248. globalViewport.width -= this.viewportBorder * 2;
  90249. globalViewport.height -= this.viewportBorder * 2;
  90250. this._positionX -= this.viewportBorder;
  90251. this._positionY -= this.viewportBorder;
  90252. }
  90253. // Position
  90254. var centerX = globalViewport.x + globalViewport.width / 2;
  90255. var centerY = globalViewport.y + globalViewport.height / 2;
  90256. var distX = centerX - this._positionX;
  90257. var distY = centerY - this._positionY;
  90258. // Effects
  90259. engine.enableEffect(this._effect);
  90260. engine.setState(false);
  90261. engine.setDepthBuffer(false);
  90262. // VBOs
  90263. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  90264. // Flares
  90265. for (var index = 0; index < this.lensFlares.length; index++) {
  90266. var flare = this.lensFlares[index];
  90267. engine.setAlphaMode(flare.alphaMode);
  90268. var x = centerX - (distX * flare.position);
  90269. var y = centerY - (distY * flare.position);
  90270. var cw = flare.size;
  90271. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  90272. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  90273. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  90274. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  90275. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  90276. // Texture
  90277. this._effect.setTexture("textureSampler", flare.texture);
  90278. // Color
  90279. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  90280. // Draw order
  90281. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  90282. }
  90283. engine.setDepthBuffer(true);
  90284. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  90285. return true;
  90286. };
  90287. LensFlareSystem.prototype.dispose = function () {
  90288. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  90289. if (vertexBuffer) {
  90290. vertexBuffer.dispose();
  90291. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  90292. }
  90293. if (this._indexBuffer) {
  90294. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  90295. this._indexBuffer = null;
  90296. }
  90297. while (this.lensFlares.length) {
  90298. this.lensFlares[0].dispose();
  90299. }
  90300. // Remove from scene
  90301. var index = this._scene.lensFlareSystems.indexOf(this);
  90302. this._scene.lensFlareSystems.splice(index, 1);
  90303. };
  90304. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  90305. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  90306. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  90307. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  90308. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  90309. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  90310. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  90311. var parsedFlare = parsedLensFlareSystem.flares[index];
  90312. BABYLON.LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  90313. }
  90314. return lensFlareSystem;
  90315. };
  90316. LensFlareSystem.prototype.serialize = function () {
  90317. var serializationObject = {};
  90318. serializationObject.id = this.id;
  90319. serializationObject.name = this.name;
  90320. serializationObject.emitterId = this.getEmitter().id;
  90321. serializationObject.borderLimit = this.borderLimit;
  90322. serializationObject.flares = [];
  90323. for (var index = 0; index < this.lensFlares.length; index++) {
  90324. var flare = this.lensFlares[index];
  90325. serializationObject.flares.push({
  90326. size: flare.size,
  90327. position: flare.position,
  90328. color: flare.color.asArray(),
  90329. textureName: BABYLON.Tools.GetFilename(flare.texture ? flare.texture.name : "")
  90330. });
  90331. }
  90332. return serializationObject;
  90333. };
  90334. return LensFlareSystem;
  90335. }());
  90336. BABYLON.LensFlareSystem = LensFlareSystem;
  90337. })(BABYLON || (BABYLON = {}));
  90338. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  90339. var BABYLON;
  90340. (function (BABYLON) {
  90341. /**
  90342. * This is a holder class for the physics joint created by the physics plugin.
  90343. * It holds a set of functions to control the underlying joint.
  90344. */
  90345. var PhysicsJoint = /** @class */ (function () {
  90346. function PhysicsJoint(type, jointData) {
  90347. this.type = type;
  90348. this.jointData = jointData;
  90349. jointData.nativeParams = jointData.nativeParams || {};
  90350. }
  90351. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  90352. get: function () {
  90353. return this._physicsJoint;
  90354. },
  90355. set: function (newJoint) {
  90356. if (this._physicsJoint) {
  90357. //remove from the wolrd
  90358. }
  90359. this._physicsJoint = newJoint;
  90360. },
  90361. enumerable: true,
  90362. configurable: true
  90363. });
  90364. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  90365. set: function (physicsPlugin) {
  90366. this._physicsPlugin = physicsPlugin;
  90367. },
  90368. enumerable: true,
  90369. configurable: true
  90370. });
  90371. /**
  90372. * Execute a function that is physics-plugin specific.
  90373. * @param {Function} func the function that will be executed.
  90374. * It accepts two parameters: the physics world and the physics joint.
  90375. */
  90376. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  90377. func(this._physicsPlugin.world, this._physicsJoint);
  90378. };
  90379. //TODO check if the native joints are the same
  90380. //Joint Types
  90381. PhysicsJoint.DistanceJoint = 0;
  90382. PhysicsJoint.HingeJoint = 1;
  90383. PhysicsJoint.BallAndSocketJoint = 2;
  90384. PhysicsJoint.WheelJoint = 3;
  90385. PhysicsJoint.SliderJoint = 4;
  90386. //OIMO
  90387. PhysicsJoint.PrismaticJoint = 5;
  90388. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  90389. PhysicsJoint.UniversalJoint = 6;
  90390. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  90391. //Cannon
  90392. //Similar to a Ball-Joint. Different in params
  90393. PhysicsJoint.PointToPointJoint = 8;
  90394. //Cannon only at the moment
  90395. PhysicsJoint.SpringJoint = 9;
  90396. PhysicsJoint.LockJoint = 10;
  90397. return PhysicsJoint;
  90398. }());
  90399. BABYLON.PhysicsJoint = PhysicsJoint;
  90400. /**
  90401. * A class representing a physics distance joint.
  90402. */
  90403. var DistanceJoint = /** @class */ (function (_super) {
  90404. __extends(DistanceJoint, _super);
  90405. function DistanceJoint(jointData) {
  90406. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  90407. }
  90408. /**
  90409. * Update the predefined distance.
  90410. */
  90411. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  90412. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  90413. };
  90414. return DistanceJoint;
  90415. }(PhysicsJoint));
  90416. BABYLON.DistanceJoint = DistanceJoint;
  90417. var MotorEnabledJoint = /** @class */ (function (_super) {
  90418. __extends(MotorEnabledJoint, _super);
  90419. function MotorEnabledJoint(type, jointData) {
  90420. return _super.call(this, type, jointData) || this;
  90421. }
  90422. /**
  90423. * Set the motor values.
  90424. * Attention, this function is plugin specific. Engines won't react 100% the same.
  90425. * @param {number} force the force to apply
  90426. * @param {number} maxForce max force for this motor.
  90427. */
  90428. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  90429. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  90430. };
  90431. /**
  90432. * Set the motor's limits.
  90433. * Attention, this function is plugin specific. Engines won't react 100% the same.
  90434. */
  90435. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  90436. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  90437. };
  90438. return MotorEnabledJoint;
  90439. }(PhysicsJoint));
  90440. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  90441. /**
  90442. * This class represents a single hinge physics joint
  90443. */
  90444. var HingeJoint = /** @class */ (function (_super) {
  90445. __extends(HingeJoint, _super);
  90446. function HingeJoint(jointData) {
  90447. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  90448. }
  90449. /**
  90450. * Set the motor values.
  90451. * Attention, this function is plugin specific. Engines won't react 100% the same.
  90452. * @param {number} force the force to apply
  90453. * @param {number} maxForce max force for this motor.
  90454. */
  90455. HingeJoint.prototype.setMotor = function (force, maxForce) {
  90456. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  90457. };
  90458. /**
  90459. * Set the motor's limits.
  90460. * Attention, this function is plugin specific. Engines won't react 100% the same.
  90461. */
  90462. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  90463. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  90464. };
  90465. return HingeJoint;
  90466. }(MotorEnabledJoint));
  90467. BABYLON.HingeJoint = HingeJoint;
  90468. /**
  90469. * This class represents a dual hinge physics joint (same as wheel joint)
  90470. */
  90471. var Hinge2Joint = /** @class */ (function (_super) {
  90472. __extends(Hinge2Joint, _super);
  90473. function Hinge2Joint(jointData) {
  90474. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  90475. }
  90476. /**
  90477. * Set the motor values.
  90478. * Attention, this function is plugin specific. Engines won't react 100% the same.
  90479. * @param {number} force the force to apply
  90480. * @param {number} maxForce max force for this motor.
  90481. * @param {motorIndex} the motor's index, 0 or 1.
  90482. */
  90483. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  90484. if (motorIndex === void 0) { motorIndex = 0; }
  90485. this._physicsPlugin.setMotor(this, force || 0, maxForce, motorIndex);
  90486. };
  90487. /**
  90488. * Set the motor limits.
  90489. * Attention, this function is plugin specific. Engines won't react 100% the same.
  90490. * @param {number} upperLimit the upper limit
  90491. * @param {number} lowerLimit lower limit
  90492. * @param {motorIndex} the motor's index, 0 or 1.
  90493. */
  90494. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  90495. if (motorIndex === void 0) { motorIndex = 0; }
  90496. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  90497. };
  90498. return Hinge2Joint;
  90499. }(MotorEnabledJoint));
  90500. BABYLON.Hinge2Joint = Hinge2Joint;
  90501. })(BABYLON || (BABYLON = {}));
  90502. //# sourceMappingURL=babylon.physicsJoint.js.map
  90503. var BABYLON;
  90504. (function (BABYLON) {
  90505. var PhysicsImpostor = /** @class */ (function () {
  90506. function PhysicsImpostor(object, type, _options, _scene) {
  90507. if (_options === void 0) { _options = { mass: 0 }; }
  90508. var _this = this;
  90509. this.object = object;
  90510. this.type = type;
  90511. this._options = _options;
  90512. this._scene = _scene;
  90513. this._bodyUpdateRequired = false;
  90514. this._onBeforePhysicsStepCallbacks = new Array();
  90515. this._onAfterPhysicsStepCallbacks = new Array();
  90516. this._onPhysicsCollideCallbacks = [];
  90517. this._deltaPosition = BABYLON.Vector3.Zero();
  90518. this._isDisposed = false;
  90519. //temp variables for parent rotation calculations
  90520. //private _mats: Array<Matrix> = [new Matrix(), new Matrix()];
  90521. this._tmpQuat = new BABYLON.Quaternion();
  90522. this._tmpQuat2 = new BABYLON.Quaternion();
  90523. /**
  90524. * this function is executed by the physics engine.
  90525. */
  90526. this.beforeStep = function () {
  90527. if (!_this._physicsEngine) {
  90528. return;
  90529. }
  90530. _this.object.translate(_this._deltaPosition, -1);
  90531. _this._deltaRotationConjugated && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this.object.rotationQuaternion);
  90532. _this.object.computeWorldMatrix(false);
  90533. if (_this.object.parent && _this.object.rotationQuaternion) {
  90534. _this.getParentsRotation();
  90535. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this._tmpQuat);
  90536. }
  90537. else {
  90538. _this._tmpQuat.copyFrom(_this.object.rotationQuaternion || new BABYLON.Quaternion());
  90539. }
  90540. if (!_this._options.disableBidirectionalTransformation) {
  90541. _this.object.rotationQuaternion && _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, /*bInfo.boundingBox.centerWorld*/ _this.object.getAbsolutePivotPoint(), _this._tmpQuat);
  90542. }
  90543. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  90544. func(_this);
  90545. });
  90546. };
  90547. /**
  90548. * this function is executed by the physics engine.
  90549. */
  90550. this.afterStep = function () {
  90551. if (!_this._physicsEngine) {
  90552. return;
  90553. }
  90554. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  90555. func(_this);
  90556. });
  90557. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  90558. // object has now its world rotation. needs to be converted to local.
  90559. if (_this.object.parent && _this.object.rotationQuaternion) {
  90560. _this.getParentsRotation();
  90561. _this._tmpQuat.conjugateInPlace();
  90562. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this.object.rotationQuaternion);
  90563. }
  90564. // take the position set and make it the absolute position of this object.
  90565. _this.object.setAbsolutePosition(_this.object.position);
  90566. _this._deltaRotation && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotation, _this.object.rotationQuaternion);
  90567. _this.object.translate(_this._deltaPosition, 1);
  90568. };
  90569. /**
  90570. * Legacy collision detection event support
  90571. */
  90572. this.onCollideEvent = null;
  90573. //event and body object due to cannon's event-based architecture.
  90574. this.onCollide = function (e) {
  90575. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent) {
  90576. return;
  90577. }
  90578. if (!_this._physicsEngine) {
  90579. return;
  90580. }
  90581. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  90582. if (otherImpostor) {
  90583. // Legacy collision detection event support
  90584. if (_this.onCollideEvent) {
  90585. _this.onCollideEvent(_this, otherImpostor);
  90586. }
  90587. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  90588. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  90589. }).forEach(function (obj) {
  90590. obj.callback(_this, otherImpostor);
  90591. });
  90592. }
  90593. };
  90594. //sanity check!
  90595. if (!this.object) {
  90596. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  90597. return;
  90598. }
  90599. //legacy support for old syntax.
  90600. if (!this._scene && object.getScene) {
  90601. this._scene = object.getScene();
  90602. }
  90603. if (!this._scene) {
  90604. return;
  90605. }
  90606. this._physicsEngine = this._scene.getPhysicsEngine();
  90607. if (!this._physicsEngine) {
  90608. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  90609. }
  90610. else {
  90611. //set the object's quaternion, if not set
  90612. if (!this.object.rotationQuaternion) {
  90613. if (this.object.rotation) {
  90614. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  90615. }
  90616. else {
  90617. this.object.rotationQuaternion = new BABYLON.Quaternion();
  90618. }
  90619. }
  90620. //default options params
  90621. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  90622. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  90623. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  90624. this._joints = [];
  90625. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  90626. if (!this.object.parent || this._options.ignoreParent) {
  90627. this._init();
  90628. }
  90629. else if (this.object.parent.physicsImpostor) {
  90630. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  90631. }
  90632. }
  90633. }
  90634. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  90635. get: function () {
  90636. return this._isDisposed;
  90637. },
  90638. enumerable: true,
  90639. configurable: true
  90640. });
  90641. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  90642. get: function () {
  90643. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;
  90644. },
  90645. set: function (value) {
  90646. this.setMass(value);
  90647. },
  90648. enumerable: true,
  90649. configurable: true
  90650. });
  90651. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  90652. get: function () {
  90653. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;
  90654. },
  90655. set: function (value) {
  90656. if (!this._physicsEngine) {
  90657. return;
  90658. }
  90659. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  90660. },
  90661. enumerable: true,
  90662. configurable: true
  90663. });
  90664. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  90665. get: function () {
  90666. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0;
  90667. },
  90668. set: function (value) {
  90669. if (!this._physicsEngine) {
  90670. return;
  90671. }
  90672. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  90673. },
  90674. enumerable: true,
  90675. configurable: true
  90676. });
  90677. /**
  90678. * This function will completly initialize this impostor.
  90679. * It will create a new body - but only if this mesh has no parent.
  90680. * If it has, this impostor will not be used other than to define the impostor
  90681. * of the child mesh.
  90682. * @hidden
  90683. */
  90684. PhysicsImpostor.prototype._init = function () {
  90685. if (!this._physicsEngine) {
  90686. return;
  90687. }
  90688. this._physicsEngine.removeImpostor(this);
  90689. this.physicsBody = null;
  90690. this._parent = this._parent || this._getPhysicsParent();
  90691. if (!this._isDisposed && (!this.parent || this._options.ignoreParent)) {
  90692. this._physicsEngine.addImpostor(this);
  90693. }
  90694. };
  90695. PhysicsImpostor.prototype._getPhysicsParent = function () {
  90696. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  90697. var parentMesh = this.object.parent;
  90698. return parentMesh.physicsImpostor;
  90699. }
  90700. return null;
  90701. };
  90702. /**
  90703. * Should a new body be generated.
  90704. */
  90705. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  90706. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  90707. };
  90708. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  90709. this.forceUpdate();
  90710. };
  90711. /**
  90712. * Force a regeneration of this or the parent's impostor's body.
  90713. * Use under cautious - This will remove all joints already implemented.
  90714. */
  90715. PhysicsImpostor.prototype.forceUpdate = function () {
  90716. this._init();
  90717. if (this.parent && !this._options.ignoreParent) {
  90718. this.parent.forceUpdate();
  90719. }
  90720. };
  90721. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  90722. /*public get mesh(): AbstractMesh {
  90723. return this._mesh;
  90724. }*/
  90725. /**
  90726. * Gets the body that holds this impostor. Either its own, or its parent.
  90727. */
  90728. get: function () {
  90729. return (this._parent && !this._options.ignoreParent) ? this._parent.physicsBody : this._physicsBody;
  90730. },
  90731. /**
  90732. * Set the physics body. Used mainly by the physics engine/plugin
  90733. */
  90734. set: function (physicsBody) {
  90735. if (this._physicsBody && this._physicsEngine) {
  90736. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  90737. }
  90738. this._physicsBody = physicsBody;
  90739. this.resetUpdateFlags();
  90740. },
  90741. enumerable: true,
  90742. configurable: true
  90743. });
  90744. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  90745. get: function () {
  90746. return !this._options.ignoreParent && this._parent ? this._parent : null;
  90747. },
  90748. set: function (value) {
  90749. this._parent = value;
  90750. },
  90751. enumerable: true,
  90752. configurable: true
  90753. });
  90754. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  90755. this._bodyUpdateRequired = false;
  90756. };
  90757. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  90758. if (this.object.getBoundingInfo) {
  90759. var q = this.object.rotationQuaternion;
  90760. //reset rotation
  90761. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  90762. //calculate the world matrix with no rotation
  90763. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  90764. var boundingInfo = this.object.getBoundingInfo();
  90765. var size = boundingInfo.boundingBox.extendSizeWorld.scale(2);
  90766. //bring back the rotation
  90767. this.object.rotationQuaternion = q;
  90768. //calculate the world matrix with the new rotation
  90769. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  90770. return size;
  90771. }
  90772. else {
  90773. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  90774. }
  90775. };
  90776. PhysicsImpostor.prototype.getObjectCenter = function () {
  90777. if (this.object.getBoundingInfo) {
  90778. var boundingInfo = this.object.getBoundingInfo();
  90779. return boundingInfo.boundingBox.centerWorld;
  90780. }
  90781. else {
  90782. return this.object.position;
  90783. }
  90784. };
  90785. /**
  90786. * Get a specific parametes from the options parameter.
  90787. */
  90788. PhysicsImpostor.prototype.getParam = function (paramName) {
  90789. return this._options[paramName];
  90790. };
  90791. /**
  90792. * Sets a specific parameter in the options given to the physics plugin
  90793. */
  90794. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  90795. this._options[paramName] = value;
  90796. this._bodyUpdateRequired = true;
  90797. };
  90798. /**
  90799. * Specifically change the body's mass option. Won't recreate the physics body object
  90800. */
  90801. PhysicsImpostor.prototype.setMass = function (mass) {
  90802. if (this.getParam("mass") !== mass) {
  90803. this.setParam("mass", mass);
  90804. }
  90805. if (this._physicsEngine) {
  90806. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  90807. }
  90808. };
  90809. PhysicsImpostor.prototype.getLinearVelocity = function () {
  90810. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : BABYLON.Vector3.Zero();
  90811. };
  90812. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  90813. if (this._physicsEngine) {
  90814. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  90815. }
  90816. };
  90817. PhysicsImpostor.prototype.getAngularVelocity = function () {
  90818. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : BABYLON.Vector3.Zero();
  90819. };
  90820. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  90821. if (this._physicsEngine) {
  90822. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  90823. }
  90824. };
  90825. /**
  90826. * Execute a function with the physics plugin native code.
  90827. * Provide a function the will have two variables - the world object and the physics body object.
  90828. */
  90829. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  90830. if (this._physicsEngine) {
  90831. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  90832. }
  90833. };
  90834. /**
  90835. * Register a function that will be executed before the physics world is stepping forward.
  90836. */
  90837. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  90838. this._onBeforePhysicsStepCallbacks.push(func);
  90839. };
  90840. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  90841. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  90842. if (index > -1) {
  90843. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  90844. }
  90845. else {
  90846. BABYLON.Tools.Warn("Function to remove was not found");
  90847. }
  90848. };
  90849. /**
  90850. * Register a function that will be executed after the physics step
  90851. */
  90852. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  90853. this._onAfterPhysicsStepCallbacks.push(func);
  90854. };
  90855. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  90856. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  90857. if (index > -1) {
  90858. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  90859. }
  90860. else {
  90861. BABYLON.Tools.Warn("Function to remove was not found");
  90862. }
  90863. };
  90864. /**
  90865. * register a function that will be executed when this impostor collides against a different body.
  90866. */
  90867. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  90868. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  90869. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  90870. };
  90871. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  90872. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  90873. var index = -1;
  90874. var found = this._onPhysicsCollideCallbacks.some(function (cbDef, idx) {
  90875. if (cbDef.callback === func && cbDef.otherImpostors.length === collidedAgainstList.length) {
  90876. // chcek the arrays match
  90877. var sameList = cbDef.otherImpostors.every(function (impostor) {
  90878. return collidedAgainstList.indexOf(impostor) > -1;
  90879. });
  90880. if (sameList) {
  90881. index = idx;
  90882. }
  90883. return sameList;
  90884. }
  90885. return false;
  90886. });
  90887. if (found) {
  90888. this._onPhysicsCollideCallbacks.splice(index, 1);
  90889. }
  90890. else {
  90891. BABYLON.Tools.Warn("Function to remove was not found");
  90892. }
  90893. };
  90894. PhysicsImpostor.prototype.getParentsRotation = function () {
  90895. var parent = this.object.parent;
  90896. this._tmpQuat.copyFromFloats(0, 0, 0, 1);
  90897. while (parent) {
  90898. if (parent.rotationQuaternion) {
  90899. this._tmpQuat2.copyFrom(parent.rotationQuaternion);
  90900. }
  90901. else {
  90902. BABYLON.Quaternion.RotationYawPitchRollToRef(parent.rotation.y, parent.rotation.x, parent.rotation.z, this._tmpQuat2);
  90903. }
  90904. this._tmpQuat.multiplyToRef(this._tmpQuat2, this._tmpQuat);
  90905. parent = parent.parent;
  90906. }
  90907. return this._tmpQuat;
  90908. };
  90909. /**
  90910. * Apply a force
  90911. */
  90912. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  90913. if (this._physicsEngine) {
  90914. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  90915. }
  90916. return this;
  90917. };
  90918. /**
  90919. * Apply an impulse
  90920. */
  90921. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  90922. if (this._physicsEngine) {
  90923. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  90924. }
  90925. return this;
  90926. };
  90927. /**
  90928. * A help function to create a joint.
  90929. */
  90930. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  90931. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  90932. this.addJoint(otherImpostor, joint);
  90933. return this;
  90934. };
  90935. /**
  90936. * Add a joint to this impostor with a different impostor.
  90937. */
  90938. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  90939. this._joints.push({
  90940. otherImpostor: otherImpostor,
  90941. joint: joint
  90942. });
  90943. if (this._physicsEngine) {
  90944. this._physicsEngine.addJoint(this, otherImpostor, joint);
  90945. }
  90946. return this;
  90947. };
  90948. /**
  90949. * Will keep this body still, in a sleep mode.
  90950. */
  90951. PhysicsImpostor.prototype.sleep = function () {
  90952. if (this._physicsEngine) {
  90953. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  90954. }
  90955. return this;
  90956. };
  90957. /**
  90958. * Wake the body up.
  90959. */
  90960. PhysicsImpostor.prototype.wakeUp = function () {
  90961. if (this._physicsEngine) {
  90962. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  90963. }
  90964. return this;
  90965. };
  90966. PhysicsImpostor.prototype.clone = function (newObject) {
  90967. if (!newObject)
  90968. return null;
  90969. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  90970. };
  90971. PhysicsImpostor.prototype.dispose = function ( /*disposeChildren: boolean = true*/) {
  90972. var _this = this;
  90973. //no dispose if no physics engine is available.
  90974. if (!this._physicsEngine) {
  90975. return;
  90976. }
  90977. this._joints.forEach(function (j) {
  90978. if (_this._physicsEngine) {
  90979. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  90980. }
  90981. });
  90982. //dispose the physics body
  90983. this._physicsEngine.removeImpostor(this);
  90984. if (this.parent) {
  90985. this.parent.forceUpdate();
  90986. }
  90987. else {
  90988. /*this._object.getChildMeshes().forEach(function(mesh) {
  90989. if (mesh.physicsImpostor) {
  90990. if (disposeChildren) {
  90991. mesh.physicsImpostor.dispose();
  90992. mesh.physicsImpostor = null;
  90993. }
  90994. }
  90995. })*/
  90996. }
  90997. this._isDisposed = true;
  90998. };
  90999. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  91000. this._deltaPosition.copyFrom(position);
  91001. };
  91002. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  91003. if (!this._deltaRotation) {
  91004. this._deltaRotation = new BABYLON.Quaternion();
  91005. }
  91006. this._deltaRotation.copyFrom(rotation);
  91007. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  91008. };
  91009. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  91010. if (this._physicsEngine) {
  91011. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  91012. }
  91013. return this;
  91014. };
  91015. PhysicsImpostor.prototype.getRadius = function () {
  91016. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0;
  91017. };
  91018. /**
  91019. * Sync a bone with this impostor
  91020. * @param bone The bone to sync to the impostor.
  91021. * @param boneMesh The mesh that the bone is influencing.
  91022. * @param jointPivot The pivot of the joint / bone in local space.
  91023. * @param distToJoint Optional distance from the impostor to the joint.
  91024. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  91025. */
  91026. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  91027. var tempVec = PhysicsImpostor._tmpVecs[0];
  91028. var mesh = this.object;
  91029. if (mesh.rotationQuaternion) {
  91030. if (adjustRotation) {
  91031. var tempQuat = PhysicsImpostor._tmpQuat;
  91032. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  91033. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  91034. }
  91035. else {
  91036. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  91037. }
  91038. }
  91039. tempVec.x = 0;
  91040. tempVec.y = 0;
  91041. tempVec.z = 0;
  91042. if (jointPivot) {
  91043. tempVec.x = jointPivot.x;
  91044. tempVec.y = jointPivot.y;
  91045. tempVec.z = jointPivot.z;
  91046. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  91047. if (distToJoint === undefined || distToJoint === null) {
  91048. distToJoint = jointPivot.length();
  91049. }
  91050. tempVec.x *= distToJoint;
  91051. tempVec.y *= distToJoint;
  91052. tempVec.z *= distToJoint;
  91053. }
  91054. if (bone.getParent()) {
  91055. tempVec.addInPlace(mesh.getAbsolutePosition());
  91056. bone.setAbsolutePosition(tempVec, boneMesh);
  91057. }
  91058. else {
  91059. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  91060. boneMesh.position.x -= tempVec.x;
  91061. boneMesh.position.y -= tempVec.y;
  91062. boneMesh.position.z -= tempVec.z;
  91063. }
  91064. };
  91065. /**
  91066. * Sync impostor to a bone
  91067. * @param bone The bone that the impostor will be synced to.
  91068. * @param boneMesh The mesh that the bone is influencing.
  91069. * @param jointPivot The pivot of the joint / bone in local space.
  91070. * @param distToJoint Optional distance from the impostor to the joint.
  91071. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  91072. * @param boneAxis Optional vector3 axis the bone is aligned with
  91073. */
  91074. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  91075. var mesh = this.object;
  91076. if (mesh.rotationQuaternion) {
  91077. if (adjustRotation) {
  91078. var tempQuat = PhysicsImpostor._tmpQuat;
  91079. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  91080. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  91081. }
  91082. else {
  91083. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  91084. }
  91085. }
  91086. var pos = PhysicsImpostor._tmpVecs[0];
  91087. var boneDir = PhysicsImpostor._tmpVecs[1];
  91088. if (!boneAxis) {
  91089. boneAxis = PhysicsImpostor._tmpVecs[2];
  91090. boneAxis.x = 0;
  91091. boneAxis.y = 1;
  91092. boneAxis.z = 0;
  91093. }
  91094. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  91095. bone.getAbsolutePositionToRef(boneMesh, pos);
  91096. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  91097. distToJoint = jointPivot.length();
  91098. }
  91099. if (distToJoint !== undefined && distToJoint !== null) {
  91100. pos.x += boneDir.x * distToJoint;
  91101. pos.y += boneDir.y * distToJoint;
  91102. pos.z += boneDir.z * distToJoint;
  91103. }
  91104. mesh.setAbsolutePosition(pos);
  91105. };
  91106. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  91107. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  91108. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  91109. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  91110. //Impostor types
  91111. PhysicsImpostor.NoImpostor = 0;
  91112. PhysicsImpostor.SphereImpostor = 1;
  91113. PhysicsImpostor.BoxImpostor = 2;
  91114. PhysicsImpostor.PlaneImpostor = 3;
  91115. PhysicsImpostor.MeshImpostor = 4;
  91116. PhysicsImpostor.CylinderImpostor = 7;
  91117. PhysicsImpostor.ParticleImpostor = 8;
  91118. PhysicsImpostor.HeightmapImpostor = 9;
  91119. return PhysicsImpostor;
  91120. }());
  91121. BABYLON.PhysicsImpostor = PhysicsImpostor;
  91122. })(BABYLON || (BABYLON = {}));
  91123. //# sourceMappingURL=babylon.physicsImpostor.js.map
  91124. var BABYLON;
  91125. (function (BABYLON) {
  91126. /**
  91127. * Class used to control physics engine
  91128. * @see http://doc.babylonjs.com/how_to/using_the_physics_engine
  91129. */
  91130. var PhysicsEngine = /** @class */ (function () {
  91131. /**
  91132. * Creates a new Physics Engine
  91133. * @param gravity defines the gravity vector used by the simulation
  91134. * @param _physicsPlugin defines the plugin to use (CannonJS by default)
  91135. */
  91136. function PhysicsEngine(gravity, _physicsPlugin) {
  91137. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  91138. this._physicsPlugin = _physicsPlugin;
  91139. this._impostors = [];
  91140. this._joints = [];
  91141. if (!this._physicsPlugin.isSupported()) {
  91142. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  91143. + "Please make sure it is included.");
  91144. }
  91145. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  91146. this.setGravity(gravity);
  91147. this.setTimeStep();
  91148. }
  91149. /**
  91150. * Sets the gravity vector used by the simulation
  91151. * @param gravity defines the gravity vector to use
  91152. */
  91153. PhysicsEngine.prototype.setGravity = function (gravity) {
  91154. this.gravity = gravity;
  91155. this._physicsPlugin.setGravity(this.gravity);
  91156. };
  91157. /**
  91158. * Set the time step of the physics engine.
  91159. * Default is 1/60.
  91160. * To slow it down, enter 1/600 for example.
  91161. * To speed it up, 1/30
  91162. * @param newTimeStep defines the new timestep to apply to this world.
  91163. */
  91164. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  91165. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  91166. this._physicsPlugin.setTimeStep(newTimeStep);
  91167. };
  91168. /**
  91169. * Get the time step of the physics engine.
  91170. * @returns the current time step
  91171. */
  91172. PhysicsEngine.prototype.getTimeStep = function () {
  91173. return this._physicsPlugin.getTimeStep();
  91174. };
  91175. /**
  91176. * Release all resources
  91177. */
  91178. PhysicsEngine.prototype.dispose = function () {
  91179. this._impostors.forEach(function (impostor) {
  91180. impostor.dispose();
  91181. });
  91182. this._physicsPlugin.dispose();
  91183. };
  91184. /**
  91185. * Gets the name of the current physics plugin
  91186. * @returns the name of the plugin
  91187. */
  91188. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  91189. return this._physicsPlugin.name;
  91190. };
  91191. /**
  91192. * Adding a new impostor for the impostor tracking.
  91193. * This will be done by the impostor itself.
  91194. * @param impostor the impostor to add
  91195. */
  91196. PhysicsEngine.prototype.addImpostor = function (impostor) {
  91197. impostor.uniqueId = this._impostors.push(impostor);
  91198. //if no parent, generate the body
  91199. if (!impostor.parent) {
  91200. this._physicsPlugin.generatePhysicsBody(impostor);
  91201. }
  91202. };
  91203. /**
  91204. * Remove an impostor from the engine.
  91205. * This impostor and its mesh will not longer be updated by the physics engine.
  91206. * @param impostor the impostor to remove
  91207. */
  91208. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  91209. var index = this._impostors.indexOf(impostor);
  91210. if (index > -1) {
  91211. var removed = this._impostors.splice(index, 1);
  91212. //Is it needed?
  91213. if (removed.length) {
  91214. //this will also remove it from the world.
  91215. removed[0].physicsBody = null;
  91216. }
  91217. }
  91218. };
  91219. /**
  91220. * Add a joint to the physics engine
  91221. * @param mainImpostor defines the main impostor to which the joint is added.
  91222. * @param connectedImpostor defines the impostor that is connected to the main impostor using this joint
  91223. * @param joint defines the joint that will connect both impostors.
  91224. */
  91225. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  91226. var impostorJoint = {
  91227. mainImpostor: mainImpostor,
  91228. connectedImpostor: connectedImpostor,
  91229. joint: joint
  91230. };
  91231. joint.physicsPlugin = this._physicsPlugin;
  91232. this._joints.push(impostorJoint);
  91233. this._physicsPlugin.generateJoint(impostorJoint);
  91234. };
  91235. /**
  91236. * Removes a joint from the simulation
  91237. * @param mainImpostor defines the impostor used with the joint
  91238. * @param connectedImpostor defines the other impostor connected to the main one by the joint
  91239. * @param joint defines the joint to remove
  91240. */
  91241. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  91242. var matchingJoints = this._joints.filter(function (impostorJoint) {
  91243. return (impostorJoint.connectedImpostor === connectedImpostor
  91244. && impostorJoint.joint === joint
  91245. && impostorJoint.mainImpostor === mainImpostor);
  91246. });
  91247. if (matchingJoints.length) {
  91248. this._physicsPlugin.removeJoint(matchingJoints[0]);
  91249. //TODO remove it from the list as well
  91250. }
  91251. };
  91252. /**
  91253. * Called by the scene. No need to call it.
  91254. * @param delta defines the timespam between frames
  91255. */
  91256. PhysicsEngine.prototype._step = function (delta) {
  91257. var _this = this;
  91258. //check if any mesh has no body / requires an update
  91259. this._impostors.forEach(function (impostor) {
  91260. if (impostor.isBodyInitRequired()) {
  91261. _this._physicsPlugin.generatePhysicsBody(impostor);
  91262. }
  91263. });
  91264. if (delta > 0.1) {
  91265. delta = 0.1;
  91266. }
  91267. else if (delta <= 0) {
  91268. delta = 1.0 / 60.0;
  91269. }
  91270. this._physicsPlugin.executeStep(delta, this._impostors);
  91271. };
  91272. /**
  91273. * Gets the current plugin used to run the simulation
  91274. * @returns current plugin
  91275. */
  91276. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  91277. return this._physicsPlugin;
  91278. };
  91279. /**
  91280. * Gets the list of physic impostors
  91281. * @returns an array of PhysicsImpostor
  91282. */
  91283. PhysicsEngine.prototype.getImpostors = function () {
  91284. return this._impostors;
  91285. };
  91286. /**
  91287. * Gets the impostor for a physics enabled object
  91288. * @param object defines the object impersonated by the impostor
  91289. * @returns the PhysicsImpostor or null if not found
  91290. */
  91291. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  91292. for (var i = 0; i < this._impostors.length; ++i) {
  91293. if (this._impostors[i].object === object) {
  91294. return this._impostors[i];
  91295. }
  91296. }
  91297. return null;
  91298. };
  91299. /**
  91300. * Gets the impostor for a physics body object
  91301. * @param body defines physics body used by the impostor
  91302. * @returns the PhysicsImpostor or null if not found
  91303. */
  91304. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  91305. for (var i = 0; i < this._impostors.length; ++i) {
  91306. if (this._impostors[i].physicsBody === body) {
  91307. return this._impostors[i];
  91308. }
  91309. }
  91310. return null;
  91311. };
  91312. /**
  91313. * Global value used to control the smallest number supported by the simulation
  91314. */
  91315. PhysicsEngine.Epsilon = 0.001;
  91316. return PhysicsEngine;
  91317. }());
  91318. BABYLON.PhysicsEngine = PhysicsEngine;
  91319. })(BABYLON || (BABYLON = {}));
  91320. //# sourceMappingURL=babylon.physicsEngine.js.map
  91321. var BABYLON;
  91322. (function (BABYLON) {
  91323. var PhysicsHelper = /** @class */ (function () {
  91324. function PhysicsHelper(scene) {
  91325. this._scene = scene;
  91326. this._physicsEngine = this._scene.getPhysicsEngine();
  91327. if (!this._physicsEngine) {
  91328. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you can use the methods.');
  91329. }
  91330. }
  91331. /**
  91332. * @param {Vector3} origin the origin of the explosion
  91333. * @param {number} radius the explosion radius
  91334. * @param {number} strength the explosion strength
  91335. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  91336. */
  91337. PhysicsHelper.prototype.applyRadialExplosionImpulse = function (origin, radius, strength, falloff) {
  91338. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  91339. if (!this._physicsEngine) {
  91340. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call this method.');
  91341. return null;
  91342. }
  91343. var impostors = this._physicsEngine.getImpostors();
  91344. if (impostors.length === 0) {
  91345. return null;
  91346. }
  91347. var event = new PhysicsRadialExplosionEvent(this._scene);
  91348. impostors.forEach(function (impostor) {
  91349. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  91350. if (!impostorForceAndContactPoint) {
  91351. return;
  91352. }
  91353. impostor.applyImpulse(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  91354. });
  91355. event.dispose(false);
  91356. return event;
  91357. };
  91358. /**
  91359. * @param {Vector3} origin the origin of the explosion
  91360. * @param {number} radius the explosion radius
  91361. * @param {number} strength the explosion strength
  91362. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  91363. */
  91364. PhysicsHelper.prototype.applyRadialExplosionForce = function (origin, radius, strength, falloff) {
  91365. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  91366. if (!this._physicsEngine) {
  91367. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  91368. return null;
  91369. }
  91370. var impostors = this._physicsEngine.getImpostors();
  91371. if (impostors.length === 0) {
  91372. return null;
  91373. }
  91374. var event = new PhysicsRadialExplosionEvent(this._scene);
  91375. impostors.forEach(function (impostor) {
  91376. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  91377. if (!impostorForceAndContactPoint) {
  91378. return;
  91379. }
  91380. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  91381. });
  91382. event.dispose(false);
  91383. return event;
  91384. };
  91385. /**
  91386. * @param {Vector3} origin the origin of the explosion
  91387. * @param {number} radius the explosion radius
  91388. * @param {number} strength the explosion strength
  91389. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  91390. */
  91391. PhysicsHelper.prototype.gravitationalField = function (origin, radius, strength, falloff) {
  91392. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  91393. if (!this._physicsEngine) {
  91394. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  91395. return null;
  91396. }
  91397. var impostors = this._physicsEngine.getImpostors();
  91398. if (impostors.length === 0) {
  91399. return null;
  91400. }
  91401. var event = new PhysicsGravitationalFieldEvent(this, this._scene, origin, radius, strength, falloff);
  91402. event.dispose(false);
  91403. return event;
  91404. };
  91405. /**
  91406. * @param {Vector3} origin the origin of the updraft
  91407. * @param {number} radius the radius of the updraft
  91408. * @param {number} strength the strength of the updraft
  91409. * @param {number} height the height of the updraft
  91410. * @param {PhysicsUpdraftMode} updraftMode possible options: Center & Perpendicular. Defaults to Center
  91411. */
  91412. PhysicsHelper.prototype.updraft = function (origin, radius, strength, height, updraftMode) {
  91413. if (updraftMode === void 0) { updraftMode = PhysicsUpdraftMode.Center; }
  91414. if (!this._physicsEngine) {
  91415. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  91416. return null;
  91417. }
  91418. if (this._physicsEngine.getImpostors().length === 0) {
  91419. return null;
  91420. }
  91421. var event = new PhysicsUpdraftEvent(this._scene, origin, radius, strength, height, updraftMode);
  91422. event.dispose(false);
  91423. return event;
  91424. };
  91425. /**
  91426. * @param {Vector3} origin the of the vortex
  91427. * @param {number} radius the radius of the vortex
  91428. * @param {number} strength the strength of the vortex
  91429. * @param {number} height the height of the vortex
  91430. */
  91431. PhysicsHelper.prototype.vortex = function (origin, radius, strength, height) {
  91432. if (!this._physicsEngine) {
  91433. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  91434. return null;
  91435. }
  91436. if (this._physicsEngine.getImpostors().length === 0) {
  91437. return null;
  91438. }
  91439. var event = new PhysicsVortexEvent(this._scene, origin, radius, strength, height);
  91440. event.dispose(false);
  91441. return event;
  91442. };
  91443. return PhysicsHelper;
  91444. }());
  91445. BABYLON.PhysicsHelper = PhysicsHelper;
  91446. /***** Radial explosion *****/
  91447. var PhysicsRadialExplosionEvent = /** @class */ (function () {
  91448. function PhysicsRadialExplosionEvent(scene) {
  91449. this._sphereOptions = { segments: 32, diameter: 1 }; // TODO: make configurable
  91450. this._rays = [];
  91451. this._dataFetched = false; // check if the data has been fetched. If not, do cleanup
  91452. this._scene = scene;
  91453. }
  91454. /**
  91455. * Returns the data related to the radial explosion event (sphere & rays).
  91456. * @returns {PhysicsRadialExplosionEventData}
  91457. */
  91458. PhysicsRadialExplosionEvent.prototype.getData = function () {
  91459. this._dataFetched = true;
  91460. return {
  91461. sphere: this._sphere,
  91462. rays: this._rays,
  91463. };
  91464. };
  91465. /**
  91466. * Returns the force and contact point of the impostor or false, if the impostor is not affected by the force/impulse.
  91467. * @param impostor
  91468. * @param {Vector3} origin the origin of the explosion
  91469. * @param {number} radius the explosion radius
  91470. * @param {number} strength the explosion strength
  91471. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear
  91472. * @returns {Nullable<PhysicsForceAndContactPoint>}
  91473. */
  91474. PhysicsRadialExplosionEvent.prototype.getImpostorForceAndContactPoint = function (impostor, origin, radius, strength, falloff) {
  91475. if (impostor.mass === 0) {
  91476. return null;
  91477. }
  91478. if (!this._intersectsWithSphere(impostor, origin, radius)) {
  91479. return null;
  91480. }
  91481. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  91482. return null;
  91483. }
  91484. var impostorObjectCenter = impostor.getObjectCenter();
  91485. var direction = impostorObjectCenter.subtract(origin);
  91486. var ray = new BABYLON.Ray(origin, direction, radius);
  91487. this._rays.push(ray);
  91488. var hit = ray.intersectsMesh(impostor.object);
  91489. var contactPoint = hit.pickedPoint;
  91490. if (!contactPoint) {
  91491. return null;
  91492. }
  91493. var distanceFromOrigin = BABYLON.Vector3.Distance(origin, contactPoint);
  91494. if (distanceFromOrigin > radius) {
  91495. return null;
  91496. }
  91497. var multiplier = falloff === PhysicsRadialImpulseFalloff.Constant
  91498. ? strength
  91499. : strength * (1 - (distanceFromOrigin / radius));
  91500. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  91501. return { force: force, contactPoint: contactPoint };
  91502. };
  91503. /**
  91504. * Disposes the sphere.
  91505. * @param {bolean} force
  91506. */
  91507. PhysicsRadialExplosionEvent.prototype.dispose = function (force) {
  91508. var _this = this;
  91509. if (force === void 0) { force = true; }
  91510. if (force) {
  91511. this._sphere.dispose();
  91512. }
  91513. else {
  91514. setTimeout(function () {
  91515. if (!_this._dataFetched) {
  91516. _this._sphere.dispose();
  91517. }
  91518. }, 0);
  91519. }
  91520. };
  91521. /*** Helpers ***/
  91522. PhysicsRadialExplosionEvent.prototype._prepareSphere = function () {
  91523. if (!this._sphere) {
  91524. this._sphere = BABYLON.MeshBuilder.CreateSphere("radialExplosionEventSphere", this._sphereOptions, this._scene);
  91525. this._sphere.isVisible = false;
  91526. }
  91527. };
  91528. PhysicsRadialExplosionEvent.prototype._intersectsWithSphere = function (impostor, origin, radius) {
  91529. var impostorObject = impostor.object;
  91530. this._prepareSphere();
  91531. this._sphere.position = origin;
  91532. this._sphere.scaling = new BABYLON.Vector3(radius * 2, radius * 2, radius * 2);
  91533. this._sphere._updateBoundingInfo();
  91534. this._sphere.computeWorldMatrix(true);
  91535. return this._sphere.intersectsMesh(impostorObject, true);
  91536. };
  91537. return PhysicsRadialExplosionEvent;
  91538. }());
  91539. BABYLON.PhysicsRadialExplosionEvent = PhysicsRadialExplosionEvent;
  91540. /***** Gravitational Field *****/
  91541. var PhysicsGravitationalFieldEvent = /** @class */ (function () {
  91542. function PhysicsGravitationalFieldEvent(physicsHelper, scene, origin, radius, strength, falloff) {
  91543. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  91544. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  91545. this._physicsHelper = physicsHelper;
  91546. this._scene = scene;
  91547. this._origin = origin;
  91548. this._radius = radius;
  91549. this._strength = strength;
  91550. this._falloff = falloff;
  91551. this._tickCallback = this._tick.bind(this);
  91552. }
  91553. /**
  91554. * Returns the data related to the gravitational field event (sphere).
  91555. * @returns {PhysicsGravitationalFieldEventData}
  91556. */
  91557. PhysicsGravitationalFieldEvent.prototype.getData = function () {
  91558. this._dataFetched = true;
  91559. return {
  91560. sphere: this._sphere,
  91561. };
  91562. };
  91563. /**
  91564. * Enables the gravitational field.
  91565. */
  91566. PhysicsGravitationalFieldEvent.prototype.enable = function () {
  91567. this._tickCallback.call(this);
  91568. this._scene.registerBeforeRender(this._tickCallback);
  91569. };
  91570. /**
  91571. * Disables the gravitational field.
  91572. */
  91573. PhysicsGravitationalFieldEvent.prototype.disable = function () {
  91574. this._scene.unregisterBeforeRender(this._tickCallback);
  91575. };
  91576. /**
  91577. * Disposes the sphere.
  91578. * @param {bolean} force
  91579. */
  91580. PhysicsGravitationalFieldEvent.prototype.dispose = function (force) {
  91581. var _this = this;
  91582. if (force === void 0) { force = true; }
  91583. if (force) {
  91584. this._sphere.dispose();
  91585. }
  91586. else {
  91587. setTimeout(function () {
  91588. if (!_this._dataFetched) {
  91589. _this._sphere.dispose();
  91590. }
  91591. }, 0);
  91592. }
  91593. };
  91594. PhysicsGravitationalFieldEvent.prototype._tick = function () {
  91595. // Since the params won't change, we fetch the event only once
  91596. if (this._sphere) {
  91597. this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  91598. }
  91599. else {
  91600. var radialExplosionEvent = this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  91601. if (radialExplosionEvent) {
  91602. this._sphere = radialExplosionEvent.getData().sphere.clone('radialExplosionEventSphereClone');
  91603. }
  91604. }
  91605. };
  91606. return PhysicsGravitationalFieldEvent;
  91607. }());
  91608. BABYLON.PhysicsGravitationalFieldEvent = PhysicsGravitationalFieldEvent;
  91609. /***** Updraft *****/
  91610. var PhysicsUpdraftEvent = /** @class */ (function () {
  91611. function PhysicsUpdraftEvent(_scene, _origin, _radius, _strength, _height, _updraftMode) {
  91612. this._scene = _scene;
  91613. this._origin = _origin;
  91614. this._radius = _radius;
  91615. this._strength = _strength;
  91616. this._height = _height;
  91617. this._updraftMode = _updraftMode;
  91618. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  91619. this._originDirection = BABYLON.Vector3.Zero(); // used if the updraftMode is perpendicular
  91620. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  91621. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  91622. this._physicsEngine = this._scene.getPhysicsEngine();
  91623. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  91624. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  91625. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  91626. this._originDirection = this._origin.subtract(this._originTop).normalize();
  91627. }
  91628. this._tickCallback = this._tick.bind(this);
  91629. }
  91630. /**
  91631. * Returns the data related to the updraft event (cylinder).
  91632. * @returns {PhysicsUpdraftEventData}
  91633. */
  91634. PhysicsUpdraftEvent.prototype.getData = function () {
  91635. this._dataFetched = true;
  91636. return {
  91637. cylinder: this._cylinder,
  91638. };
  91639. };
  91640. /**
  91641. * Enables the updraft.
  91642. */
  91643. PhysicsUpdraftEvent.prototype.enable = function () {
  91644. this._tickCallback.call(this);
  91645. this._scene.registerBeforeRender(this._tickCallback);
  91646. };
  91647. /**
  91648. * Disables the cortex.
  91649. */
  91650. PhysicsUpdraftEvent.prototype.disable = function () {
  91651. this._scene.unregisterBeforeRender(this._tickCallback);
  91652. };
  91653. /**
  91654. * Disposes the sphere.
  91655. * @param {bolean} force
  91656. */
  91657. PhysicsUpdraftEvent.prototype.dispose = function (force) {
  91658. var _this = this;
  91659. if (force === void 0) { force = true; }
  91660. if (force) {
  91661. this._cylinder.dispose();
  91662. }
  91663. else {
  91664. setTimeout(function () {
  91665. if (!_this._dataFetched) {
  91666. _this._cylinder.dispose();
  91667. }
  91668. }, 0);
  91669. }
  91670. };
  91671. PhysicsUpdraftEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  91672. if (impostor.mass === 0) {
  91673. return null;
  91674. }
  91675. if (!this._intersectsWithCylinder(impostor)) {
  91676. return null;
  91677. }
  91678. var impostorObjectCenter = impostor.getObjectCenter();
  91679. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  91680. var direction = this._originDirection;
  91681. }
  91682. else {
  91683. var direction = impostorObjectCenter.subtract(this._originTop);
  91684. }
  91685. var multiplier = this._strength * -1;
  91686. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  91687. return { force: force, contactPoint: impostorObjectCenter };
  91688. };
  91689. PhysicsUpdraftEvent.prototype._tick = function () {
  91690. var _this = this;
  91691. this._physicsEngine.getImpostors().forEach(function (impostor) {
  91692. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  91693. if (!impostorForceAndContactPoint) {
  91694. return;
  91695. }
  91696. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  91697. });
  91698. };
  91699. /*** Helpers ***/
  91700. PhysicsUpdraftEvent.prototype._prepareCylinder = function () {
  91701. if (!this._cylinder) {
  91702. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("updraftEventCylinder", {
  91703. height: this._height,
  91704. diameter: this._radius * 2,
  91705. }, this._scene);
  91706. this._cylinder.isVisible = false;
  91707. }
  91708. };
  91709. PhysicsUpdraftEvent.prototype._intersectsWithCylinder = function (impostor) {
  91710. var impostorObject = impostor.object;
  91711. this._prepareCylinder();
  91712. this._cylinder.position = this._cylinderPosition;
  91713. return this._cylinder.intersectsMesh(impostorObject, true);
  91714. };
  91715. return PhysicsUpdraftEvent;
  91716. }());
  91717. BABYLON.PhysicsUpdraftEvent = PhysicsUpdraftEvent;
  91718. /***** Vortex *****/
  91719. var PhysicsVortexEvent = /** @class */ (function () {
  91720. function PhysicsVortexEvent(_scene, _origin, _radius, _strength, _height) {
  91721. this._scene = _scene;
  91722. this._origin = _origin;
  91723. this._radius = _radius;
  91724. this._strength = _strength;
  91725. this._height = _height;
  91726. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  91727. this._centripetalForceThreshold = 0.7; // at which distance, relative to the radius the centripetal forces should kick in
  91728. this._updraftMultiplier = 0.02;
  91729. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  91730. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  91731. this._physicsEngine = this._scene.getPhysicsEngine();
  91732. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  91733. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  91734. this._tickCallback = this._tick.bind(this);
  91735. }
  91736. /**
  91737. * Returns the data related to the vortex event (cylinder).
  91738. * @returns {PhysicsVortexEventData}
  91739. */
  91740. PhysicsVortexEvent.prototype.getData = function () {
  91741. this._dataFetched = true;
  91742. return {
  91743. cylinder: this._cylinder,
  91744. };
  91745. };
  91746. /**
  91747. * Enables the vortex.
  91748. */
  91749. PhysicsVortexEvent.prototype.enable = function () {
  91750. this._tickCallback.call(this);
  91751. this._scene.registerBeforeRender(this._tickCallback);
  91752. };
  91753. /**
  91754. * Disables the cortex.
  91755. */
  91756. PhysicsVortexEvent.prototype.disable = function () {
  91757. this._scene.unregisterBeforeRender(this._tickCallback);
  91758. };
  91759. /**
  91760. * Disposes the sphere.
  91761. * @param {bolean} force
  91762. */
  91763. PhysicsVortexEvent.prototype.dispose = function (force) {
  91764. var _this = this;
  91765. if (force === void 0) { force = true; }
  91766. if (force) {
  91767. this._cylinder.dispose();
  91768. }
  91769. else {
  91770. setTimeout(function () {
  91771. if (!_this._dataFetched) {
  91772. _this._cylinder.dispose();
  91773. }
  91774. }, 0);
  91775. }
  91776. };
  91777. PhysicsVortexEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  91778. if (impostor.mass === 0) {
  91779. return null;
  91780. }
  91781. if (!this._intersectsWithCylinder(impostor)) {
  91782. return null;
  91783. }
  91784. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  91785. return null;
  91786. }
  91787. var impostorObjectCenter = impostor.getObjectCenter();
  91788. 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)
  91789. var originToImpostorDirection = impostorObjectCenter.subtract(originOnPlane);
  91790. var ray = new BABYLON.Ray(originOnPlane, originToImpostorDirection, this._radius);
  91791. var hit = ray.intersectsMesh(impostor.object);
  91792. var contactPoint = hit.pickedPoint;
  91793. if (!contactPoint) {
  91794. return null;
  91795. }
  91796. var absoluteDistanceFromOrigin = hit.distance / this._radius;
  91797. var perpendicularDirection = BABYLON.Vector3.Cross(originOnPlane, impostorObjectCenter).normalize();
  91798. var directionToOrigin = contactPoint.normalize();
  91799. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  91800. directionToOrigin = directionToOrigin.negate();
  91801. }
  91802. // TODO: find a more physically based solution
  91803. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  91804. var forceX = directionToOrigin.x * this._strength / 8;
  91805. var forceY = directionToOrigin.y * this._updraftMultiplier;
  91806. var forceZ = directionToOrigin.z * this._strength / 8;
  91807. }
  91808. else {
  91809. var forceX = (perpendicularDirection.x + directionToOrigin.x) / 2;
  91810. var forceY = this._originTop.y * this._updraftMultiplier;
  91811. var forceZ = (perpendicularDirection.z + directionToOrigin.z) / 2;
  91812. }
  91813. var force = new BABYLON.Vector3(forceX, forceY, forceZ);
  91814. force = force.multiplyByFloats(this._strength, this._strength, this._strength);
  91815. return { force: force, contactPoint: impostorObjectCenter };
  91816. };
  91817. PhysicsVortexEvent.prototype._tick = function () {
  91818. var _this = this;
  91819. this._physicsEngine.getImpostors().forEach(function (impostor) {
  91820. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  91821. if (!impostorForceAndContactPoint) {
  91822. return;
  91823. }
  91824. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  91825. });
  91826. };
  91827. /*** Helpers ***/
  91828. PhysicsVortexEvent.prototype._prepareCylinder = function () {
  91829. if (!this._cylinder) {
  91830. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("vortexEventCylinder", {
  91831. height: this._height,
  91832. diameter: this._radius * 2,
  91833. }, this._scene);
  91834. this._cylinder.isVisible = false;
  91835. }
  91836. };
  91837. PhysicsVortexEvent.prototype._intersectsWithCylinder = function (impostor) {
  91838. var impostorObject = impostor.object;
  91839. this._prepareCylinder();
  91840. this._cylinder.position = this._cylinderPosition;
  91841. return this._cylinder.intersectsMesh(impostorObject, true);
  91842. };
  91843. return PhysicsVortexEvent;
  91844. }());
  91845. BABYLON.PhysicsVortexEvent = PhysicsVortexEvent;
  91846. /***** Enums *****/
  91847. /**
  91848. * The strenght of the force in correspondence to the distance of the affected object
  91849. */
  91850. var PhysicsRadialImpulseFalloff;
  91851. (function (PhysicsRadialImpulseFalloff) {
  91852. /** Defines that impulse is constant in strength across it's whole radius */
  91853. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Constant"] = 0] = "Constant";
  91854. /** DEfines that impulse gets weaker if it's further from the origin */
  91855. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Linear"] = 1] = "Linear";
  91856. })(PhysicsRadialImpulseFalloff = BABYLON.PhysicsRadialImpulseFalloff || (BABYLON.PhysicsRadialImpulseFalloff = {}));
  91857. /**
  91858. * The strenght of the force in correspondence to the distance of the affected object
  91859. */
  91860. var PhysicsUpdraftMode;
  91861. (function (PhysicsUpdraftMode) {
  91862. /** Defines that the upstream forces will pull towards the top center of the cylinder */
  91863. PhysicsUpdraftMode[PhysicsUpdraftMode["Center"] = 0] = "Center";
  91864. /** Defines that once a impostor is inside the cylinder, it will shoot out perpendicular from the ground of the cylinder */
  91865. PhysicsUpdraftMode[PhysicsUpdraftMode["Perpendicular"] = 1] = "Perpendicular";
  91866. })(PhysicsUpdraftMode = BABYLON.PhysicsUpdraftMode || (BABYLON.PhysicsUpdraftMode = {}));
  91867. })(BABYLON || (BABYLON = {}));
  91868. //# sourceMappingURL=babylon.physicsHelper.js.map
  91869. var BABYLON;
  91870. (function (BABYLON) {
  91871. /** @hidden */
  91872. var CannonJSPlugin = /** @class */ (function () {
  91873. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  91874. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  91875. if (iterations === void 0) { iterations = 10; }
  91876. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  91877. this.name = "CannonJSPlugin";
  91878. this._physicsMaterials = new Array();
  91879. this._fixedTimeStep = 1 / 60;
  91880. //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html
  91881. this.BJSCANNON = CANNON;
  91882. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  91883. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  91884. this._tmpPosition = BABYLON.Vector3.Zero();
  91885. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  91886. this._tmpUnityRotation = new BABYLON.Quaternion();
  91887. if (!this.isSupported()) {
  91888. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  91889. return;
  91890. }
  91891. this._extendNamespace();
  91892. this.world = new this.BJSCANNON.World();
  91893. this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
  91894. this.world.solver.iterations = iterations;
  91895. }
  91896. CannonJSPlugin.prototype.setGravity = function (gravity) {
  91897. this.world.gravity.copy(gravity);
  91898. };
  91899. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  91900. this._fixedTimeStep = timeStep;
  91901. };
  91902. CannonJSPlugin.prototype.getTimeStep = function () {
  91903. return this._fixedTimeStep;
  91904. };
  91905. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  91906. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  91907. };
  91908. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  91909. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  91910. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  91911. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  91912. };
  91913. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  91914. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  91915. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  91916. impostor.physicsBody.applyForce(impulse, worldPoint);
  91917. };
  91918. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  91919. //parent-child relationship. Does this impostor has a parent impostor?
  91920. if (impostor.parent) {
  91921. if (impostor.physicsBody) {
  91922. this.removePhysicsBody(impostor);
  91923. //TODO is that needed?
  91924. impostor.forceUpdate();
  91925. }
  91926. return;
  91927. }
  91928. //should a new body be created for this impostor?
  91929. if (impostor.isBodyInitRequired()) {
  91930. var shape = this._createShape(impostor);
  91931. //unregister events, if body is being changed
  91932. var oldBody = impostor.physicsBody;
  91933. if (oldBody) {
  91934. this.removePhysicsBody(impostor);
  91935. }
  91936. //create the body and material
  91937. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  91938. var bodyCreationObject = {
  91939. mass: impostor.getParam("mass"),
  91940. material: material
  91941. };
  91942. // A simple extend, in case native options were used.
  91943. var nativeOptions = impostor.getParam("nativeOptions");
  91944. for (var key in nativeOptions) {
  91945. if (nativeOptions.hasOwnProperty(key)) {
  91946. bodyCreationObject[key] = nativeOptions[key];
  91947. }
  91948. }
  91949. impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
  91950. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  91951. this.world.addEventListener("preStep", impostor.beforeStep);
  91952. this.world.addEventListener("postStep", impostor.afterStep);
  91953. impostor.physicsBody.addShape(shape);
  91954. this.world.add(impostor.physicsBody);
  91955. //try to keep the body moving in the right direction by taking old properties.
  91956. //Should be tested!
  91957. if (oldBody) {
  91958. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  91959. impostor.physicsBody[param].copy(oldBody[param]);
  91960. });
  91961. }
  91962. this._processChildMeshes(impostor);
  91963. }
  91964. //now update the body's transformation
  91965. this._updatePhysicsBodyTransformation(impostor);
  91966. };
  91967. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  91968. var _this = this;
  91969. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
  91970. var currentRotation = mainImpostor.object.rotationQuaternion;
  91971. if (meshChildren.length) {
  91972. var processMesh = function (localPosition, mesh) {
  91973. if (!currentRotation || !mesh.rotationQuaternion) {
  91974. return;
  91975. }
  91976. var childImpostor = mesh.getPhysicsImpostor();
  91977. if (childImpostor) {
  91978. var parent = childImpostor.parent;
  91979. if (parent !== mainImpostor) {
  91980. var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());
  91981. var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation));
  91982. if (childImpostor.physicsBody) {
  91983. _this.removePhysicsBody(childImpostor);
  91984. childImpostor.physicsBody = null;
  91985. }
  91986. childImpostor.parent = mainImpostor;
  91987. childImpostor.resetUpdateFlags();
  91988. 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));
  91989. //Add the mass of the children.
  91990. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  91991. }
  91992. }
  91993. currentRotation.multiplyInPlace(mesh.rotationQuaternion);
  91994. mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition()));
  91995. };
  91996. meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
  91997. }
  91998. };
  91999. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  92000. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  92001. this.world.removeEventListener("preStep", impostor.beforeStep);
  92002. this.world.removeEventListener("postStep", impostor.afterStep);
  92003. this.world.remove(impostor.physicsBody);
  92004. };
  92005. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  92006. var mainBody = impostorJoint.mainImpostor.physicsBody;
  92007. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  92008. if (!mainBody || !connectedBody) {
  92009. return;
  92010. }
  92011. var constraint;
  92012. var jointData = impostorJoint.joint.jointData;
  92013. //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html
  92014. var constraintData = {
  92015. pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
  92016. pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
  92017. axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
  92018. axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
  92019. maxForce: jointData.nativeParams.maxForce,
  92020. collideConnected: !!jointData.collision
  92021. };
  92022. switch (impostorJoint.joint.type) {
  92023. case BABYLON.PhysicsJoint.HingeJoint:
  92024. case BABYLON.PhysicsJoint.Hinge2Joint:
  92025. constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  92026. break;
  92027. case BABYLON.PhysicsJoint.DistanceJoint:
  92028. constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  92029. break;
  92030. case BABYLON.PhysicsJoint.SpringJoint:
  92031. var springData = jointData;
  92032. constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
  92033. restLength: springData.length,
  92034. stiffness: springData.stiffness,
  92035. damping: springData.damping,
  92036. localAnchorA: constraintData.pivotA,
  92037. localAnchorB: constraintData.pivotB
  92038. });
  92039. break;
  92040. case BABYLON.PhysicsJoint.LockJoint:
  92041. constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
  92042. break;
  92043. case BABYLON.PhysicsJoint.PointToPointJoint:
  92044. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  92045. default:
  92046. constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  92047. break;
  92048. }
  92049. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  92050. constraint.collideConnected = !!jointData.collision;
  92051. impostorJoint.joint.physicsJoint = constraint;
  92052. //don't add spring as constraint, as it is not one.
  92053. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  92054. this.world.addConstraint(constraint);
  92055. }
  92056. else {
  92057. impostorJoint.joint.jointData.forceApplicationCallback = impostorJoint.joint.jointData.forceApplicationCallback || function () {
  92058. constraint.applyForce();
  92059. };
  92060. impostorJoint.mainImpostor.registerAfterPhysicsStep(impostorJoint.joint.jointData.forceApplicationCallback);
  92061. }
  92062. };
  92063. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  92064. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  92065. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  92066. }
  92067. else {
  92068. impostorJoint.mainImpostor.unregisterAfterPhysicsStep(impostorJoint.joint.jointData.forceApplicationCallback);
  92069. }
  92070. };
  92071. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  92072. var index;
  92073. var mat;
  92074. for (index = 0; index < this._physicsMaterials.length; index++) {
  92075. mat = this._physicsMaterials[index];
  92076. if (mat.friction === friction && mat.restitution === restitution) {
  92077. return mat;
  92078. }
  92079. }
  92080. var currentMat = new this.BJSCANNON.Material(name);
  92081. currentMat.friction = friction;
  92082. currentMat.restitution = restitution;
  92083. this._physicsMaterials.push(currentMat);
  92084. return currentMat;
  92085. };
  92086. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  92087. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  92088. };
  92089. CannonJSPlugin.prototype._createShape = function (impostor) {
  92090. var object = impostor.object;
  92091. var returnValue;
  92092. var extendSize = impostor.getObjectExtendSize();
  92093. switch (impostor.type) {
  92094. case BABYLON.PhysicsImpostor.SphereImpostor:
  92095. var radiusX = extendSize.x;
  92096. var radiusY = extendSize.y;
  92097. var radiusZ = extendSize.z;
  92098. returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  92099. break;
  92100. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  92101. case BABYLON.PhysicsImpostor.CylinderImpostor:
  92102. returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  92103. break;
  92104. case BABYLON.PhysicsImpostor.BoxImpostor:
  92105. var box = extendSize.scale(0.5);
  92106. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  92107. break;
  92108. case BABYLON.PhysicsImpostor.PlaneImpostor:
  92109. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  92110. returnValue = new this.BJSCANNON.Plane();
  92111. break;
  92112. case BABYLON.PhysicsImpostor.MeshImpostor:
  92113. // should transform the vertex data to world coordinates!!
  92114. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  92115. var rawFaces = object.getIndices ? object.getIndices() : [];
  92116. if (!rawVerts)
  92117. return;
  92118. // get only scale! so the object could transform correctly.
  92119. var oldPosition = object.position.clone();
  92120. var oldRotation = object.rotation && object.rotation.clone();
  92121. var oldQuaternion = object.rotationQuaternion && object.rotationQuaternion.clone();
  92122. object.position.copyFromFloats(0, 0, 0);
  92123. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  92124. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  92125. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  92126. var transform = object.computeWorldMatrix(true);
  92127. // convert rawVerts to object space
  92128. var temp = new Array();
  92129. var index;
  92130. for (index = 0; index < rawVerts.length; index += 3) {
  92131. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(rawVerts, index), transform).toArray(temp, index);
  92132. }
  92133. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  92134. returnValue = new this.BJSCANNON.Trimesh(temp, rawFaces);
  92135. //now set back the transformation!
  92136. object.position.copyFrom(oldPosition);
  92137. oldRotation && object.rotation && object.rotation.copyFrom(oldRotation);
  92138. oldQuaternion && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion);
  92139. break;
  92140. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  92141. var oldPosition2 = object.position.clone();
  92142. var oldRotation2 = object.rotation && object.rotation.clone();
  92143. var oldQuaternion2 = object.rotationQuaternion && object.rotationQuaternion.clone();
  92144. object.position.copyFromFloats(0, 0, 0);
  92145. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  92146. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  92147. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  92148. object.rotationQuaternion && object.rotationQuaternion.multiplyInPlace(this._minus90X);
  92149. returnValue = this._createHeightmap(object);
  92150. object.position.copyFrom(oldPosition2);
  92151. oldRotation2 && object.rotation && object.rotation.copyFrom(oldRotation2);
  92152. oldQuaternion2 && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion2);
  92153. object.computeWorldMatrix(true);
  92154. break;
  92155. case BABYLON.PhysicsImpostor.ParticleImpostor:
  92156. returnValue = new this.BJSCANNON.Particle();
  92157. break;
  92158. }
  92159. return returnValue;
  92160. };
  92161. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  92162. var pos = (object.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  92163. var transform = object.computeWorldMatrix(true);
  92164. // convert rawVerts to object space
  92165. var temp = new Array();
  92166. var index;
  92167. for (index = 0; index < pos.length; index += 3) {
  92168. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(pos, index), transform).toArray(temp, index);
  92169. }
  92170. pos = temp;
  92171. var matrix = new Array();
  92172. //For now pointDepth will not be used and will be automatically calculated.
  92173. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  92174. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  92175. var boundingInfo = object.getBoundingInfo();
  92176. var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.y);
  92177. var minY = boundingInfo.boundingBox.extendSizeWorld.z;
  92178. var elementSize = dim * 2 / arraySize;
  92179. for (var i = 0; i < pos.length; i = i + 3) {
  92180. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  92181. var z = Math.round(((pos[i + 1]) / elementSize - arraySize / 2) * -1);
  92182. var y = -pos[i + 2] + minY;
  92183. if (!matrix[x]) {
  92184. matrix[x] = [];
  92185. }
  92186. if (!matrix[x][z]) {
  92187. matrix[x][z] = y;
  92188. }
  92189. matrix[x][z] = Math.max(y, matrix[x][z]);
  92190. }
  92191. for (var x = 0; x <= arraySize; ++x) {
  92192. if (!matrix[x]) {
  92193. var loc = 1;
  92194. while (!matrix[(x + loc) % arraySize]) {
  92195. loc++;
  92196. }
  92197. matrix[x] = matrix[(x + loc) % arraySize].slice();
  92198. //console.log("missing x", x);
  92199. }
  92200. for (var z = 0; z <= arraySize; ++z) {
  92201. if (!matrix[x][z]) {
  92202. var loc = 1;
  92203. var newValue;
  92204. while (newValue === undefined) {
  92205. newValue = matrix[x][(z + loc++) % arraySize];
  92206. }
  92207. matrix[x][z] = newValue;
  92208. }
  92209. }
  92210. }
  92211. var shape = new this.BJSCANNON.Heightfield(matrix, {
  92212. elementSize: elementSize
  92213. });
  92214. //For future reference, needed for body transformation
  92215. shape.minY = minY;
  92216. return shape;
  92217. };
  92218. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  92219. var object = impostor.object;
  92220. //make sure it is updated...
  92221. object.computeWorldMatrix && object.computeWorldMatrix(true);
  92222. // The delta between the mesh position and the mesh bounding box center
  92223. var bInfo = object.getBoundingInfo();
  92224. if (!bInfo)
  92225. return;
  92226. var center = impostor.getObjectCenter();
  92227. //m.getAbsolutePosition().subtract(m.getBoundingInfo().boundingBox.centerWorld)
  92228. this._tmpDeltaPosition.copyFrom(object.getAbsolutePivotPoint().subtract(center));
  92229. this._tmpDeltaPosition.divideInPlace(impostor.object.scaling);
  92230. this._tmpPosition.copyFrom(center);
  92231. var quaternion = object.rotationQuaternion;
  92232. if (!quaternion) {
  92233. return;
  92234. }
  92235. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  92236. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  92237. //-90 DEG in X, precalculated
  92238. quaternion = quaternion.multiply(this._minus90X);
  92239. //Invert! (Precalculated, 90 deg in X)
  92240. //No need to clone. this will never change.
  92241. impostor.setDeltaRotation(this._plus90X);
  92242. }
  92243. //If it is a heightfield, if should be centered.
  92244. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  92245. var mesh = object;
  92246. var boundingInfo = mesh.getBoundingInfo();
  92247. //calculate the correct body position:
  92248. var rotationQuaternion = mesh.rotationQuaternion;
  92249. mesh.rotationQuaternion = this._tmpUnityRotation;
  92250. mesh.computeWorldMatrix(true);
  92251. //get original center with no rotation
  92252. var c = center.clone();
  92253. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  92254. //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
  92255. var p = BABYLON.Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z);
  92256. mesh.setPreTransformMatrix(p);
  92257. mesh.computeWorldMatrix(true);
  92258. //calculate the translation
  92259. var translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  92260. this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z);
  92261. //add it inverted to the delta
  92262. this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c));
  92263. this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y;
  92264. //rotation is back
  92265. mesh.rotationQuaternion = rotationQuaternion;
  92266. mesh.setPreTransformMatrix(oldPivot);
  92267. mesh.computeWorldMatrix(true);
  92268. }
  92269. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  92270. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  92271. //this._tmpPosition.copyFrom(object.position);
  92272. }
  92273. impostor.setDeltaPosition(this._tmpDeltaPosition);
  92274. //Now update the impostor object
  92275. impostor.physicsBody.position.copy(this._tmpPosition);
  92276. impostor.physicsBody.quaternion.copy(quaternion);
  92277. };
  92278. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  92279. impostor.object.position.copyFrom(impostor.physicsBody.position);
  92280. if (impostor.object.rotationQuaternion) {
  92281. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  92282. }
  92283. };
  92284. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  92285. impostor.physicsBody.position.copy(newPosition);
  92286. impostor.physicsBody.quaternion.copy(newRotation);
  92287. };
  92288. CannonJSPlugin.prototype.isSupported = function () {
  92289. return this.BJSCANNON !== undefined;
  92290. };
  92291. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  92292. impostor.physicsBody.velocity.copy(velocity);
  92293. };
  92294. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  92295. impostor.physicsBody.angularVelocity.copy(velocity);
  92296. };
  92297. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  92298. var v = impostor.physicsBody.velocity;
  92299. if (!v) {
  92300. return null;
  92301. }
  92302. return new BABYLON.Vector3(v.x, v.y, v.z);
  92303. };
  92304. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  92305. var v = impostor.physicsBody.angularVelocity;
  92306. if (!v) {
  92307. return null;
  92308. }
  92309. return new BABYLON.Vector3(v.x, v.y, v.z);
  92310. };
  92311. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  92312. impostor.physicsBody.mass = mass;
  92313. impostor.physicsBody.updateMassProperties();
  92314. };
  92315. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  92316. return impostor.physicsBody.mass;
  92317. };
  92318. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  92319. return impostor.physicsBody.material.friction;
  92320. };
  92321. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  92322. impostor.physicsBody.material.friction = friction;
  92323. };
  92324. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  92325. return impostor.physicsBody.material.restitution;
  92326. };
  92327. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  92328. impostor.physicsBody.material.restitution = restitution;
  92329. };
  92330. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  92331. impostor.physicsBody.sleep();
  92332. };
  92333. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  92334. impostor.physicsBody.wakeUp();
  92335. };
  92336. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  92337. joint.physicsJoint.distance = maxDistance;
  92338. };
  92339. // private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  92340. // if (!motorIndex) {
  92341. // joint.physicsJoint.enableMotor();
  92342. // }
  92343. // }
  92344. // private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  92345. // if (!motorIndex) {
  92346. // joint.physicsJoint.disableMotor();
  92347. // }
  92348. // }
  92349. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  92350. if (!motorIndex) {
  92351. joint.physicsJoint.enableMotor();
  92352. joint.physicsJoint.setMotorSpeed(speed);
  92353. if (maxForce) {
  92354. this.setLimit(joint, maxForce);
  92355. }
  92356. }
  92357. };
  92358. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  92359. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  92360. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  92361. };
  92362. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  92363. var body = impostor.physicsBody;
  92364. mesh.position.x = body.position.x;
  92365. mesh.position.y = body.position.y;
  92366. mesh.position.z = body.position.z;
  92367. if (mesh.rotationQuaternion) {
  92368. mesh.rotationQuaternion.x = body.quaternion.x;
  92369. mesh.rotationQuaternion.y = body.quaternion.y;
  92370. mesh.rotationQuaternion.z = body.quaternion.z;
  92371. mesh.rotationQuaternion.w = body.quaternion.w;
  92372. }
  92373. };
  92374. CannonJSPlugin.prototype.getRadius = function (impostor) {
  92375. var shape = impostor.physicsBody.shapes[0];
  92376. return shape.boundingSphereRadius;
  92377. };
  92378. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  92379. var shape = impostor.physicsBody.shapes[0];
  92380. result.x = shape.halfExtents.x * 2;
  92381. result.y = shape.halfExtents.y * 2;
  92382. result.z = shape.halfExtents.z * 2;
  92383. };
  92384. CannonJSPlugin.prototype.dispose = function () {
  92385. };
  92386. CannonJSPlugin.prototype._extendNamespace = function () {
  92387. //this will force cannon to execute at least one step when using interpolation
  92388. var step_tmp1 = new this.BJSCANNON.Vec3();
  92389. var Engine = this.BJSCANNON;
  92390. this.BJSCANNON.World.prototype.step = function (dt, timeSinceLastCalled, maxSubSteps) {
  92391. maxSubSteps = maxSubSteps || 10;
  92392. timeSinceLastCalled = timeSinceLastCalled || 0;
  92393. if (timeSinceLastCalled === 0) {
  92394. this.internalStep(dt);
  92395. this.time += dt;
  92396. }
  92397. else {
  92398. var internalSteps = Math.floor((this.time + timeSinceLastCalled) / dt) - Math.floor(this.time / dt);
  92399. internalSteps = Math.min(internalSteps, maxSubSteps) || 1;
  92400. var t0 = performance.now();
  92401. for (var i = 0; i !== internalSteps; i++) {
  92402. this.internalStep(dt);
  92403. if (performance.now() - t0 > dt * 1000) {
  92404. break;
  92405. }
  92406. }
  92407. this.time += timeSinceLastCalled;
  92408. var h = this.time % dt;
  92409. var h_div_dt = h / dt;
  92410. var interpvelo = step_tmp1;
  92411. var bodies = this.bodies;
  92412. for (var j = 0; j !== bodies.length; j++) {
  92413. var b = bodies[j];
  92414. if (b.type !== Engine.Body.STATIC && b.sleepState !== Engine.Body.SLEEPING) {
  92415. b.position.vsub(b.previousPosition, interpvelo);
  92416. interpvelo.scale(h_div_dt, interpvelo);
  92417. b.position.vadd(interpvelo, b.interpolatedPosition);
  92418. }
  92419. else {
  92420. b.interpolatedPosition.copy(b.position);
  92421. b.interpolatedQuaternion.copy(b.quaternion);
  92422. }
  92423. }
  92424. }
  92425. };
  92426. };
  92427. return CannonJSPlugin;
  92428. }());
  92429. BABYLON.CannonJSPlugin = CannonJSPlugin;
  92430. })(BABYLON || (BABYLON = {}));
  92431. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  92432. var BABYLON;
  92433. (function (BABYLON) {
  92434. /** @hidden */
  92435. var OimoJSPlugin = /** @class */ (function () {
  92436. function OimoJSPlugin(iterations) {
  92437. this.name = "OimoJSPlugin";
  92438. this._tmpImpostorsArray = [];
  92439. this._tmpPositionVector = BABYLON.Vector3.Zero();
  92440. this.BJSOIMO = OIMO;
  92441. this.world = new this.BJSOIMO.World({
  92442. iterations: iterations
  92443. });
  92444. this.world.clear();
  92445. }
  92446. OimoJSPlugin.prototype.setGravity = function (gravity) {
  92447. this.world.gravity.copy(gravity);
  92448. };
  92449. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  92450. this.world.timeStep = timeStep;
  92451. };
  92452. OimoJSPlugin.prototype.getTimeStep = function () {
  92453. return this.world.timeStep;
  92454. };
  92455. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  92456. var _this = this;
  92457. impostors.forEach(function (impostor) {
  92458. impostor.beforeStep();
  92459. });
  92460. this.world.step();
  92461. impostors.forEach(function (impostor) {
  92462. impostor.afterStep();
  92463. //update the ordered impostors array
  92464. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  92465. });
  92466. //check for collisions
  92467. var contact = this.world.contacts;
  92468. while (contact !== null) {
  92469. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  92470. contact = contact.next;
  92471. continue;
  92472. }
  92473. //is this body colliding with any other? get the impostor
  92474. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  92475. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  92476. if (!mainImpostor || !collidingImpostor) {
  92477. contact = contact.next;
  92478. continue;
  92479. }
  92480. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  92481. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  92482. contact = contact.next;
  92483. }
  92484. };
  92485. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  92486. var mass = impostor.physicsBody.mass;
  92487. impostor.physicsBody.applyImpulse(contactPoint.scale(this.world.invScale), force.scale(this.world.invScale * mass));
  92488. };
  92489. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  92490. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  92491. this.applyImpulse(impostor, force, contactPoint);
  92492. };
  92493. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  92494. var _this = this;
  92495. //parent-child relationship. Does this impostor has a parent impostor?
  92496. if (impostor.parent) {
  92497. if (impostor.physicsBody) {
  92498. this.removePhysicsBody(impostor);
  92499. //TODO is that needed?
  92500. impostor.forceUpdate();
  92501. }
  92502. return;
  92503. }
  92504. if (impostor.isBodyInitRequired()) {
  92505. var bodyConfig = {
  92506. name: impostor.uniqueId,
  92507. //Oimo must have mass, also for static objects.
  92508. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  92509. size: [],
  92510. type: [],
  92511. pos: [],
  92512. posShape: [],
  92513. rot: [],
  92514. rotShape: [],
  92515. move: impostor.getParam("mass") !== 0,
  92516. density: impostor.getParam("mass"),
  92517. friction: impostor.getParam("friction"),
  92518. restitution: impostor.getParam("restitution"),
  92519. //Supporting older versions of Oimo
  92520. world: this.world
  92521. };
  92522. var impostors = [impostor];
  92523. var addToArray = function (parent) {
  92524. if (!parent.getChildMeshes)
  92525. return;
  92526. parent.getChildMeshes().forEach(function (m) {
  92527. if (m.physicsImpostor) {
  92528. impostors.push(m.physicsImpostor);
  92529. //m.physicsImpostor._init();
  92530. }
  92531. });
  92532. };
  92533. addToArray(impostor.object);
  92534. var checkWithEpsilon_1 = function (value) {
  92535. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  92536. };
  92537. var globalQuaternion_1 = new BABYLON.Quaternion();
  92538. impostors.forEach(function (i) {
  92539. if (!i.object.rotationQuaternion) {
  92540. return;
  92541. }
  92542. //get the correct bounding box
  92543. var oldQuaternion = i.object.rotationQuaternion;
  92544. globalQuaternion_1 = oldQuaternion.clone();
  92545. var rot = oldQuaternion.toEulerAngles();
  92546. var extendSize = i.getObjectExtendSize();
  92547. var radToDeg = 57.295779513082320876;
  92548. if (i === impostor) {
  92549. var center = impostor.getObjectCenter();
  92550. impostor.object.getAbsolutePivotPoint().subtractToRef(center, _this._tmpPositionVector);
  92551. _this._tmpPositionVector.divideInPlace(impostor.object.scaling);
  92552. //Can also use Array.prototype.push.apply
  92553. bodyConfig.pos.push(center.x);
  92554. bodyConfig.pos.push(center.y);
  92555. bodyConfig.pos.push(center.z);
  92556. bodyConfig.posShape.push(0, 0, 0);
  92557. //tmp solution
  92558. bodyConfig.rot.push(0);
  92559. bodyConfig.rot.push(0);
  92560. bodyConfig.rot.push(0);
  92561. bodyConfig.rotShape.push(0, 0, 0);
  92562. }
  92563. else {
  92564. var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());
  92565. bodyConfig.posShape.push(localPosition.x);
  92566. bodyConfig.posShape.push(localPosition.y);
  92567. bodyConfig.posShape.push(localPosition.z);
  92568. bodyConfig.pos.push(0, 0, 0);
  92569. //tmp solution until https://github.com/lo-th/OIMO.js/pull/37 is merged
  92570. bodyConfig.rot.push(0);
  92571. bodyConfig.rot.push(0);
  92572. bodyConfig.rot.push(0);
  92573. bodyConfig.rotShape.push(rot.x * radToDeg);
  92574. bodyConfig.rotShape.push(rot.y * radToDeg);
  92575. bodyConfig.rotShape.push(rot.z * radToDeg);
  92576. }
  92577. // register mesh
  92578. switch (i.type) {
  92579. case BABYLON.PhysicsImpostor.ParticleImpostor:
  92580. BABYLON.Tools.Warn("No Particle support in OIMO.js. using SphereImpostor instead");
  92581. case BABYLON.PhysicsImpostor.SphereImpostor:
  92582. var radiusX = extendSize.x;
  92583. var radiusY = extendSize.y;
  92584. var radiusZ = extendSize.z;
  92585. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  92586. bodyConfig.type.push('sphere');
  92587. //due to the way oimo works with compounds, add 3 times
  92588. bodyConfig.size.push(size);
  92589. bodyConfig.size.push(size);
  92590. bodyConfig.size.push(size);
  92591. break;
  92592. case BABYLON.PhysicsImpostor.CylinderImpostor:
  92593. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  92594. var sizeY = checkWithEpsilon_1(extendSize.y);
  92595. bodyConfig.type.push('cylinder');
  92596. bodyConfig.size.push(sizeX);
  92597. bodyConfig.size.push(sizeY);
  92598. //due to the way oimo works with compounds, add one more value.
  92599. bodyConfig.size.push(sizeY);
  92600. break;
  92601. case BABYLON.PhysicsImpostor.PlaneImpostor:
  92602. case BABYLON.PhysicsImpostor.BoxImpostor:
  92603. default:
  92604. var sizeX = checkWithEpsilon_1(extendSize.x);
  92605. var sizeY = checkWithEpsilon_1(extendSize.y);
  92606. var sizeZ = checkWithEpsilon_1(extendSize.z);
  92607. bodyConfig.type.push('box');
  92608. //if (i === impostor) {
  92609. bodyConfig.size.push(sizeX);
  92610. bodyConfig.size.push(sizeY);
  92611. bodyConfig.size.push(sizeZ);
  92612. //} else {
  92613. // bodyConfig.size.push(0,0,0);
  92614. //}
  92615. break;
  92616. }
  92617. //actually not needed, but hey...
  92618. i.object.rotationQuaternion = oldQuaternion;
  92619. });
  92620. impostor.physicsBody = this.world.add(bodyConfig);
  92621. // set the quaternion, ignoring the previously defined (euler) rotation
  92622. impostor.physicsBody.resetQuaternion(globalQuaternion_1);
  92623. // update with delta 0, so the body will reveive the new rotation.
  92624. impostor.physicsBody.updatePosition(0);
  92625. }
  92626. else {
  92627. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  92628. }
  92629. impostor.setDeltaPosition(this._tmpPositionVector);
  92630. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  92631. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  92632. };
  92633. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  92634. //impostor.physicsBody.dispose();
  92635. //Same as : (older oimo versions)
  92636. this.world.removeRigidBody(impostor.physicsBody);
  92637. };
  92638. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  92639. var mainBody = impostorJoint.mainImpostor.physicsBody;
  92640. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  92641. if (!mainBody || !connectedBody) {
  92642. return;
  92643. }
  92644. var jointData = impostorJoint.joint.jointData;
  92645. var options = jointData.nativeParams || {};
  92646. var type;
  92647. var nativeJointData = {
  92648. body1: mainBody,
  92649. body2: connectedBody,
  92650. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  92651. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  92652. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  92653. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  92654. min: options.min,
  92655. max: options.max,
  92656. collision: options.collision || jointData.collision,
  92657. spring: options.spring,
  92658. //supporting older version of Oimo
  92659. world: this.world
  92660. };
  92661. switch (impostorJoint.joint.type) {
  92662. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  92663. type = "jointBall";
  92664. break;
  92665. case BABYLON.PhysicsJoint.SpringJoint:
  92666. BABYLON.Tools.Warn("OIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  92667. var springData = jointData;
  92668. nativeJointData.min = springData.length || nativeJointData.min;
  92669. //Max should also be set, just make sure it is at least min
  92670. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  92671. case BABYLON.PhysicsJoint.DistanceJoint:
  92672. type = "jointDistance";
  92673. nativeJointData.max = jointData.maxDistance;
  92674. break;
  92675. case BABYLON.PhysicsJoint.PrismaticJoint:
  92676. type = "jointPrisme";
  92677. break;
  92678. case BABYLON.PhysicsJoint.SliderJoint:
  92679. type = "jointSlide";
  92680. break;
  92681. case BABYLON.PhysicsJoint.WheelJoint:
  92682. type = "jointWheel";
  92683. break;
  92684. case BABYLON.PhysicsJoint.HingeJoint:
  92685. default:
  92686. type = "jointHinge";
  92687. break;
  92688. }
  92689. nativeJointData.type = type;
  92690. impostorJoint.joint.physicsJoint = this.world.add(nativeJointData);
  92691. };
  92692. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  92693. //Bug in Oimo prevents us from disposing a joint in the playground
  92694. //joint.joint.physicsJoint.dispose();
  92695. //So we will bruteforce it!
  92696. try {
  92697. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  92698. }
  92699. catch (e) {
  92700. BABYLON.Tools.Warn(e);
  92701. }
  92702. };
  92703. OimoJSPlugin.prototype.isSupported = function () {
  92704. return this.BJSOIMO !== undefined;
  92705. };
  92706. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  92707. if (!impostor.physicsBody.sleeping) {
  92708. //TODO check that
  92709. /*if (impostor.physicsBody.shapes.next) {
  92710. var parentShape = this._getLastShape(impostor.physicsBody);
  92711. impostor.object.position.copyFrom(parentShape.position);
  92712. console.log(parentShape.position);
  92713. } else {*/
  92714. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  92715. //}
  92716. if (impostor.object.rotationQuaternion) {
  92717. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  92718. }
  92719. }
  92720. };
  92721. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  92722. var body = impostor.physicsBody;
  92723. body.position.copy(newPosition);
  92724. body.orientation.copy(newRotation);
  92725. body.syncShapes();
  92726. body.awake();
  92727. };
  92728. /*private _getLastShape(body: any): any {
  92729. var lastShape = body.shapes;
  92730. while (lastShape.next) {
  92731. lastShape = lastShape.next;
  92732. }
  92733. return lastShape;
  92734. }*/
  92735. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  92736. impostor.physicsBody.linearVelocity.copy(velocity);
  92737. };
  92738. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  92739. impostor.physicsBody.angularVelocity.copy(velocity);
  92740. };
  92741. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  92742. var v = impostor.physicsBody.linearVelocity;
  92743. if (!v) {
  92744. return null;
  92745. }
  92746. return new BABYLON.Vector3(v.x, v.y, v.z);
  92747. };
  92748. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  92749. var v = impostor.physicsBody.angularVelocity;
  92750. if (!v) {
  92751. return null;
  92752. }
  92753. return new BABYLON.Vector3(v.x, v.y, v.z);
  92754. };
  92755. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  92756. var staticBody = mass === 0;
  92757. //this will actually set the body's density and not its mass.
  92758. //But this is how oimo treats the mass variable.
  92759. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  92760. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  92761. };
  92762. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  92763. return impostor.physicsBody.shapes.density;
  92764. };
  92765. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  92766. return impostor.physicsBody.shapes.friction;
  92767. };
  92768. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  92769. impostor.physicsBody.shapes.friction = friction;
  92770. };
  92771. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  92772. return impostor.physicsBody.shapes.restitution;
  92773. };
  92774. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  92775. impostor.physicsBody.shapes.restitution = restitution;
  92776. };
  92777. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  92778. impostor.physicsBody.sleep();
  92779. };
  92780. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  92781. impostor.physicsBody.awake();
  92782. };
  92783. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  92784. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  92785. if (minDistance !== void 0) {
  92786. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  92787. }
  92788. };
  92789. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  92790. //TODO separate rotational and transational motors.
  92791. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  92792. if (motor) {
  92793. motor.setMotor(speed, maxForce);
  92794. }
  92795. };
  92796. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  92797. //TODO separate rotational and transational motors.
  92798. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  92799. if (motor) {
  92800. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  92801. }
  92802. };
  92803. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  92804. var body = impostor.physicsBody;
  92805. mesh.position.x = body.position.x;
  92806. mesh.position.y = body.position.y;
  92807. mesh.position.z = body.position.z;
  92808. if (mesh.rotationQuaternion) {
  92809. mesh.rotationQuaternion.x = body.orientation.x;
  92810. mesh.rotationQuaternion.y = body.orientation.y;
  92811. mesh.rotationQuaternion.z = body.orientation.z;
  92812. mesh.rotationQuaternion.w = body.orientation.s;
  92813. }
  92814. };
  92815. OimoJSPlugin.prototype.getRadius = function (impostor) {
  92816. return impostor.physicsBody.shapes.radius;
  92817. };
  92818. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  92819. var shape = impostor.physicsBody.shapes;
  92820. result.x = shape.halfWidth * 2;
  92821. result.y = shape.halfHeight * 2;
  92822. result.z = shape.halfDepth * 2;
  92823. };
  92824. OimoJSPlugin.prototype.dispose = function () {
  92825. this.world.clear();
  92826. };
  92827. return OimoJSPlugin;
  92828. }());
  92829. BABYLON.OimoJSPlugin = OimoJSPlugin;
  92830. })(BABYLON || (BABYLON = {}));
  92831. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  92832. var BABYLON;
  92833. (function (BABYLON) {
  92834. /**
  92835. * Gets the current physics engine
  92836. * @returns a IPhysicsEngine or null if none attached
  92837. */
  92838. BABYLON.Scene.prototype.getPhysicsEngine = function () {
  92839. return this._physicsEngine;
  92840. };
  92841. /**
  92842. * Enables physics to the current scene
  92843. * @param gravity defines the scene's gravity for the physics engine
  92844. * @param plugin defines the physics engine to be used. defaults to OimoJS.
  92845. * @return a boolean indicating if the physics engine was initialized
  92846. */
  92847. BABYLON.Scene.prototype.enablePhysics = function (gravity, plugin) {
  92848. if (gravity === void 0) { gravity = null; }
  92849. if (this._physicsEngine) {
  92850. return true;
  92851. }
  92852. // Register the component to the scene
  92853. var component = this._getComponent(BABYLON.SceneComponentConstants.NAME_PHYSICSENGINE);
  92854. if (!component) {
  92855. component = new PhysicsEngineSceneComponent(this);
  92856. this._addComponent(component);
  92857. }
  92858. try {
  92859. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  92860. return true;
  92861. }
  92862. catch (e) {
  92863. BABYLON.Tools.Error(e.message);
  92864. return false;
  92865. }
  92866. };
  92867. /**
  92868. * Disables and disposes the physics engine associated with the scene
  92869. */
  92870. BABYLON.Scene.prototype.disablePhysicsEngine = function () {
  92871. if (!this._physicsEngine) {
  92872. return;
  92873. }
  92874. this._physicsEngine.dispose();
  92875. this._physicsEngine = null;
  92876. };
  92877. /**
  92878. * Gets a boolean indicating if there is an active physics engine
  92879. * @returns a boolean indicating if there is an active physics engine
  92880. */
  92881. BABYLON.Scene.prototype.isPhysicsEnabled = function () {
  92882. return this._physicsEngine !== undefined;
  92883. };
  92884. /**
  92885. * Deletes a physics compound impostor
  92886. * @param compound defines the compound to delete
  92887. */
  92888. BABYLON.Scene.prototype.deleteCompoundImpostor = function (compound) {
  92889. var mesh = compound.parts[0].mesh;
  92890. if (mesh.physicsImpostor) {
  92891. mesh.physicsImpostor.dispose( /*true*/);
  92892. mesh.physicsImpostor = null;
  92893. }
  92894. };
  92895. /** @hidden */
  92896. BABYLON.Scene.prototype._advancePhysicsEngineStep = function (step) {
  92897. if (this._physicsEngine) {
  92898. this.onBeforePhysicsObservable.notifyObservers(this);
  92899. this._physicsEngine._step(step / 1000);
  92900. this.onAfterPhysicsObservable.notifyObservers(this);
  92901. }
  92902. };
  92903. Object.defineProperty(BABYLON.AbstractMesh.prototype, "physicsImpostor", {
  92904. get: function () {
  92905. return this._physicsImpostor;
  92906. },
  92907. set: function (value) {
  92908. var _this = this;
  92909. if (this._physicsImpostor === value) {
  92910. return;
  92911. }
  92912. if (this._disposePhysicsObserver) {
  92913. this.onDisposeObservable.remove(this._disposePhysicsObserver);
  92914. }
  92915. this._physicsImpostor = value;
  92916. if (value) {
  92917. this._disposePhysicsObserver = this.onDisposeObservable.add(function () {
  92918. // Physics
  92919. if (_this.physicsImpostor) {
  92920. _this.physicsImpostor.dispose( /*!doNotRecurse*/);
  92921. _this.physicsImpostor = null;
  92922. }
  92923. });
  92924. }
  92925. },
  92926. enumerable: true,
  92927. configurable: true
  92928. });
  92929. /**
  92930. * Gets the current physics impostor
  92931. * @see http://doc.babylonjs.com/features/physics_engine
  92932. * @returns a physics impostor or null
  92933. */
  92934. BABYLON.AbstractMesh.prototype.getPhysicsImpostor = function () {
  92935. return this.physicsImpostor;
  92936. };
  92937. /**
  92938. * Apply a physic impulse to the mesh
  92939. * @param force defines the force to apply
  92940. * @param contactPoint defines where to apply the force
  92941. * @returns the current mesh
  92942. * @see http://doc.babylonjs.com/how_to/using_the_physics_engine
  92943. */
  92944. BABYLON.AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  92945. if (!this.physicsImpostor) {
  92946. return this;
  92947. }
  92948. this.physicsImpostor.applyImpulse(force, contactPoint);
  92949. return this;
  92950. };
  92951. /**
  92952. * Creates a physic joint between two meshes
  92953. * @param otherMesh defines the other mesh to use
  92954. * @param pivot1 defines the pivot to use on this mesh
  92955. * @param pivot2 defines the pivot to use on the other mesh
  92956. * @param options defines additional options (can be plugin dependent)
  92957. * @returns the current mesh
  92958. * @see https://www.babylonjs-playground.com/#0BS5U0#0
  92959. */
  92960. BABYLON.AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  92961. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  92962. return this;
  92963. }
  92964. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  92965. mainPivot: pivot1,
  92966. connectedPivot: pivot2,
  92967. nativeParams: options
  92968. });
  92969. return this;
  92970. };
  92971. /**
  92972. * Defines the physics engine scene component responsible to manage a physics engine
  92973. */
  92974. var PhysicsEngineSceneComponent = /** @class */ (function () {
  92975. /**
  92976. * Creates a new instance of the component for the given scene
  92977. * @param scene Defines the scene to register the component in
  92978. */
  92979. function PhysicsEngineSceneComponent(scene) {
  92980. var _this = this;
  92981. /**
  92982. * The component name helpful to identify the component in the list of scene components.
  92983. */
  92984. this.name = BABYLON.SceneComponentConstants.NAME_PHYSICSENGINE;
  92985. this.scene = scene;
  92986. this.scene.onBeforePhysicsObservable = new BABYLON.Observable();
  92987. this.scene.onAfterPhysicsObservable = new BABYLON.Observable();
  92988. // Replace the function used to get the deterministic frame time
  92989. this.scene.getDeterministicFrameTime = function () {
  92990. if (_this.scene._physicsEngine) {
  92991. return _this.scene._physicsEngine.getTimeStep() * 1000;
  92992. }
  92993. return 1000.0 / 60.0;
  92994. };
  92995. }
  92996. /**
  92997. * Registers the component in a given scene
  92998. */
  92999. PhysicsEngineSceneComponent.prototype.register = function () {
  93000. };
  93001. /**
  93002. * Rebuilds the elements related to this component in case of
  93003. * context lost for instance.
  93004. */
  93005. PhysicsEngineSceneComponent.prototype.rebuild = function () {
  93006. // Nothing to do for this component
  93007. };
  93008. /**
  93009. * Disposes the component and the associated ressources
  93010. */
  93011. PhysicsEngineSceneComponent.prototype.dispose = function () {
  93012. this.scene.onBeforePhysicsObservable.clear();
  93013. this.scene.onAfterPhysicsObservable.clear();
  93014. if (this.scene._physicsEngine) {
  93015. this.scene.disablePhysicsEngine();
  93016. }
  93017. };
  93018. return PhysicsEngineSceneComponent;
  93019. }());
  93020. BABYLON.PhysicsEngineSceneComponent = PhysicsEngineSceneComponent;
  93021. })(BABYLON || (BABYLON = {}));
  93022. //# sourceMappingURL=babylon.physicsEngineComponent.js.map
  93023. var BABYLON;
  93024. (function (BABYLON) {
  93025. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  93026. // All values and structures referenced from:
  93027. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  93028. var DDS_MAGIC = 0x20534444;
  93029. var
  93030. //DDSD_CAPS = 0x1,
  93031. //DDSD_HEIGHT = 0x2,
  93032. //DDSD_WIDTH = 0x4,
  93033. //DDSD_PITCH = 0x8,
  93034. //DDSD_PIXELFORMAT = 0x1000,
  93035. DDSD_MIPMAPCOUNT = 0x20000;
  93036. //DDSD_LINEARSIZE = 0x80000,
  93037. //DDSD_DEPTH = 0x800000;
  93038. // var DDSCAPS_COMPLEX = 0x8,
  93039. // DDSCAPS_MIPMAP = 0x400000,
  93040. // DDSCAPS_TEXTURE = 0x1000;
  93041. var DDSCAPS2_CUBEMAP = 0x200;
  93042. // DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  93043. // DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  93044. // DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  93045. // DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  93046. // DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  93047. // DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  93048. // DDSCAPS2_VOLUME = 0x200000;
  93049. var
  93050. //DDPF_ALPHAPIXELS = 0x1,
  93051. //DDPF_ALPHA = 0x2,
  93052. DDPF_FOURCC = 0x4, DDPF_RGB = 0x40,
  93053. //DDPF_YUV = 0x200,
  93054. DDPF_LUMINANCE = 0x20000;
  93055. function FourCCToInt32(value) {
  93056. return value.charCodeAt(0) +
  93057. (value.charCodeAt(1) << 8) +
  93058. (value.charCodeAt(2) << 16) +
  93059. (value.charCodeAt(3) << 24);
  93060. }
  93061. function Int32ToFourCC(value) {
  93062. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  93063. }
  93064. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  93065. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  93066. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  93067. var FOURCC_DX10 = FourCCToInt32("DX10");
  93068. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  93069. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  93070. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  93071. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  93072. var headerLengthInt = 31; // The header length in 32 bit ints
  93073. // Offsets into the header array
  93074. var off_magic = 0;
  93075. var off_size = 1;
  93076. var off_flags = 2;
  93077. var off_height = 3;
  93078. var off_width = 4;
  93079. var off_mipmapCount = 7;
  93080. var off_pfFlags = 20;
  93081. var off_pfFourCC = 21;
  93082. var off_RGBbpp = 22;
  93083. var off_RMask = 23;
  93084. var off_GMask = 24;
  93085. var off_BMask = 25;
  93086. var off_AMask = 26;
  93087. // var off_caps1 = 27;
  93088. var off_caps2 = 28;
  93089. // var off_caps3 = 29;
  93090. // var off_caps4 = 30;
  93091. var off_dxgiFormat = 32;
  93092. ;
  93093. var DDSTools = /** @class */ (function () {
  93094. function DDSTools() {
  93095. }
  93096. DDSTools.GetDDSInfo = function (arrayBuffer) {
  93097. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  93098. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  93099. var mipmapCount = 1;
  93100. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  93101. mipmapCount = Math.max(1, header[off_mipmapCount]);
  93102. }
  93103. var fourCC = header[off_pfFourCC];
  93104. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  93105. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  93106. switch (fourCC) {
  93107. case FOURCC_D3DFMT_R16G16B16A16F:
  93108. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  93109. break;
  93110. case FOURCC_D3DFMT_R32G32B32A32F:
  93111. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  93112. break;
  93113. case FOURCC_DX10:
  93114. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  93115. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  93116. break;
  93117. }
  93118. }
  93119. return {
  93120. width: header[off_width],
  93121. height: header[off_height],
  93122. mipmapCount: mipmapCount,
  93123. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  93124. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  93125. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  93126. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  93127. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || fourCC === FOURCC_DXT5),
  93128. dxgiFormat: dxgiFormat,
  93129. textureType: textureType
  93130. };
  93131. };
  93132. DDSTools._ToHalfFloat = function (value) {
  93133. if (!DDSTools._FloatView) {
  93134. DDSTools._FloatView = new Float32Array(1);
  93135. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  93136. }
  93137. DDSTools._FloatView[0] = value;
  93138. var x = DDSTools._Int32View[0];
  93139. var bits = (x >> 16) & 0x8000; /* Get the sign */
  93140. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  93141. var e = (x >> 23) & 0xff; /* Using int is faster here */
  93142. /* If zero, or denormal, or exponent underflows too much for a denormal
  93143. * half, return signed zero. */
  93144. if (e < 103) {
  93145. return bits;
  93146. }
  93147. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  93148. if (e > 142) {
  93149. bits |= 0x7c00;
  93150. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  93151. * not Inf, so make sure we set one mantissa bit too. */
  93152. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  93153. return bits;
  93154. }
  93155. /* If exponent underflows but not too much, return a denormal */
  93156. if (e < 113) {
  93157. m |= 0x0800;
  93158. /* Extra rounding may overflow and set mantissa to 0 and exponent
  93159. * to 1, which is OK. */
  93160. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  93161. return bits;
  93162. }
  93163. bits |= ((e - 112) << 10) | (m >> 1);
  93164. bits += m & 1;
  93165. return bits;
  93166. };
  93167. DDSTools._FromHalfFloat = function (value) {
  93168. var s = (value & 0x8000) >> 15;
  93169. var e = (value & 0x7C00) >> 10;
  93170. var f = value & 0x03FF;
  93171. if (e === 0) {
  93172. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  93173. }
  93174. else if (e == 0x1F) {
  93175. return f ? NaN : ((s ? -1 : 1) * Infinity);
  93176. }
  93177. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  93178. };
  93179. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  93180. var destArray = new Float32Array(dataLength);
  93181. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  93182. var index = 0;
  93183. for (var y = 0; y < height; y++) {
  93184. for (var x = 0; x < width; x++) {
  93185. var srcPos = (x + y * width) * 4;
  93186. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  93187. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  93188. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  93189. if (DDSTools.StoreLODInAlphaChannel) {
  93190. destArray[index + 3] = lod;
  93191. }
  93192. else {
  93193. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  93194. }
  93195. index += 4;
  93196. }
  93197. }
  93198. return destArray;
  93199. };
  93200. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  93201. if (DDSTools.StoreLODInAlphaChannel) {
  93202. var destArray = new Uint16Array(dataLength);
  93203. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  93204. var index = 0;
  93205. for (var y = 0; y < height; y++) {
  93206. for (var x = 0; x < width; x++) {
  93207. var srcPos = (x + y * width) * 4;
  93208. destArray[index] = srcData[srcPos];
  93209. destArray[index + 1] = srcData[srcPos + 1];
  93210. destArray[index + 2] = srcData[srcPos + 2];
  93211. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  93212. index += 4;
  93213. }
  93214. }
  93215. return destArray;
  93216. }
  93217. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  93218. };
  93219. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  93220. if (DDSTools.StoreLODInAlphaChannel) {
  93221. var destArray = new Float32Array(dataLength);
  93222. var srcData = new Float32Array(arrayBuffer, dataOffset);
  93223. var index = 0;
  93224. for (var y = 0; y < height; y++) {
  93225. for (var x = 0; x < width; x++) {
  93226. var srcPos = (x + y * width) * 4;
  93227. destArray[index] = srcData[srcPos];
  93228. destArray[index + 1] = srcData[srcPos + 1];
  93229. destArray[index + 2] = srcData[srcPos + 2];
  93230. destArray[index + 3] = lod;
  93231. index += 4;
  93232. }
  93233. }
  93234. return destArray;
  93235. }
  93236. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  93237. };
  93238. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  93239. var destArray = new Uint8Array(dataLength);
  93240. var srcData = new Float32Array(arrayBuffer, dataOffset);
  93241. var index = 0;
  93242. for (var y = 0; y < height; y++) {
  93243. for (var x = 0; x < width; x++) {
  93244. var srcPos = (x + y * width) * 4;
  93245. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  93246. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  93247. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  93248. if (DDSTools.StoreLODInAlphaChannel) {
  93249. destArray[index + 3] = lod;
  93250. }
  93251. else {
  93252. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  93253. }
  93254. index += 4;
  93255. }
  93256. }
  93257. return destArray;
  93258. };
  93259. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  93260. var destArray = new Uint8Array(dataLength);
  93261. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  93262. var index = 0;
  93263. for (var y = 0; y < height; y++) {
  93264. for (var x = 0; x < width; x++) {
  93265. var srcPos = (x + y * width) * 4;
  93266. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  93267. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  93268. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  93269. if (DDSTools.StoreLODInAlphaChannel) {
  93270. destArray[index + 3] = lod;
  93271. }
  93272. else {
  93273. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  93274. }
  93275. index += 4;
  93276. }
  93277. }
  93278. return destArray;
  93279. };
  93280. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset) {
  93281. var byteArray = new Uint8Array(dataLength);
  93282. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  93283. var index = 0;
  93284. for (var y = 0; y < height; y++) {
  93285. for (var x = 0; x < width; x++) {
  93286. var srcPos = (x + y * width) * 4;
  93287. byteArray[index] = srcData[srcPos + rOffset];
  93288. byteArray[index + 1] = srcData[srcPos + gOffset];
  93289. byteArray[index + 2] = srcData[srcPos + bOffset];
  93290. byteArray[index + 3] = srcData[srcPos + aOffset];
  93291. index += 4;
  93292. }
  93293. }
  93294. return byteArray;
  93295. };
  93296. DDSTools._ExtractLongWordOrder = function (value) {
  93297. if (value === 0 || value === 255 || value === -16777216) {
  93298. return 0;
  93299. }
  93300. return 1 + DDSTools._ExtractLongWordOrder(value >> 8);
  93301. };
  93302. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset) {
  93303. var byteArray = new Uint8Array(dataLength);
  93304. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  93305. var index = 0;
  93306. for (var y = 0; y < height; y++) {
  93307. for (var x = 0; x < width; x++) {
  93308. var srcPos = (x + y * width) * 3;
  93309. byteArray[index] = srcData[srcPos + rOffset];
  93310. byteArray[index + 1] = srcData[srcPos + gOffset];
  93311. byteArray[index + 2] = srcData[srcPos + bOffset];
  93312. index += 3;
  93313. }
  93314. }
  93315. return byteArray;
  93316. };
  93317. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  93318. var byteArray = new Uint8Array(dataLength);
  93319. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  93320. var index = 0;
  93321. for (var y = 0; y < height; y++) {
  93322. for (var x = 0; x < width; x++) {
  93323. var srcPos = (x + y * width);
  93324. byteArray[index] = srcData[srcPos];
  93325. index++;
  93326. }
  93327. }
  93328. return byteArray;
  93329. };
  93330. /**
  93331. * Uploads DDS Levels to a Babylon Texture
  93332. * @hidden
  93333. */
  93334. DDSTools.UploadDDSLevels = function (engine, texture, arrayBuffer, info, loadMipmaps, faces, lodIndex, currentFace) {
  93335. if (lodIndex === void 0) { lodIndex = -1; }
  93336. var sphericalPolynomialFaces = null;
  93337. if (info.sphericalPolynomial) {
  93338. sphericalPolynomialFaces = new Array();
  93339. }
  93340. var ext = engine.getCaps().s3tc;
  93341. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  93342. var fourCC, width, height, dataLength = 0, dataOffset;
  93343. var byteArray, mipmapCount, mip;
  93344. var internalCompressedFormat = 0;
  93345. var blockBytes = 1;
  93346. if (header[off_magic] !== DDS_MAGIC) {
  93347. BABYLON.Tools.Error("Invalid magic number in DDS header");
  93348. return;
  93349. }
  93350. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  93351. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  93352. return;
  93353. }
  93354. if (info.isCompressed && !ext) {
  93355. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  93356. return;
  93357. }
  93358. var bpp = header[off_RGBbpp];
  93359. dataOffset = header[off_size] + 4;
  93360. var computeFormats = false;
  93361. if (info.isFourCC) {
  93362. fourCC = header[off_pfFourCC];
  93363. switch (fourCC) {
  93364. case FOURCC_DXT1:
  93365. blockBytes = 8;
  93366. internalCompressedFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  93367. break;
  93368. case FOURCC_DXT3:
  93369. blockBytes = 16;
  93370. internalCompressedFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  93371. break;
  93372. case FOURCC_DXT5:
  93373. blockBytes = 16;
  93374. internalCompressedFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  93375. break;
  93376. case FOURCC_D3DFMT_R16G16B16A16F:
  93377. computeFormats = true;
  93378. break;
  93379. case FOURCC_D3DFMT_R32G32B32A32F:
  93380. computeFormats = true;
  93381. break;
  93382. case FOURCC_DX10:
  93383. // There is an additionnal header so dataOffset need to be changed
  93384. dataOffset += 5 * 4; // 5 uints
  93385. var supported = false;
  93386. switch (info.dxgiFormat) {
  93387. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  93388. computeFormats = true;
  93389. supported = true;
  93390. break;
  93391. case DXGI_FORMAT_B8G8R8X8_UNORM:
  93392. info.isRGB = true;
  93393. info.isFourCC = false;
  93394. bpp = 32;
  93395. supported = true;
  93396. break;
  93397. }
  93398. if (supported) {
  93399. break;
  93400. }
  93401. default:
  93402. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  93403. return;
  93404. }
  93405. }
  93406. var rOffset = DDSTools._ExtractLongWordOrder(header[off_RMask]);
  93407. var gOffset = DDSTools._ExtractLongWordOrder(header[off_GMask]);
  93408. var bOffset = DDSTools._ExtractLongWordOrder(header[off_BMask]);
  93409. var aOffset = DDSTools._ExtractLongWordOrder(header[off_AMask]);
  93410. if (computeFormats) {
  93411. internalCompressedFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  93412. }
  93413. mipmapCount = 1;
  93414. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  93415. mipmapCount = Math.max(1, header[off_mipmapCount]);
  93416. }
  93417. for (var face = 0; face < faces; face++) {
  93418. width = header[off_width];
  93419. height = header[off_height];
  93420. for (mip = 0; mip < mipmapCount; ++mip) {
  93421. if (lodIndex === -1 || lodIndex === mip) {
  93422. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  93423. var i = (lodIndex === -1) ? mip : 0;
  93424. if (!info.isCompressed && info.isFourCC) {
  93425. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  93426. dataLength = width * height * 4;
  93427. var floatArray = null;
  93428. if (engine._badOS || engine._badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) { // Required because iOS has many issues with float and half float generation
  93429. if (bpp === 128) {
  93430. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  93431. if (sphericalPolynomialFaces && i == 0) {
  93432. sphericalPolynomialFaces.push(DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  93433. }
  93434. }
  93435. else if (bpp === 64) {
  93436. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  93437. if (sphericalPolynomialFaces && i == 0) {
  93438. sphericalPolynomialFaces.push(DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  93439. }
  93440. }
  93441. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  93442. }
  93443. else {
  93444. if (bpp === 128) {
  93445. texture.type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  93446. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  93447. if (sphericalPolynomialFaces && i == 0) {
  93448. sphericalPolynomialFaces.push(floatArray);
  93449. }
  93450. }
  93451. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  93452. texture.type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  93453. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  93454. if (sphericalPolynomialFaces && i == 0) {
  93455. sphericalPolynomialFaces.push(floatArray);
  93456. }
  93457. }
  93458. else { // 64
  93459. texture.type = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  93460. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  93461. if (sphericalPolynomialFaces && i == 0) {
  93462. sphericalPolynomialFaces.push(DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  93463. }
  93464. }
  93465. }
  93466. if (floatArray) {
  93467. engine._uploadDataToTextureDirectly(texture, floatArray, face, i);
  93468. }
  93469. }
  93470. else if (info.isRGB) {
  93471. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  93472. if (bpp === 24) {
  93473. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGB;
  93474. dataLength = width * height * 3;
  93475. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset);
  93476. engine._uploadDataToTextureDirectly(texture, byteArray, face, i);
  93477. }
  93478. else { // 32
  93479. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  93480. dataLength = width * height * 4;
  93481. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset);
  93482. engine._uploadDataToTextureDirectly(texture, byteArray, face, i);
  93483. }
  93484. }
  93485. else if (info.isLuminance) {
  93486. var unpackAlignment = engine._getUnpackAlignement();
  93487. var unpaddedRowSize = width;
  93488. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  93489. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  93490. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  93491. texture.format = BABYLON.Engine.TEXTUREFORMAT_LUMINANCE;
  93492. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  93493. engine._uploadDataToTextureDirectly(texture, byteArray, face, i);
  93494. }
  93495. else {
  93496. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  93497. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  93498. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  93499. engine._uploadCompressedDataToTextureDirectly(texture, internalCompressedFormat, width, height, byteArray, face, i);
  93500. }
  93501. }
  93502. dataOffset += bpp ? (width * height * (bpp / 8)) : dataLength;
  93503. width *= 0.5;
  93504. height *= 0.5;
  93505. width = Math.max(1.0, width);
  93506. height = Math.max(1.0, height);
  93507. }
  93508. if (currentFace !== undefined) {
  93509. // Loading a single face
  93510. break;
  93511. }
  93512. }
  93513. if (sphericalPolynomialFaces && sphericalPolynomialFaces.length > 0) {
  93514. info.sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial({
  93515. size: header[off_width],
  93516. right: sphericalPolynomialFaces[0],
  93517. left: sphericalPolynomialFaces[1],
  93518. up: sphericalPolynomialFaces[2],
  93519. down: sphericalPolynomialFaces[3],
  93520. front: sphericalPolynomialFaces[4],
  93521. back: sphericalPolynomialFaces[5],
  93522. format: BABYLON.Engine.TEXTUREFORMAT_RGBA,
  93523. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  93524. gammaSpace: false,
  93525. });
  93526. }
  93527. else {
  93528. info.sphericalPolynomial = undefined;
  93529. }
  93530. };
  93531. DDSTools.StoreLODInAlphaChannel = false;
  93532. return DDSTools;
  93533. }());
  93534. BABYLON.DDSTools = DDSTools;
  93535. })(BABYLON || (BABYLON = {}));
  93536. //# sourceMappingURL=babylon.dds.js.map
  93537. var BABYLON;
  93538. (function (BABYLON) {
  93539. /**
  93540. * Implementation of the DDS Texture Loader.
  93541. */
  93542. var DDSTextureLoader = /** @class */ (function () {
  93543. function DDSTextureLoader() {
  93544. /**
  93545. * Defines wether the loader supports cascade loading the different faces.
  93546. */
  93547. this.supportCascades = true;
  93548. }
  93549. /**
  93550. * This returns if the loader support the current file information.
  93551. * @param extension defines the file extension of the file being loaded
  93552. * @param textureFormatInUse defines the current compressed format in use iun the engine
  93553. * @param fallback defines the fallback internal texture if any
  93554. * @param isBase64 defines whether the texture is encoded as a base64
  93555. * @param isBuffer defines whether the texture data are stored as a buffer
  93556. * @returns true if the loader can load the specified file
  93557. */
  93558. DDSTextureLoader.prototype.canLoad = function (extension, textureFormatInUse, fallback, isBase64, isBuffer) {
  93559. return extension.indexOf(".dds") === 0;
  93560. };
  93561. /**
  93562. * Transform the url before loading if required.
  93563. * @param rootUrl the url of the texture
  93564. * @param textureFormatInUse defines the current compressed format in use iun the engine
  93565. * @returns the transformed texture
  93566. */
  93567. DDSTextureLoader.prototype.transformUrl = function (rootUrl, textureFormatInUse) {
  93568. return rootUrl;
  93569. };
  93570. /**
  93571. * Gets the fallback url in case the load fail. This can return null to allow the default fallback mecanism to work
  93572. * @param rootUrl the url of the texture
  93573. * @param textureFormatInUse defines the current compressed format in use iun the engine
  93574. * @returns the fallback texture
  93575. */
  93576. DDSTextureLoader.prototype.getFallbackTextureUrl = function (rootUrl, textureFormatInUse) {
  93577. return null;
  93578. };
  93579. /**
  93580. * Uploads the cube texture data to the WebGl Texture. It has alreday been bound.
  93581. * @param data contains the texture data
  93582. * @param texture defines the BabylonJS internal texture
  93583. * @param createPolynomials will be true if polynomials have been requested
  93584. * @param onLoad defines the callback to trigger once the texture is ready
  93585. * @param onError defines the callback to trigger in case of error
  93586. */
  93587. DDSTextureLoader.prototype.loadCubeData = function (imgs, texture, createPolynomials, onLoad, onError) {
  93588. var engine = texture.getEngine();
  93589. var info;
  93590. var loadMipmap = false;
  93591. if (Array.isArray(imgs)) {
  93592. for (var index = 0; index < imgs.length; index++) {
  93593. var data_1 = imgs[index];
  93594. info = BABYLON.DDSTools.GetDDSInfo(data_1);
  93595. texture.width = info.width;
  93596. texture.height = info.height;
  93597. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && texture.generateMipMaps;
  93598. engine._unpackFlipY(info.isCompressed);
  93599. BABYLON.DDSTools.UploadDDSLevels(engine, texture, data_1, info, loadMipmap, 6, -1, index);
  93600. if (!info.isFourCC && info.mipmapCount === 1) {
  93601. engine.generateMipMapsForCubemap(texture);
  93602. }
  93603. }
  93604. }
  93605. else {
  93606. var data = imgs;
  93607. info = BABYLON.DDSTools.GetDDSInfo(data);
  93608. texture.width = info.width;
  93609. texture.height = info.height;
  93610. if (createPolynomials) {
  93611. info.sphericalPolynomial = new BABYLON.SphericalPolynomial();
  93612. }
  93613. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && texture.generateMipMaps;
  93614. engine._unpackFlipY(info.isCompressed);
  93615. BABYLON.DDSTools.UploadDDSLevels(engine, texture, data, info, loadMipmap, 6);
  93616. if (!info.isFourCC && info.mipmapCount === 1) {
  93617. engine.generateMipMapsForCubemap(texture);
  93618. }
  93619. }
  93620. engine._setCubeMapTextureParams(loadMipmap);
  93621. texture.isReady = true;
  93622. if (onLoad) {
  93623. onLoad({ isDDS: true, width: texture.width, info: info, data: imgs, texture: texture });
  93624. }
  93625. };
  93626. /**
  93627. * Uploads the 2D texture data to the WebGl Texture. It has alreday been bound once in the callback.
  93628. * @param data contains the texture data
  93629. * @param texture defines the BabylonJS internal texture
  93630. * @param callback defines the method to call once ready to upload
  93631. */
  93632. DDSTextureLoader.prototype.loadData = function (data, texture, callback) {
  93633. var info = BABYLON.DDSTools.GetDDSInfo(data);
  93634. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && texture.generateMipMaps && ((info.width >> (info.mipmapCount - 1)) === 1);
  93635. callback(info.width, info.height, loadMipmap, info.isFourCC, function () {
  93636. BABYLON.DDSTools.UploadDDSLevels(texture.getEngine(), texture, data, info, loadMipmap, 1);
  93637. });
  93638. };
  93639. return DDSTextureLoader;
  93640. }());
  93641. // Register the loader.
  93642. BABYLON.Engine._TextureLoaders.push(new DDSTextureLoader());
  93643. })(BABYLON || (BABYLON = {}));
  93644. //# sourceMappingURL=babylon.ddsTextureLoader.js.map
  93645. var BABYLON;
  93646. (function (BABYLON) {
  93647. /*
  93648. * Based on jsTGALoader - Javascript loader for TGA file
  93649. * By Vincent Thibault
  93650. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  93651. */
  93652. var TGATools = /** @class */ (function () {
  93653. function TGATools() {
  93654. }
  93655. TGATools.GetTGAHeader = function (data) {
  93656. var offset = 0;
  93657. var header = {
  93658. id_length: data[offset++],
  93659. colormap_type: data[offset++],
  93660. image_type: data[offset++],
  93661. colormap_index: data[offset++] | data[offset++] << 8,
  93662. colormap_length: data[offset++] | data[offset++] << 8,
  93663. colormap_size: data[offset++],
  93664. origin: [
  93665. data[offset++] | data[offset++] << 8,
  93666. data[offset++] | data[offset++] << 8
  93667. ],
  93668. width: data[offset++] | data[offset++] << 8,
  93669. height: data[offset++] | data[offset++] << 8,
  93670. pixel_size: data[offset++],
  93671. flags: data[offset++]
  93672. };
  93673. return header;
  93674. };
  93675. /**
  93676. * Uploads TGA content to a Babylon Texture
  93677. * @hidden
  93678. */
  93679. TGATools.UploadContent = function (texture, data) {
  93680. // Not enough data to contain header ?
  93681. if (data.length < 19) {
  93682. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  93683. return;
  93684. }
  93685. // Read Header
  93686. var offset = 18;
  93687. var header = TGATools.GetTGAHeader(data);
  93688. // Assume it's a valid Targa file.
  93689. if (header.id_length + offset > data.length) {
  93690. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  93691. return;
  93692. }
  93693. // Skip not needed data
  93694. offset += header.id_length;
  93695. var use_rle = false;
  93696. var use_pal = false;
  93697. var use_grey = false;
  93698. // Get some informations.
  93699. switch (header.image_type) {
  93700. case TGATools._TYPE_RLE_INDEXED:
  93701. use_rle = true;
  93702. case TGATools._TYPE_INDEXED:
  93703. use_pal = true;
  93704. break;
  93705. case TGATools._TYPE_RLE_RGB:
  93706. use_rle = true;
  93707. case TGATools._TYPE_RGB:
  93708. // use_rgb = true;
  93709. break;
  93710. case TGATools._TYPE_RLE_GREY:
  93711. use_rle = true;
  93712. case TGATools._TYPE_GREY:
  93713. use_grey = true;
  93714. break;
  93715. }
  93716. var pixel_data;
  93717. // var numAlphaBits = header.flags & 0xf;
  93718. var pixel_size = header.pixel_size >> 3;
  93719. var pixel_total = header.width * header.height * pixel_size;
  93720. // Read palettes
  93721. var palettes;
  93722. if (use_pal) {
  93723. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  93724. }
  93725. // Read LRE
  93726. if (use_rle) {
  93727. pixel_data = new Uint8Array(pixel_total);
  93728. var c, count, i;
  93729. var localOffset = 0;
  93730. var pixels = new Uint8Array(pixel_size);
  93731. while (offset < pixel_total && localOffset < pixel_total) {
  93732. c = data[offset++];
  93733. count = (c & 0x7f) + 1;
  93734. // RLE pixels
  93735. if (c & 0x80) {
  93736. // Bind pixel tmp array
  93737. for (i = 0; i < pixel_size; ++i) {
  93738. pixels[i] = data[offset++];
  93739. }
  93740. // Copy pixel array
  93741. for (i = 0; i < count; ++i) {
  93742. pixel_data.set(pixels, localOffset + i * pixel_size);
  93743. }
  93744. localOffset += pixel_size * count;
  93745. }
  93746. // Raw pixels
  93747. else {
  93748. count *= pixel_size;
  93749. for (i = 0; i < count; ++i) {
  93750. pixel_data[localOffset + i] = data[offset++];
  93751. }
  93752. localOffset += count;
  93753. }
  93754. }
  93755. }
  93756. // RAW Pixels
  93757. else {
  93758. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  93759. }
  93760. // Load to texture
  93761. var x_start, y_start, x_step, y_step, y_end, x_end;
  93762. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  93763. default:
  93764. case TGATools._ORIGIN_UL:
  93765. x_start = 0;
  93766. x_step = 1;
  93767. x_end = header.width;
  93768. y_start = 0;
  93769. y_step = 1;
  93770. y_end = header.height;
  93771. break;
  93772. case TGATools._ORIGIN_BL:
  93773. x_start = 0;
  93774. x_step = 1;
  93775. x_end = header.width;
  93776. y_start = header.height - 1;
  93777. y_step = -1;
  93778. y_end = -1;
  93779. break;
  93780. case TGATools._ORIGIN_UR:
  93781. x_start = header.width - 1;
  93782. x_step = -1;
  93783. x_end = -1;
  93784. y_start = 0;
  93785. y_step = 1;
  93786. y_end = header.height;
  93787. break;
  93788. case TGATools._ORIGIN_BR:
  93789. x_start = header.width - 1;
  93790. x_step = -1;
  93791. x_end = -1;
  93792. y_start = header.height - 1;
  93793. y_step = -1;
  93794. y_end = -1;
  93795. break;
  93796. }
  93797. // Load the specify method
  93798. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  93799. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  93800. var engine = texture.getEngine();
  93801. engine._uploadDataToTextureDirectly(texture, imageData);
  93802. };
  93803. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  93804. var image = pixel_data, colormap = palettes;
  93805. var width = header.width, height = header.height;
  93806. var color, i = 0, x, y;
  93807. var imageData = new Uint8Array(width * height * 4);
  93808. for (y = y_start; y !== y_end; y += y_step) {
  93809. for (x = x_start; x !== x_end; x += x_step, i++) {
  93810. color = image[i];
  93811. imageData[(x + width * y) * 4 + 3] = 255;
  93812. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  93813. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  93814. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  93815. }
  93816. }
  93817. return imageData;
  93818. };
  93819. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  93820. var image = pixel_data;
  93821. var width = header.width, height = header.height;
  93822. var color, i = 0, x, y;
  93823. var imageData = new Uint8Array(width * height * 4);
  93824. for (y = y_start; y !== y_end; y += y_step) {
  93825. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  93826. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  93827. var r = (((color & 0x7C00) >> 10) * 255) / 0x1F | 0;
  93828. var g = (((color & 0x03E0) >> 5) * 255) / 0x1F | 0;
  93829. var b = ((color & 0x001F) * 255) / 0x1F | 0;
  93830. imageData[(x + width * y) * 4 + 0] = r;
  93831. imageData[(x + width * y) * 4 + 1] = g;
  93832. imageData[(x + width * y) * 4 + 2] = b;
  93833. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  93834. }
  93835. }
  93836. return imageData;
  93837. };
  93838. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  93839. var image = pixel_data;
  93840. var width = header.width, height = header.height;
  93841. var i = 0, x, y;
  93842. var imageData = new Uint8Array(width * height * 4);
  93843. for (y = y_start; y !== y_end; y += y_step) {
  93844. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  93845. imageData[(x + width * y) * 4 + 3] = 255;
  93846. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  93847. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  93848. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  93849. }
  93850. }
  93851. return imageData;
  93852. };
  93853. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  93854. var image = pixel_data;
  93855. var width = header.width, height = header.height;
  93856. var i = 0, x, y;
  93857. var imageData = new Uint8Array(width * height * 4);
  93858. for (y = y_start; y !== y_end; y += y_step) {
  93859. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  93860. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  93861. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  93862. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  93863. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  93864. }
  93865. }
  93866. return imageData;
  93867. };
  93868. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  93869. var image = pixel_data;
  93870. var width = header.width, height = header.height;
  93871. var color, i = 0, x, y;
  93872. var imageData = new Uint8Array(width * height * 4);
  93873. for (y = y_start; y !== y_end; y += y_step) {
  93874. for (x = x_start; x !== x_end; x += x_step, i++) {
  93875. color = image[i];
  93876. imageData[(x + width * y) * 4 + 0] = color;
  93877. imageData[(x + width * y) * 4 + 1] = color;
  93878. imageData[(x + width * y) * 4 + 2] = color;
  93879. imageData[(x + width * y) * 4 + 3] = 255;
  93880. }
  93881. }
  93882. return imageData;
  93883. };
  93884. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  93885. var image = pixel_data;
  93886. var width = header.width, height = header.height;
  93887. var i = 0, x, y;
  93888. var imageData = new Uint8Array(width * height * 4);
  93889. for (y = y_start; y !== y_end; y += y_step) {
  93890. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  93891. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  93892. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  93893. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  93894. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  93895. }
  93896. }
  93897. return imageData;
  93898. };
  93899. //private static _TYPE_NO_DATA = 0;
  93900. TGATools._TYPE_INDEXED = 1;
  93901. TGATools._TYPE_RGB = 2;
  93902. TGATools._TYPE_GREY = 3;
  93903. TGATools._TYPE_RLE_INDEXED = 9;
  93904. TGATools._TYPE_RLE_RGB = 10;
  93905. TGATools._TYPE_RLE_GREY = 11;
  93906. TGATools._ORIGIN_MASK = 0x30;
  93907. TGATools._ORIGIN_SHIFT = 0x04;
  93908. TGATools._ORIGIN_BL = 0x00;
  93909. TGATools._ORIGIN_BR = 0x01;
  93910. TGATools._ORIGIN_UL = 0x02;
  93911. TGATools._ORIGIN_UR = 0x03;
  93912. return TGATools;
  93913. }());
  93914. BABYLON.TGATools = TGATools;
  93915. })(BABYLON || (BABYLON = {}));
  93916. //# sourceMappingURL=babylon.tga.js.map
  93917. var BABYLON;
  93918. (function (BABYLON) {
  93919. /**
  93920. * Implementation of the TGA Texture Loader.
  93921. */
  93922. var TGATextureLoader = /** @class */ (function () {
  93923. function TGATextureLoader() {
  93924. /**
  93925. * Defines wether the loader supports cascade loading the different faces.
  93926. */
  93927. this.supportCascades = false;
  93928. }
  93929. /**
  93930. * This returns if the loader support the current file information.
  93931. * @param extension defines the file extension of the file being loaded
  93932. * @param textureFormatInUse defines the current compressed format in use iun the engine
  93933. * @param fallback defines the fallback internal texture if any
  93934. * @param isBase64 defines whether the texture is encoded as a base64
  93935. * @param isBuffer defines whether the texture data are stored as a buffer
  93936. * @returns true if the loader can load the specified file
  93937. */
  93938. TGATextureLoader.prototype.canLoad = function (extension, textureFormatInUse, fallback, isBase64, isBuffer) {
  93939. return extension.indexOf(".tga") === 0;
  93940. };
  93941. /**
  93942. * Transform the url before loading if required.
  93943. * @param rootUrl the url of the texture
  93944. * @param textureFormatInUse defines the current compressed format in use iun the engine
  93945. * @returns the transformed texture
  93946. */
  93947. TGATextureLoader.prototype.transformUrl = function (rootUrl, textureFormatInUse) {
  93948. return rootUrl;
  93949. };
  93950. /**
  93951. * Gets the fallback url in case the load fail. This can return null to allow the default fallback mecanism to work
  93952. * @param rootUrl the url of the texture
  93953. * @param textureFormatInUse defines the current compressed format in use iun the engine
  93954. * @returns the fallback texture
  93955. */
  93956. TGATextureLoader.prototype.getFallbackTextureUrl = function (rootUrl, textureFormatInUse) {
  93957. return null;
  93958. };
  93959. /**
  93960. * Uploads the cube texture data to the WebGl Texture. It has alreday been bound.
  93961. * @param data contains the texture data
  93962. * @param texture defines the BabylonJS internal texture
  93963. * @param createPolynomials will be true if polynomials have been requested
  93964. * @param onLoad defines the callback to trigger once the texture is ready
  93965. * @param onError defines the callback to trigger in case of error
  93966. */
  93967. TGATextureLoader.prototype.loadCubeData = function (data, texture, createPolynomials, onLoad, onError) {
  93968. throw ".env not supported in Cube.";
  93969. };
  93970. /**
  93971. * Uploads the 2D texture data to the WebGl Texture. It has alreday been bound once in the callback.
  93972. * @param data contains the texture data
  93973. * @param texture defines the BabylonJS internal texture
  93974. * @param callback defines the method to call once ready to upload
  93975. */
  93976. TGATextureLoader.prototype.loadData = function (data, texture, callback) {
  93977. var uintData = new Uint8Array(data);
  93978. var header = BABYLON.TGATools.GetTGAHeader(uintData);
  93979. callback(header.width, header.height, texture.generateMipMaps, false, function () {
  93980. BABYLON.TGATools.UploadContent(texture, uintData);
  93981. });
  93982. };
  93983. return TGATextureLoader;
  93984. }());
  93985. // Register the loader.
  93986. BABYLON.Engine._TextureLoaders.push(new TGATextureLoader());
  93987. })(BABYLON || (BABYLON = {}));
  93988. //# sourceMappingURL=babylon.tgaTextureLoader.js.map
  93989. var BABYLON;
  93990. (function (BABYLON) {
  93991. /**
  93992. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  93993. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  93994. */
  93995. var KhronosTextureContainer = /** @class */ (function () {
  93996. /**
  93997. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  93998. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  93999. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  94000. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  94001. */
  94002. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  94003. this.arrayBuffer = arrayBuffer;
  94004. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  94005. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  94006. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  94007. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  94008. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  94009. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  94010. BABYLON.Tools.Error("texture missing KTX identifier");
  94011. return;
  94012. }
  94013. // load the reset of the header in native 32 bit int
  94014. var header = new Int32Array(this.arrayBuffer, 12, 13);
  94015. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  94016. var oppositeEndianess = header[0] === 0x01020304;
  94017. // read all the header elements in order they exist in the file, without modification (sans endainness)
  94018. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  94019. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  94020. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  94021. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  94022. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  94023. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  94024. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  94025. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  94026. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  94027. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  94028. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  94029. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  94030. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  94031. if (this.glType !== 0) {
  94032. BABYLON.Tools.Error("only compressed formats currently supported");
  94033. return;
  94034. }
  94035. else {
  94036. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  94037. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  94038. }
  94039. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  94040. BABYLON.Tools.Error("only 2D textures currently supported");
  94041. return;
  94042. }
  94043. if (this.numberOfArrayElements !== 0) {
  94044. BABYLON.Tools.Error("texture arrays not currently supported");
  94045. return;
  94046. }
  94047. if (this.numberOfFaces !== facesExpected) {
  94048. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  94049. return;
  94050. }
  94051. // we now have a completely validated file, so could use existence of loadType as success
  94052. // would need to make this more elaborate & adjust checks above to support more than one load type
  94053. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  94054. }
  94055. // not as fast hardware based, but will probably never need to use
  94056. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  94057. return ((val & 0xFF) << 24)
  94058. | ((val & 0xFF00) << 8)
  94059. | ((val >> 8) & 0xFF00)
  94060. | ((val >> 24) & 0xFF);
  94061. };
  94062. /**
  94063. * Uploads KTX content to a Babylon Texture.
  94064. * It is assumed that the texture has already been created & is currently bound
  94065. * @hidden
  94066. */
  94067. KhronosTextureContainer.prototype.uploadLevels = function (texture, loadMipmaps) {
  94068. switch (this.loadType) {
  94069. case KhronosTextureContainer.COMPRESSED_2D:
  94070. this._upload2DCompressedLevels(texture, loadMipmaps);
  94071. break;
  94072. case KhronosTextureContainer.TEX_2D:
  94073. case KhronosTextureContainer.COMPRESSED_3D:
  94074. case KhronosTextureContainer.TEX_3D:
  94075. }
  94076. };
  94077. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (texture, loadMipmaps) {
  94078. // initialize width & height for level 1
  94079. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  94080. var width = this.pixelWidth;
  94081. var height = this.pixelHeight;
  94082. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  94083. for (var level = 0; level < mipmapCount; level++) {
  94084. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  94085. dataOffset += 4; //image data starts from next multiple of 4 offset. Each face refers to same imagesize field above.
  94086. for (var face = 0; face < this.numberOfFaces; face++) {
  94087. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset, imageSize);
  94088. var engine = texture.getEngine();
  94089. engine._uploadCompressedDataToTextureDirectly(texture, this.glInternalFormat, width, height, byteArray, face, level);
  94090. dataOffset += imageSize; // add size of the image for the next face/mipmap
  94091. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  94092. }
  94093. width = Math.max(1.0, width * 0.5);
  94094. height = Math.max(1.0, height * 0.5);
  94095. }
  94096. };
  94097. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  94098. // load types
  94099. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  94100. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  94101. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  94102. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  94103. return KhronosTextureContainer;
  94104. }());
  94105. BABYLON.KhronosTextureContainer = KhronosTextureContainer;
  94106. })(BABYLON || (BABYLON = {}));
  94107. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  94108. var BABYLON;
  94109. (function (BABYLON) {
  94110. /**
  94111. * Implementation of the KTX Texture Loader.
  94112. */
  94113. var KTXTextureLoader = /** @class */ (function () {
  94114. function KTXTextureLoader() {
  94115. /**
  94116. * Defines wether the loader supports cascade loading the different faces.
  94117. */
  94118. this.supportCascades = false;
  94119. }
  94120. /**
  94121. * This returns if the loader support the current file information.
  94122. * @param extension defines the file extension of the file being loaded
  94123. * @param textureFormatInUse defines the current compressed format in use iun the engine
  94124. * @param fallback defines the fallback internal texture if any
  94125. * @param isBase64 defines whether the texture is encoded as a base64
  94126. * @param isBuffer defines whether the texture data are stored as a buffer
  94127. * @returns true if the loader can load the specified file
  94128. */
  94129. KTXTextureLoader.prototype.canLoad = function (extension, textureFormatInUse, fallback, isBase64, isBuffer) {
  94130. if (textureFormatInUse && !isBase64 && !fallback && !isBuffer) {
  94131. return true;
  94132. }
  94133. return false;
  94134. };
  94135. /**
  94136. * Transform the url before loading if required.
  94137. * @param rootUrl the url of the texture
  94138. * @param textureFormatInUse defines the current compressed format in use iun the engine
  94139. * @returns the transformed texture
  94140. */
  94141. KTXTextureLoader.prototype.transformUrl = function (rootUrl, textureFormatInUse) {
  94142. var lastDot = rootUrl.lastIndexOf('.');
  94143. return (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + textureFormatInUse;
  94144. };
  94145. /**
  94146. * Gets the fallback url in case the load fail. This can return null to allow the default fallback mecanism to work
  94147. * @param rootUrl the url of the texture
  94148. * @param textureFormatInUse defines the current compressed format in use iun the engine
  94149. * @returns the fallback texture
  94150. */
  94151. KTXTextureLoader.prototype.getFallbackTextureUrl = function (rootUrl, textureFormatInUse) {
  94152. // remove the format appended to the rootUrl in the original createCubeTexture call.
  94153. var exp = new RegExp("" + textureFormatInUse + "$");
  94154. return rootUrl.replace(exp, "");
  94155. };
  94156. /**
  94157. * Uploads the cube texture data to the WebGl Texture. It has alreday been bound.
  94158. * @param data contains the texture data
  94159. * @param texture defines the BabylonJS internal texture
  94160. * @param createPolynomials will be true if polynomials have been requested
  94161. * @param onLoad defines the callback to trigger once the texture is ready
  94162. * @param onError defines the callback to trigger in case of error
  94163. */
  94164. KTXTextureLoader.prototype.loadCubeData = function (data, texture, createPolynomials, onLoad, onError) {
  94165. if (Array.isArray(data)) {
  94166. return;
  94167. }
  94168. var engine = texture.getEngine();
  94169. var ktx = new BABYLON.KhronosTextureContainer(data, 6);
  94170. var loadMipmap = ktx.numberOfMipmapLevels > 1 && texture.generateMipMaps;
  94171. engine._unpackFlipY(true);
  94172. ktx.uploadLevels(texture, texture.generateMipMaps);
  94173. texture.width = ktx.pixelWidth;
  94174. texture.height = ktx.pixelHeight;
  94175. engine._setCubeMapTextureParams(loadMipmap);
  94176. texture.isReady = true;
  94177. };
  94178. /**
  94179. * Uploads the 2D texture data to the WebGl Texture. It has alreday been bound once in the callback.
  94180. * @param data contains the texture data
  94181. * @param texture defines the BabylonJS internal texture
  94182. * @param callback defines the method to call once ready to upload
  94183. */
  94184. KTXTextureLoader.prototype.loadData = function (data, texture, callback) {
  94185. var ktx = new BABYLON.KhronosTextureContainer(data, 1);
  94186. callback(ktx.pixelWidth, ktx.pixelHeight, false, true, function () {
  94187. ktx.uploadLevels(texture, texture.generateMipMaps);
  94188. });
  94189. };
  94190. return KTXTextureLoader;
  94191. }());
  94192. // Register the loader.
  94193. BABYLON.Engine._TextureLoaders.unshift(new KTXTextureLoader());
  94194. })(BABYLON || (BABYLON = {}));
  94195. //# sourceMappingURL=babylon.ktxTextureLoader.js.map
  94196. var BABYLON;
  94197. (function (BABYLON) {
  94198. /**
  94199. * Sets of helpers addressing the serialization and deserialization of environment texture
  94200. * stored in a BabylonJS env file.
  94201. * Those files are usually stored as .env files.
  94202. */
  94203. var EnvironmentTextureTools = /** @class */ (function () {
  94204. function EnvironmentTextureTools() {
  94205. }
  94206. /**
  94207. * Gets the environment info from an env file.
  94208. * @param data The array buffer containing the .env bytes.
  94209. * @returns the environment file info (the json header) if successfully parsed.
  94210. */
  94211. EnvironmentTextureTools.GetEnvInfo = function (data) {
  94212. var dataView = new DataView(data);
  94213. var pos = 0;
  94214. for (var i = 0; i < EnvironmentTextureTools._MagicBytes.length; i++) {
  94215. if (dataView.getUint8(pos++) !== EnvironmentTextureTools._MagicBytes[i]) {
  94216. BABYLON.Tools.Error('Not a babylon environment map');
  94217. return null;
  94218. }
  94219. }
  94220. // Read json manifest - collect characters up to null terminator
  94221. var manifestString = '';
  94222. var charCode = 0x00;
  94223. while ((charCode = dataView.getUint8(pos++))) {
  94224. manifestString += String.fromCharCode(charCode);
  94225. }
  94226. var manifest = JSON.parse(manifestString);
  94227. if (manifest.specular) {
  94228. // Extend the header with the position of the payload.
  94229. manifest.specular.specularDataPosition = pos;
  94230. // Fallback to 0.8 exactly if lodGenerationScale is not defined for backward compatibility.
  94231. manifest.specular.lodGenerationScale = manifest.specular.lodGenerationScale || 0.8;
  94232. }
  94233. return manifest;
  94234. };
  94235. /**
  94236. * Creates an environment texture from a loaded cube texture.
  94237. * @param texture defines the cube texture to convert in env file
  94238. * @return a promise containing the environment data if succesfull.
  94239. */
  94240. EnvironmentTextureTools.CreateEnvTextureAsync = function (texture) {
  94241. var _this = this;
  94242. var internalTexture = texture.getInternalTexture();
  94243. if (!internalTexture) {
  94244. return Promise.reject("The cube texture is invalid.");
  94245. }
  94246. if (!texture._prefiltered) {
  94247. return Promise.reject("The cube texture is invalid (not prefiltered).");
  94248. }
  94249. var engine = internalTexture.getEngine();
  94250. if (engine && engine.premultipliedAlpha) {
  94251. return Promise.reject("Env texture can only be created when the engine is created with the premultipliedAlpha option set to false.");
  94252. }
  94253. if (texture.textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  94254. return Promise.reject("The cube texture should allow HDR (Full Float or Half Float).");
  94255. }
  94256. var canvas = engine.getRenderingCanvas();
  94257. if (!canvas) {
  94258. return Promise.reject("Env texture can only be created when the engine is associated to a canvas.");
  94259. }
  94260. var textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  94261. if (!engine.getCaps().textureFloatRender) {
  94262. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  94263. if (!engine.getCaps().textureHalfFloatRender) {
  94264. return Promise.reject("Env texture can only be created when the browser supports half float or full float rendering.");
  94265. }
  94266. }
  94267. var cubeWidth = internalTexture.width;
  94268. var hostingScene = new BABYLON.Scene(engine);
  94269. var specularTextures = {};
  94270. var promises = [];
  94271. // Read and collect all mipmaps data from the cube.
  94272. var mipmapsCount = BABYLON.Scalar.Log2(internalTexture.width);
  94273. mipmapsCount = Math.round(mipmapsCount);
  94274. var _loop_1 = function (i) {
  94275. var faceWidth = Math.pow(2, mipmapsCount - i);
  94276. var _loop_2 = function (face) {
  94277. var data = texture.readPixels(face, i);
  94278. // Creates a temp texture with the face data.
  94279. var tempTexture = engine.createRawTexture(data, faceWidth, faceWidth, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE, null, textureType);
  94280. // And rgbdEncode them.
  94281. var promise = new Promise(function (resolve, reject) {
  94282. 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);
  94283. rgbdPostProcess.getEffect().executeWhenCompiled(function () {
  94284. rgbdPostProcess.onApply = function (effect) {
  94285. effect._bindTexture("textureSampler", tempTexture);
  94286. };
  94287. // As the process needs to happen on the main canvas, keep track of the current size
  94288. var currentW = engine.getRenderWidth();
  94289. var currentH = engine.getRenderHeight();
  94290. // Set the desired size for the texture
  94291. engine.setSize(faceWidth, faceWidth);
  94292. hostingScene.postProcessManager.directRender([rgbdPostProcess], null);
  94293. // Reading datas from WebGL
  94294. BABYLON.Tools.ToBlob(canvas, function (blob) {
  94295. var fileReader = new FileReader();
  94296. fileReader.onload = function (event) {
  94297. var arrayBuffer = event.target.result;
  94298. specularTextures[i * 6 + face] = arrayBuffer;
  94299. resolve();
  94300. };
  94301. fileReader.readAsArrayBuffer(blob);
  94302. });
  94303. // Reapply the previous canvas size
  94304. engine.setSize(currentW, currentH);
  94305. });
  94306. });
  94307. promises.push(promise);
  94308. };
  94309. // All faces of the cube.
  94310. for (var face = 0; face < 6; face++) {
  94311. _loop_2(face);
  94312. }
  94313. };
  94314. for (var i = 0; i <= mipmapsCount; i++) {
  94315. _loop_1(i);
  94316. }
  94317. // Once all the textures haves been collected as RGBD stored in PNGs
  94318. return Promise.all(promises).then(function () {
  94319. // We can delete the hosting scene keeping track of all the creation objects
  94320. hostingScene.dispose();
  94321. // Creates the json header for the env texture
  94322. var info = {
  94323. version: 1,
  94324. width: cubeWidth,
  94325. irradiance: _this._CreateEnvTextureIrradiance(texture),
  94326. specular: {
  94327. mipmaps: [],
  94328. lodGenerationScale: texture.lodGenerationScale
  94329. }
  94330. };
  94331. // Sets the specular image data information
  94332. var position = 0;
  94333. for (var i = 0; i <= mipmapsCount; i++) {
  94334. for (var face = 0; face < 6; face++) {
  94335. var byteLength = specularTextures[i * 6 + face].byteLength;
  94336. info.specular.mipmaps.push({
  94337. length: byteLength,
  94338. position: position
  94339. });
  94340. position += byteLength;
  94341. }
  94342. }
  94343. // Encode the JSON as an array buffer
  94344. var infoString = JSON.stringify(info);
  94345. var infoBuffer = new ArrayBuffer(infoString.length + 1);
  94346. var infoView = new Uint8Array(infoBuffer); // Limited to ascii subset matching unicode.
  94347. for (var i = 0, strLen = infoString.length; i < strLen; i++) {
  94348. infoView[i] = infoString.charCodeAt(i);
  94349. }
  94350. // Ends up with a null terminator for easier parsing
  94351. infoView[infoString.length] = 0x00;
  94352. // Computes the final required size and creates the storage
  94353. var totalSize = EnvironmentTextureTools._MagicBytes.length + position + infoBuffer.byteLength;
  94354. var finalBuffer = new ArrayBuffer(totalSize);
  94355. var finalBufferView = new Uint8Array(finalBuffer);
  94356. var dataView = new DataView(finalBuffer);
  94357. // Copy the magic bytes identifying the file in
  94358. var pos = 0;
  94359. for (var i = 0; i < EnvironmentTextureTools._MagicBytes.length; i++) {
  94360. dataView.setUint8(pos++, EnvironmentTextureTools._MagicBytes[i]);
  94361. }
  94362. // Add the json info
  94363. finalBufferView.set(new Uint8Array(infoBuffer), pos);
  94364. pos += infoBuffer.byteLength;
  94365. // Finally inserts the texture data
  94366. for (var i = 0; i <= mipmapsCount; i++) {
  94367. for (var face = 0; face < 6; face++) {
  94368. var dataBuffer = specularTextures[i * 6 + face];
  94369. finalBufferView.set(new Uint8Array(dataBuffer), pos);
  94370. pos += dataBuffer.byteLength;
  94371. }
  94372. }
  94373. // Voila
  94374. return finalBuffer;
  94375. });
  94376. };
  94377. /**
  94378. * Creates a JSON representation of the spherical data.
  94379. * @param texture defines the texture containing the polynomials
  94380. * @return the JSON representation of the spherical info
  94381. */
  94382. EnvironmentTextureTools._CreateEnvTextureIrradiance = function (texture) {
  94383. var polynmials = texture.sphericalPolynomial;
  94384. if (polynmials == null) {
  94385. return null;
  94386. }
  94387. return {
  94388. x: [polynmials.x.x, polynmials.x.y, polynmials.x.z],
  94389. y: [polynmials.y.x, polynmials.y.y, polynmials.y.z],
  94390. z: [polynmials.z.x, polynmials.z.y, polynmials.z.z],
  94391. xx: [polynmials.xx.x, polynmials.xx.y, polynmials.xx.z],
  94392. yy: [polynmials.yy.x, polynmials.yy.y, polynmials.yy.z],
  94393. zz: [polynmials.zz.x, polynmials.zz.y, polynmials.zz.z],
  94394. yz: [polynmials.yz.x, polynmials.yz.y, polynmials.yz.z],
  94395. zx: [polynmials.zx.x, polynmials.zx.y, polynmials.zx.z],
  94396. xy: [polynmials.xy.x, polynmials.xy.y, polynmials.xy.z]
  94397. };
  94398. };
  94399. /**
  94400. * Uploads the texture info contained in the env file to the GPU.
  94401. * @param texture defines the internal texture to upload to
  94402. * @param arrayBuffer defines the buffer cotaining the data to load
  94403. * @param info defines the texture info retrieved through the GetEnvInfo method
  94404. * @returns a promise
  94405. */
  94406. EnvironmentTextureTools.UploadEnvLevelsAsync = function (texture, arrayBuffer, info) {
  94407. if (info.version !== 1) {
  94408. throw new Error("Unsupported babylon environment map version \"" + info.version + "\"");
  94409. }
  94410. var specularInfo = info.specular;
  94411. if (!specularInfo) {
  94412. // Nothing else parsed so far
  94413. return Promise.resolve();
  94414. }
  94415. // Double checks the enclosed info
  94416. var mipmapsCount = BABYLON.Scalar.Log2(info.width);
  94417. mipmapsCount = Math.round(mipmapsCount) + 1;
  94418. if (specularInfo.mipmaps.length !== 6 * mipmapsCount) {
  94419. throw new Error("Unsupported specular mipmaps number \"" + specularInfo.mipmaps.length + "\"");
  94420. }
  94421. texture._lodGenerationScale = specularInfo.lodGenerationScale;
  94422. var imageData = new Array(mipmapsCount);
  94423. for (var i = 0; i < mipmapsCount; i++) {
  94424. imageData[i] = new Array(6);
  94425. for (var face = 0; face < 6; face++) {
  94426. var imageInfo = specularInfo.mipmaps[i * 6 + face];
  94427. imageData[i][face] = new Uint8Array(arrayBuffer, specularInfo.specularDataPosition + imageInfo.position, imageInfo.length);
  94428. }
  94429. }
  94430. return EnvironmentTextureTools.UploadLevelsAsync(texture, imageData);
  94431. };
  94432. /**
  94433. * Uploads the levels of image data to the GPU.
  94434. * @param texture defines the internal texture to upload to
  94435. * @param imageData defines the array buffer views of image data [mipmap][face]
  94436. * @returns a promise
  94437. */
  94438. EnvironmentTextureTools.UploadLevelsAsync = function (texture, imageData) {
  94439. if (!BABYLON.Tools.IsExponentOfTwo(texture.width)) {
  94440. throw new Error("Texture size must be a power of two");
  94441. }
  94442. var mipmapsCount = Math.round(BABYLON.Scalar.Log2(texture.width)) + 1;
  94443. // Gets everything ready.
  94444. var engine = texture.getEngine();
  94445. var expandTexture = false;
  94446. var generateNonLODTextures = false;
  94447. var rgbdPostProcess = null;
  94448. var cubeRtt = null;
  94449. var lodTextures = null;
  94450. var caps = engine.getCaps();
  94451. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  94452. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  94453. texture.generateMipMaps = true;
  94454. engine.updateTextureSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE, texture);
  94455. // Add extra process if texture lod is not supported
  94456. if (!caps.textureLOD) {
  94457. expandTexture = false;
  94458. generateNonLODTextures = true;
  94459. lodTextures = {};
  94460. }
  94461. // in webgl 1 there are no ways to either render or copy lod level information for float textures.
  94462. else if (engine.webGLVersion < 2) {
  94463. expandTexture = false;
  94464. }
  94465. // If half float available we can uncompress the texture
  94466. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  94467. expandTexture = true;
  94468. texture.type = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  94469. }
  94470. // If full float available we can uncompress the texture
  94471. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  94472. expandTexture = true;
  94473. texture.type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  94474. }
  94475. // Expand the texture if possible
  94476. if (expandTexture) {
  94477. // Simply run through the decode PP
  94478. rgbdPostProcess = new BABYLON.PostProcess("rgbdDecode", "rgbdDecode", null, null, 1, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, engine, false, undefined, texture.type, undefined, null, false);
  94479. texture._isRGBD = false;
  94480. texture.invertY = false;
  94481. cubeRtt = engine.createRenderTargetCubeTexture(texture.width, {
  94482. generateDepthBuffer: false,
  94483. generateMipMaps: true,
  94484. generateStencilBuffer: false,
  94485. samplingMode: BABYLON.Texture.TRILINEAR_SAMPLINGMODE,
  94486. type: texture.type,
  94487. format: BABYLON.Engine.TEXTUREFORMAT_RGBA
  94488. });
  94489. }
  94490. else {
  94491. texture._isRGBD = true;
  94492. texture.invertY = true;
  94493. // In case of missing support, applies the same patch than DDS files.
  94494. if (generateNonLODTextures) {
  94495. var mipSlices = 3;
  94496. var scale = texture._lodGenerationScale;
  94497. var offset = texture._lodGenerationOffset;
  94498. for (var i = 0; i < mipSlices; i++) {
  94499. //compute LOD from even spacing in smoothness (matching shader calculation)
  94500. var smoothness = i / (mipSlices - 1);
  94501. var roughness = 1 - smoothness;
  94502. var minLODIndex = offset; // roughness = 0
  94503. var maxLODIndex = (mipmapsCount - 1) * scale + offset; // roughness = 1 (mipmaps start from 0)
  94504. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  94505. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  94506. var glTextureFromLod = new BABYLON.InternalTexture(engine, BABYLON.InternalTexture.DATASOURCE_TEMP);
  94507. glTextureFromLod.isCube = true;
  94508. glTextureFromLod.invertY = true;
  94509. glTextureFromLod.generateMipMaps = false;
  94510. engine.updateTextureSamplingMode(BABYLON.Texture.LINEAR_LINEAR, glTextureFromLod);
  94511. // Wrap in a base texture for easy binding.
  94512. var lodTexture = new BABYLON.BaseTexture(null);
  94513. lodTexture.isCube = true;
  94514. lodTexture._texture = glTextureFromLod;
  94515. lodTextures[mipmapIndex] = lodTexture;
  94516. switch (i) {
  94517. case 0:
  94518. texture._lodTextureLow = lodTexture;
  94519. break;
  94520. case 1:
  94521. texture._lodTextureMid = lodTexture;
  94522. break;
  94523. case 2:
  94524. texture._lodTextureHigh = lodTexture;
  94525. break;
  94526. }
  94527. }
  94528. }
  94529. }
  94530. var promises = [];
  94531. var _loop_3 = function (i) {
  94532. var _loop_4 = function (face) {
  94533. // Constructs an image element from image data
  94534. var bytes = imageData[i][face];
  94535. var blob = new Blob([bytes], { type: 'image/png' });
  94536. var url = URL.createObjectURL(blob);
  94537. var image = new Image();
  94538. image.src = url;
  94539. // Enqueue promise to upload to the texture.
  94540. var promise = new Promise(function (resolve, reject) {
  94541. image.onload = function () {
  94542. if (expandTexture) {
  94543. var tempTexture_1 = engine.createTexture(null, true, true, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, null, function (message) {
  94544. reject(message);
  94545. }, image);
  94546. rgbdPostProcess.getEffect().executeWhenCompiled(function () {
  94547. // Uncompress the data to a RTT
  94548. rgbdPostProcess.onApply = function (effect) {
  94549. effect._bindTexture("textureSampler", tempTexture_1);
  94550. effect.setFloat2("scale", 1, 1);
  94551. };
  94552. engine.scenes[0].postProcessManager.directRender([rgbdPostProcess], cubeRtt, true, face, i);
  94553. // Cleanup
  94554. engine.restoreDefaultFramebuffer();
  94555. tempTexture_1.dispose();
  94556. window.URL.revokeObjectURL(url);
  94557. resolve();
  94558. });
  94559. }
  94560. else {
  94561. engine._uploadImageToTexture(texture, image, face, i);
  94562. // Upload the face to the non lod texture support
  94563. if (generateNonLODTextures) {
  94564. var lodTexture = lodTextures[i];
  94565. if (lodTexture) {
  94566. engine._uploadImageToTexture(lodTexture._texture, image, face, 0);
  94567. }
  94568. }
  94569. resolve();
  94570. }
  94571. };
  94572. image.onerror = function (error) {
  94573. reject(error);
  94574. };
  94575. });
  94576. promises.push(promise);
  94577. };
  94578. // All faces
  94579. for (var face = 0; face < 6; face++) {
  94580. _loop_4(face);
  94581. }
  94582. };
  94583. // All mipmaps up to provided number of images
  94584. for (var i = 0; i < imageData.length; i++) {
  94585. _loop_3(i);
  94586. }
  94587. // Fill remaining mipmaps with black textures.
  94588. if (imageData.length < mipmapsCount) {
  94589. var data = void 0;
  94590. var size = Math.pow(2, mipmapsCount - 1 - imageData.length);
  94591. var dataLength = size * size * 4;
  94592. switch (texture.type) {
  94593. case BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT: {
  94594. data = new Uint8Array(dataLength);
  94595. break;
  94596. }
  94597. case BABYLON.Engine.TEXTURETYPE_HALF_FLOAT: {
  94598. data = new Uint16Array(dataLength);
  94599. break;
  94600. }
  94601. case BABYLON.Engine.TEXTURETYPE_FLOAT: {
  94602. data = new Float32Array(dataLength);
  94603. break;
  94604. }
  94605. }
  94606. for (var i = imageData.length; i < mipmapsCount; i++) {
  94607. for (var face = 0; face < 6; face++) {
  94608. engine._uploadArrayBufferViewToTexture(texture, data, face, i);
  94609. }
  94610. }
  94611. }
  94612. // Once all done, finishes the cleanup and return
  94613. return Promise.all(promises).then(function () {
  94614. // Release temp RTT.
  94615. if (cubeRtt) {
  94616. engine._releaseFramebufferObjects(cubeRtt);
  94617. cubeRtt._swapAndDie(texture);
  94618. }
  94619. // Release temp Post Process.
  94620. if (rgbdPostProcess) {
  94621. rgbdPostProcess.dispose();
  94622. }
  94623. // Flag internal texture as ready in case they are in use.
  94624. if (generateNonLODTextures) {
  94625. if (texture._lodTextureHigh && texture._lodTextureHigh._texture) {
  94626. texture._lodTextureHigh._texture.isReady = true;
  94627. }
  94628. if (texture._lodTextureMid && texture._lodTextureMid._texture) {
  94629. texture._lodTextureMid._texture.isReady = true;
  94630. }
  94631. if (texture._lodTextureLow && texture._lodTextureLow._texture) {
  94632. texture._lodTextureLow._texture.isReady = true;
  94633. }
  94634. }
  94635. });
  94636. };
  94637. /**
  94638. * Uploads spherical polynomials information to the texture.
  94639. * @param texture defines the texture we are trying to upload the information to
  94640. * @param info defines the environment texture info retrieved through the GetEnvInfo method
  94641. */
  94642. EnvironmentTextureTools.UploadEnvSpherical = function (texture, info) {
  94643. if (info.version !== 1) {
  94644. BABYLON.Tools.Warn('Unsupported babylon environment map version "' + info.version + '"');
  94645. }
  94646. var irradianceInfo = info.irradiance;
  94647. if (!irradianceInfo) {
  94648. return;
  94649. }
  94650. var sp = new BABYLON.SphericalPolynomial();
  94651. BABYLON.Vector3.FromArrayToRef(irradianceInfo.x, 0, sp.x);
  94652. BABYLON.Vector3.FromArrayToRef(irradianceInfo.y, 0, sp.y);
  94653. BABYLON.Vector3.FromArrayToRef(irradianceInfo.z, 0, sp.z);
  94654. BABYLON.Vector3.FromArrayToRef(irradianceInfo.xx, 0, sp.xx);
  94655. BABYLON.Vector3.FromArrayToRef(irradianceInfo.yy, 0, sp.yy);
  94656. BABYLON.Vector3.FromArrayToRef(irradianceInfo.zz, 0, sp.zz);
  94657. BABYLON.Vector3.FromArrayToRef(irradianceInfo.yz, 0, sp.yz);
  94658. BABYLON.Vector3.FromArrayToRef(irradianceInfo.zx, 0, sp.zx);
  94659. BABYLON.Vector3.FromArrayToRef(irradianceInfo.xy, 0, sp.xy);
  94660. texture._sphericalPolynomial = sp;
  94661. };
  94662. /**
  94663. * Magic number identifying the env file.
  94664. */
  94665. EnvironmentTextureTools._MagicBytes = [0x86, 0x16, 0x87, 0x96, 0xf6, 0xd6, 0x96, 0x36];
  94666. return EnvironmentTextureTools;
  94667. }());
  94668. BABYLON.EnvironmentTextureTools = EnvironmentTextureTools;
  94669. })(BABYLON || (BABYLON = {}));
  94670. //# sourceMappingURL=babylon.environmentTextureTools.js.map
  94671. var BABYLON;
  94672. (function (BABYLON) {
  94673. /**
  94674. * Implementation of the ENV Texture Loader.
  94675. */
  94676. var ENVTextureLoader = /** @class */ (function () {
  94677. function ENVTextureLoader() {
  94678. /**
  94679. * Defines wether the loader supports cascade loading the different faces.
  94680. */
  94681. this.supportCascades = false;
  94682. }
  94683. /**
  94684. * This returns if the loader support the current file information.
  94685. * @param extension defines the file extension of the file being loaded
  94686. * @param textureFormatInUse defines the current compressed format in use iun the engine
  94687. * @param fallback defines the fallback internal texture if any
  94688. * @param isBase64 defines whether the texture is encoded as a base64
  94689. * @param isBuffer defines whether the texture data are stored as a buffer
  94690. * @returns true if the loader can load the specified file
  94691. */
  94692. ENVTextureLoader.prototype.canLoad = function (extension, textureFormatInUse, fallback, isBase64, isBuffer) {
  94693. return extension.indexOf(".env") === 0;
  94694. };
  94695. /**
  94696. * Transform the url before loading if required.
  94697. * @param rootUrl the url of the texture
  94698. * @param textureFormatInUse defines the current compressed format in use iun the engine
  94699. * @returns the transformed texture
  94700. */
  94701. ENVTextureLoader.prototype.transformUrl = function (rootUrl, textureFormatInUse) {
  94702. return rootUrl;
  94703. };
  94704. /**
  94705. * Gets the fallback url in case the load fail. This can return null to allow the default fallback mecanism to work
  94706. * @param rootUrl the url of the texture
  94707. * @param textureFormatInUse defines the current compressed format in use iun the engine
  94708. * @returns the fallback texture
  94709. */
  94710. ENVTextureLoader.prototype.getFallbackTextureUrl = function (rootUrl, textureFormatInUse) {
  94711. return null;
  94712. };
  94713. /**
  94714. * Uploads the cube texture data to the WebGl Texture. It has alreday been bound.
  94715. * @param data contains the texture data
  94716. * @param texture defines the BabylonJS internal texture
  94717. * @param createPolynomials will be true if polynomials have been requested
  94718. * @param onLoad defines the callback to trigger once the texture is ready
  94719. * @param onError defines the callback to trigger in case of error
  94720. */
  94721. ENVTextureLoader.prototype.loadCubeData = function (data, texture, createPolynomials, onLoad, onError) {
  94722. if (Array.isArray(data)) {
  94723. return;
  94724. }
  94725. data = data;
  94726. var info = BABYLON.EnvironmentTextureTools.GetEnvInfo(data);
  94727. if (info) {
  94728. texture.width = info.width;
  94729. texture.height = info.width;
  94730. BABYLON.EnvironmentTextureTools.UploadEnvSpherical(texture, info);
  94731. BABYLON.EnvironmentTextureTools.UploadEnvLevelsAsync(texture, data, info).then(function () {
  94732. texture.isReady = true;
  94733. if (onLoad) {
  94734. onLoad();
  94735. }
  94736. });
  94737. }
  94738. else if (onError) {
  94739. onError("Can not parse the environment file", null);
  94740. }
  94741. };
  94742. /**
  94743. * Uploads the 2D texture data to the WebGl Texture. It has alreday been bound once in the callback.
  94744. * @param data contains the texture data
  94745. * @param texture defines the BabylonJS internal texture
  94746. * @param callback defines the method to call once ready to upload
  94747. */
  94748. ENVTextureLoader.prototype.loadData = function (data, texture, callback) {
  94749. throw ".env not supported in 2d.";
  94750. };
  94751. return ENVTextureLoader;
  94752. }());
  94753. // Register the loader.
  94754. BABYLON.Engine._TextureLoaders.push(new ENVTextureLoader());
  94755. })(BABYLON || (BABYLON = {}));
  94756. //# sourceMappingURL=babylon.envTextureLoader.js.map
  94757. var BABYLON;
  94758. (function (BABYLON) {
  94759. /**
  94760. * Renders a layer on top of an existing scene
  94761. */
  94762. var UtilityLayerRenderer = /** @class */ (function () {
  94763. /**
  94764. * Instantiates a UtilityLayerRenderer
  94765. * @param originalScene the original scene that will be rendered on top of
  94766. */
  94767. function UtilityLayerRenderer(
  94768. /** the original scene that will be rendered on top of */
  94769. originalScene) {
  94770. var _this = this;
  94771. this.originalScene = originalScene;
  94772. this._pointerCaptures = {};
  94773. this._lastPointerEvents = {};
  94774. /**
  94775. * If the utility layer should automatically be rendered on top of existing scene
  94776. */
  94777. this.shouldRender = true;
  94778. /**
  94779. * If set to true, only pointer down onPointerObservable events will be blocked when picking is occluded by original scene
  94780. */
  94781. this.onlyCheckPointerDownEvents = true;
  94782. /**
  94783. * If set to false, only pointerUp, pointerDown and pointerMove will be sent to the utilityLayerScene (false by default)
  94784. */
  94785. this.processAllEvents = false;
  94786. /**
  94787. * Observable raised when the pointer move from the utility layer scene to the main scene
  94788. */
  94789. this.onPointerOutObservable = new BABYLON.Observable();
  94790. // Create scene which will be rendered in the foreground and remove it from being referenced by engine to avoid interfering with existing app
  94791. this.utilityLayerScene = new BABYLON.Scene(originalScene.getEngine());
  94792. this.utilityLayerScene._allowPostProcessClearColor = false;
  94793. originalScene.getEngine().scenes.pop();
  94794. // Detach controls on utility scene, events will be fired by logic below to handle picking priority
  94795. this.utilityLayerScene.detachControl();
  94796. this._originalPointerObserver = originalScene.onPrePointerObservable.add(function (prePointerInfo, eventState) {
  94797. if (!_this.processAllEvents) {
  94798. if (prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERMOVE
  94799. && prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERUP
  94800. && prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERDOWN) {
  94801. return;
  94802. }
  94803. }
  94804. var pointerEvent = (prePointerInfo.event);
  94805. if (originalScene.isPointerCaptured(pointerEvent.pointerId)) {
  94806. _this._pointerCaptures[pointerEvent.pointerId] = false;
  94807. return;
  94808. }
  94809. var utilityScenePick = prePointerInfo.ray ? _this.utilityLayerScene.pickWithRay(prePointerInfo.ray) : _this.utilityLayerScene.pick(originalScene.pointerX, originalScene.pointerY);
  94810. if (!prePointerInfo.ray && utilityScenePick) {
  94811. prePointerInfo.ray = utilityScenePick.ray;
  94812. }
  94813. // always fire the prepointer oversvable
  94814. _this.utilityLayerScene.onPrePointerObservable.notifyObservers(prePointerInfo);
  94815. // allow every non pointer down event to flow to the utility layer
  94816. if (_this.onlyCheckPointerDownEvents && prePointerInfo.type != BABYLON.PointerEventTypes.POINTERDOWN) {
  94817. if (!prePointerInfo.skipOnPointerObservable) {
  94818. _this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, utilityScenePick));
  94819. }
  94820. if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERUP && _this._pointerCaptures[pointerEvent.pointerId]) {
  94821. _this._pointerCaptures[pointerEvent.pointerId] = false;
  94822. }
  94823. return;
  94824. }
  94825. if (_this.utilityLayerScene.autoClearDepthAndStencil) {
  94826. // If this layer is an overlay, check if this layer was hit and if so, skip pointer events for the main scene
  94827. if (utilityScenePick && utilityScenePick.hit) {
  94828. if (!prePointerInfo.skipOnPointerObservable) {
  94829. _this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, utilityScenePick));
  94830. }
  94831. prePointerInfo.skipOnPointerObservable = true;
  94832. }
  94833. }
  94834. else {
  94835. var originalScenePick = prePointerInfo.ray ? originalScene.pickWithRay(prePointerInfo.ray) : originalScene.pick(originalScene.pointerX, originalScene.pointerY);
  94836. var pointerEvent_1 = (prePointerInfo.event);
  94837. // If the layer can be occluded by the original scene, only fire pointer events to the first layer that hit they ray
  94838. if (originalScenePick && utilityScenePick) {
  94839. // No pick in utility scene
  94840. if (utilityScenePick.distance === 0 && originalScenePick.pickedMesh) {
  94841. if (_this.mainSceneTrackerPredicate && _this.mainSceneTrackerPredicate(originalScenePick.pickedMesh)) {
  94842. // We touched an utility mesh present in the main scene
  94843. _this._notifyObservers(prePointerInfo, originalScenePick, pointerEvent_1);
  94844. prePointerInfo.skipOnPointerObservable = true;
  94845. }
  94846. else if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  94847. _this._pointerCaptures[pointerEvent_1.pointerId] = true;
  94848. }
  94849. }
  94850. else if (!_this._pointerCaptures[pointerEvent_1.pointerId] && (utilityScenePick.distance < originalScenePick.distance || originalScenePick.distance === 0)) {
  94851. // We pick something in utility scene or the pick in utility is closer than the one in main scene
  94852. _this._notifyObservers(prePointerInfo, utilityScenePick, pointerEvent_1);
  94853. // If a previous utility layer set this, do not unset this
  94854. if (!prePointerInfo.skipOnPointerObservable) {
  94855. prePointerInfo.skipOnPointerObservable = utilityScenePick.distance > 0;
  94856. }
  94857. }
  94858. else if (!_this._pointerCaptures[pointerEvent_1.pointerId] && (utilityScenePick.distance > originalScenePick.distance)) {
  94859. // We have a pick in both scenes but main is closer than utility
  94860. // We touched an utility mesh present in the main scene
  94861. if (_this.mainSceneTrackerPredicate && _this.mainSceneTrackerPredicate(originalScenePick.pickedMesh)) {
  94862. _this._notifyObservers(prePointerInfo, originalScenePick, pointerEvent_1);
  94863. prePointerInfo.skipOnPointerObservable = true;
  94864. }
  94865. else if (_this._lastPointerEvents[pointerEvent_1.pointerId]) {
  94866. // We need to send a last pointerup to the utilityLayerScene to make sure animations can complete
  94867. _this.onPointerOutObservable.notifyObservers(pointerEvent_1.pointerId);
  94868. delete _this._lastPointerEvents[pointerEvent_1.pointerId];
  94869. }
  94870. }
  94871. if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERUP && _this._pointerCaptures[pointerEvent_1.pointerId]) {
  94872. _this._pointerCaptures[pointerEvent_1.pointerId] = false;
  94873. }
  94874. }
  94875. }
  94876. });
  94877. // Render directly on top of existing scene without clearing
  94878. this.utilityLayerScene.autoClear = false;
  94879. this._afterRenderObserver = this.originalScene.onAfterRenderObservable.add(function () {
  94880. if (_this.shouldRender) {
  94881. _this.render();
  94882. }
  94883. });
  94884. this._sceneDisposeObserver = this.originalScene.onDisposeObservable.add(function () {
  94885. _this.dispose();
  94886. });
  94887. this._updateCamera();
  94888. }
  94889. Object.defineProperty(UtilityLayerRenderer, "DefaultUtilityLayer", {
  94890. /**
  94891. * A shared utility layer that can be used to overlay objects into a scene (Depth map of the previous scene is cleared before drawing on top of it)
  94892. */
  94893. get: function () {
  94894. if (UtilityLayerRenderer._DefaultUtilityLayer == null) {
  94895. UtilityLayerRenderer._DefaultUtilityLayer = new UtilityLayerRenderer(BABYLON.Engine.LastCreatedScene);
  94896. UtilityLayerRenderer._DefaultUtilityLayer.originalScene.onDisposeObservable.addOnce(function () {
  94897. UtilityLayerRenderer._DefaultUtilityLayer = null;
  94898. });
  94899. }
  94900. return UtilityLayerRenderer._DefaultUtilityLayer;
  94901. },
  94902. enumerable: true,
  94903. configurable: true
  94904. });
  94905. Object.defineProperty(UtilityLayerRenderer, "DefaultKeepDepthUtilityLayer", {
  94906. /**
  94907. * A shared utility layer that can be used to embed objects into a scene (Depth map of the previous scene is not cleared before drawing on top of it)
  94908. */
  94909. get: function () {
  94910. if (UtilityLayerRenderer._DefaultKeepDepthUtilityLayer == null) {
  94911. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer = new UtilityLayerRenderer(BABYLON.Engine.LastCreatedScene);
  94912. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer.utilityLayerScene.autoClearDepthAndStencil = false;
  94913. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer.originalScene.onDisposeObservable.addOnce(function () {
  94914. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer = null;
  94915. });
  94916. }
  94917. return UtilityLayerRenderer._DefaultKeepDepthUtilityLayer;
  94918. },
  94919. enumerable: true,
  94920. configurable: true
  94921. });
  94922. UtilityLayerRenderer.prototype._notifyObservers = function (prePointerInfo, pickInfo, pointerEvent) {
  94923. if (!prePointerInfo.skipOnPointerObservable) {
  94924. this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, pickInfo));
  94925. this._lastPointerEvents[pointerEvent.pointerId] = parseInt(pointerEvent.pointerType);
  94926. }
  94927. };
  94928. /**
  94929. * Renders the utility layers scene on top of the original scene
  94930. */
  94931. UtilityLayerRenderer.prototype.render = function () {
  94932. this._updateCamera();
  94933. if (this.utilityLayerScene.activeCamera) {
  94934. // Set the camera's scene to utility layers scene
  94935. var oldScene = this.utilityLayerScene.activeCamera.getScene();
  94936. var camera = this.utilityLayerScene.activeCamera;
  94937. camera._scene = this.utilityLayerScene;
  94938. if (camera.leftCamera) {
  94939. camera.leftCamera._scene = this.utilityLayerScene;
  94940. }
  94941. if (camera.rightCamera) {
  94942. camera.rightCamera._scene = this.utilityLayerScene;
  94943. }
  94944. this.utilityLayerScene.render(false);
  94945. // Reset camera's scene back to original
  94946. camera._scene = oldScene;
  94947. if (camera.leftCamera) {
  94948. camera.leftCamera._scene = oldScene;
  94949. }
  94950. if (camera.rightCamera) {
  94951. camera.rightCamera._scene = oldScene;
  94952. }
  94953. }
  94954. };
  94955. /**
  94956. * Disposes of the renderer
  94957. */
  94958. UtilityLayerRenderer.prototype.dispose = function () {
  94959. this.onPointerOutObservable.clear();
  94960. if (this._afterRenderObserver) {
  94961. this.originalScene.onAfterRenderObservable.remove(this._afterRenderObserver);
  94962. }
  94963. if (this._sceneDisposeObserver) {
  94964. this.originalScene.onDisposeObservable.remove(this._sceneDisposeObserver);
  94965. }
  94966. if (this._originalPointerObserver) {
  94967. this.originalScene.onPrePointerObservable.remove(this._originalPointerObserver);
  94968. }
  94969. this.utilityLayerScene.dispose();
  94970. };
  94971. UtilityLayerRenderer.prototype._updateCamera = function () {
  94972. this.utilityLayerScene.activeCamera = this.originalScene.activeCamera;
  94973. };
  94974. UtilityLayerRenderer._DefaultUtilityLayer = null;
  94975. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer = null;
  94976. return UtilityLayerRenderer;
  94977. }());
  94978. BABYLON.UtilityLayerRenderer = UtilityLayerRenderer;
  94979. })(BABYLON || (BABYLON = {}));
  94980. //# sourceMappingURL=babylon.utilityLayerRenderer.js.map
  94981. //# sourceMappingURL=babylon.behavior.js.map
  94982. var BABYLON;
  94983. (function (BABYLON) {
  94984. /**
  94985. * A behavior that when attached to a mesh will allow the mesh to be dragged around the screen based on pointer events
  94986. */
  94987. var PointerDragBehavior = /** @class */ (function () {
  94988. /**
  94989. * Creates a pointer drag behavior that can be attached to a mesh
  94990. * @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)
  94991. */
  94992. function PointerDragBehavior(options) {
  94993. /**
  94994. * The maximum tolerated angle between the drag plane and dragging pointer rays to trigger pointer events. Set to 0 to allow any angle (default: 0)
  94995. */
  94996. this.maxDragAngle = 0;
  94997. /**
  94998. * @hidden
  94999. */
  95000. this._useAlternatePickedPointAboveMaxDragAngle = false;
  95001. /**
  95002. * The id of the pointer that is currently interacting with the behavior (-1 when no pointer is active)
  95003. */
  95004. this.currentDraggingPointerID = -1;
  95005. /**
  95006. * If the behavior is currently in a dragging state
  95007. */
  95008. this.dragging = false;
  95009. /**
  95010. * 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)
  95011. */
  95012. this.dragDeltaRatio = 0.2;
  95013. /**
  95014. * If the drag plane orientation should be updated during the dragging (Default: true)
  95015. */
  95016. this.updateDragPlane = true;
  95017. // Debug mode will display drag planes to help visualize behavior
  95018. this._debugMode = false;
  95019. this._moving = false;
  95020. /**
  95021. * Fires each time the attached mesh is dragged with the pointer
  95022. * * delta between last drag position and current drag position in world space
  95023. * * dragDistance along the drag axis
  95024. * * dragPlaneNormal normal of the current drag plane used during the drag
  95025. * * dragPlanePoint in world space where the drag intersects the drag plane
  95026. */
  95027. this.onDragObservable = new BABYLON.Observable();
  95028. /**
  95029. * Fires each time a drag begins (eg. mouse down on mesh)
  95030. */
  95031. this.onDragStartObservable = new BABYLON.Observable();
  95032. /**
  95033. * Fires each time a drag ends (eg. mouse release after drag)
  95034. */
  95035. this.onDragEndObservable = new BABYLON.Observable();
  95036. /**
  95037. * If the attached mesh should be moved when dragged
  95038. */
  95039. this.moveAttached = true;
  95040. /**
  95041. * If the drag behavior will react to drag events (Default: true)
  95042. */
  95043. this.enabled = true;
  95044. /**
  95045. * If camera controls should be detached during the drag
  95046. */
  95047. this.detachCameraControls = true;
  95048. /**
  95049. * If set, the drag plane/axis will be rotated based on the attached mesh's world rotation (Default: true)
  95050. */
  95051. this.useObjectOrienationForDragging = true;
  95052. this._tmpVector = new BABYLON.Vector3(0, 0, 0);
  95053. this._alternatePickedPoint = new BABYLON.Vector3(0, 0, 0);
  95054. this._worldDragAxis = new BABYLON.Vector3(0, 0, 0);
  95055. this._targetPosition = new BABYLON.Vector3(0, 0, 0);
  95056. this._attachedElement = null;
  95057. this._startDragRay = new BABYLON.Ray(new BABYLON.Vector3(), new BABYLON.Vector3());
  95058. this._lastPointerRay = {};
  95059. this._dragDelta = new BABYLON.Vector3();
  95060. // Variables to avoid instantiation in the below method
  95061. this._pointA = new BABYLON.Vector3(0, 0, 0);
  95062. this._pointB = new BABYLON.Vector3(0, 0, 0);
  95063. this._pointC = new BABYLON.Vector3(0, 0, 0);
  95064. this._lineA = new BABYLON.Vector3(0, 0, 0);
  95065. this._lineB = new BABYLON.Vector3(0, 0, 0);
  95066. this._localAxis = new BABYLON.Vector3(0, 0, 0);
  95067. this._lookAt = new BABYLON.Vector3(0, 0, 0);
  95068. this._options = options ? options : {};
  95069. var optionCount = 0;
  95070. if (this._options.dragAxis) {
  95071. optionCount++;
  95072. }
  95073. if (this._options.dragPlaneNormal) {
  95074. optionCount++;
  95075. }
  95076. if (optionCount > 1) {
  95077. throw "Multiple drag modes specified in dragBehavior options. Only one expected";
  95078. }
  95079. }
  95080. Object.defineProperty(PointerDragBehavior.prototype, "name", {
  95081. /**
  95082. * The name of the behavior
  95083. */
  95084. get: function () {
  95085. return "PointerDrag";
  95086. },
  95087. enumerable: true,
  95088. configurable: true
  95089. });
  95090. /**
  95091. * Initializes the behavior
  95092. */
  95093. PointerDragBehavior.prototype.init = function () { };
  95094. /**
  95095. * Attaches the drag behavior the passed in mesh
  95096. * @param ownerNode The mesh that will be dragged around once attached
  95097. */
  95098. PointerDragBehavior.prototype.attach = function (ownerNode) {
  95099. var _this = this;
  95100. this._scene = ownerNode.getScene();
  95101. this._attachedNode = ownerNode;
  95102. // Initialize drag plane to not interfere with existing scene
  95103. if (!PointerDragBehavior._planeScene) {
  95104. if (this._debugMode) {
  95105. PointerDragBehavior._planeScene = this._scene;
  95106. }
  95107. else {
  95108. PointerDragBehavior._planeScene = new BABYLON.Scene(this._scene.getEngine());
  95109. PointerDragBehavior._planeScene.detachControl();
  95110. this._scene.getEngine().scenes.pop();
  95111. this._scene.onDisposeObservable.addOnce(function () {
  95112. PointerDragBehavior._planeScene.dispose();
  95113. PointerDragBehavior._planeScene = null;
  95114. });
  95115. }
  95116. }
  95117. this._dragPlane = BABYLON.Mesh.CreatePlane("pointerDragPlane", this._debugMode ? 1 : 10000, PointerDragBehavior._planeScene, false, BABYLON.Mesh.DOUBLESIDE);
  95118. // State of the drag
  95119. this.lastDragPosition = new BABYLON.Vector3(0, 0, 0);
  95120. var pickPredicate = function (m) {
  95121. return _this._attachedNode == m || m.isDescendantOf(_this._attachedNode);
  95122. };
  95123. this._pointerObserver = this._scene.onPointerObservable.add(function (pointerInfo, eventState) {
  95124. if (!_this.enabled) {
  95125. return;
  95126. }
  95127. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  95128. if (!_this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.hit && pointerInfo.pickInfo.pickedMesh && pointerInfo.pickInfo.pickedPoint && pointerInfo.pickInfo.ray && pickPredicate(pointerInfo.pickInfo.pickedMesh)) {
  95129. _this._startDrag(pointerInfo.event.pointerId, pointerInfo.pickInfo.ray, pointerInfo.pickInfo.pickedPoint);
  95130. }
  95131. }
  95132. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERUP) {
  95133. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId) {
  95134. _this.releaseDrag();
  95135. }
  95136. }
  95137. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERMOVE) {
  95138. var pointerId = pointerInfo.event.pointerId;
  95139. // If drag was started with anyMouseID specified, set pointerID to the next mouse that moved
  95140. if (_this.currentDraggingPointerID === PointerDragBehavior._AnyMouseID && pointerId !== PointerDragBehavior._AnyMouseID && pointerInfo.event.pointerType == "mouse") {
  95141. if (_this._lastPointerRay[_this.currentDraggingPointerID]) {
  95142. _this._lastPointerRay[pointerId] = _this._lastPointerRay[_this.currentDraggingPointerID];
  95143. delete _this._lastPointerRay[_this.currentDraggingPointerID];
  95144. }
  95145. _this.currentDraggingPointerID = pointerId;
  95146. }
  95147. // Keep track of last pointer ray, this is used simulating the start of a drag in startDrag()
  95148. if (!_this._lastPointerRay[pointerId]) {
  95149. _this._lastPointerRay[pointerId] = new BABYLON.Ray(new BABYLON.Vector3(), new BABYLON.Vector3());
  95150. }
  95151. if (pointerInfo.pickInfo && pointerInfo.pickInfo.ray) {
  95152. _this._lastPointerRay[pointerId].origin.copyFrom(pointerInfo.pickInfo.ray.origin);
  95153. _this._lastPointerRay[pointerId].direction.copyFrom(pointerInfo.pickInfo.ray.direction);
  95154. if (_this.currentDraggingPointerID == pointerId && _this.dragging) {
  95155. _this._moveDrag(pointerInfo.pickInfo.ray);
  95156. }
  95157. }
  95158. }
  95159. });
  95160. this._beforeRenderObserver = this._scene.onBeforeRenderObservable.add(function () {
  95161. if (_this._moving && _this.moveAttached) {
  95162. BABYLON.BoundingBoxGizmo._RemoveAndStorePivotPoint(_this._attachedNode);
  95163. // Slowly move mesh to avoid jitter
  95164. _this._targetPosition.subtractToRef((_this._attachedNode).absolutePosition, _this._tmpVector);
  95165. _this._tmpVector.scaleInPlace(_this.dragDeltaRatio);
  95166. (_this._attachedNode).getAbsolutePosition().addToRef(_this._tmpVector, _this._tmpVector);
  95167. (_this._attachedNode).setAbsolutePosition(_this._tmpVector);
  95168. BABYLON.BoundingBoxGizmo._RestorePivotPoint(_this._attachedNode);
  95169. }
  95170. });
  95171. };
  95172. /**
  95173. * Force relase the drag action by code.
  95174. */
  95175. PointerDragBehavior.prototype.releaseDrag = function () {
  95176. this.dragging = false;
  95177. this.onDragEndObservable.notifyObservers({ dragPlanePoint: this.lastDragPosition, pointerId: this.currentDraggingPointerID });
  95178. this.currentDraggingPointerID = -1;
  95179. this._moving = false;
  95180. // Reattach camera controls
  95181. if (this.detachCameraControls && this._attachedElement && this._scene.activeCamera && !this._scene.activeCamera.leftCamera) {
  95182. this._scene.activeCamera.attachControl(this._attachedElement, true);
  95183. }
  95184. };
  95185. /**
  95186. * Simulates the start of a pointer drag event on the behavior
  95187. * @param pointerId pointerID of the pointer that should be simulated (Default: Any mouse pointer ID)
  95188. * @param fromRay initial ray of the pointer to be simulated (Default: Ray from camera to attached mesh)
  95189. * @param startPickedPoint picked point of the pointer to be simulated (Default: attached mesh position)
  95190. */
  95191. PointerDragBehavior.prototype.startDrag = function (pointerId, fromRay, startPickedPoint) {
  95192. if (pointerId === void 0) { pointerId = PointerDragBehavior._AnyMouseID; }
  95193. this._startDrag(pointerId, fromRay, startPickedPoint);
  95194. var lastRay = this._lastPointerRay[pointerId];
  95195. if (pointerId === PointerDragBehavior._AnyMouseID) {
  95196. lastRay = this._lastPointerRay[Object.keys(this._lastPointerRay)[0]];
  95197. }
  95198. if (lastRay) {
  95199. // if there was a last pointer ray drag the object there
  95200. this._moveDrag(lastRay);
  95201. }
  95202. };
  95203. PointerDragBehavior.prototype._startDrag = function (pointerId, fromRay, startPickedPoint) {
  95204. if (!this._scene.activeCamera || this.dragging || !this._attachedNode) {
  95205. return;
  95206. }
  95207. BABYLON.BoundingBoxGizmo._RemoveAndStorePivotPoint(this._attachedNode);
  95208. // Create start ray from the camera to the object
  95209. if (fromRay) {
  95210. this._startDragRay.direction.copyFrom(fromRay.direction);
  95211. this._startDragRay.origin.copyFrom(fromRay.origin);
  95212. }
  95213. else {
  95214. this._startDragRay.origin.copyFrom(this._scene.activeCamera.position);
  95215. this._attachedNode.getWorldMatrix().getTranslationToRef(this._tmpVector);
  95216. this._tmpVector.subtractToRef(this._scene.activeCamera.position, this._startDragRay.direction);
  95217. }
  95218. this._updateDragPlanePosition(this._startDragRay, startPickedPoint ? startPickedPoint : this._tmpVector);
  95219. var pickedPoint = this._pickWithRayOnDragPlane(this._startDragRay);
  95220. if (pickedPoint) {
  95221. this.dragging = true;
  95222. this.currentDraggingPointerID = pointerId;
  95223. this.lastDragPosition.copyFrom(pickedPoint);
  95224. this.onDragStartObservable.notifyObservers({ dragPlanePoint: pickedPoint, pointerId: this.currentDraggingPointerID });
  95225. this._targetPosition.copyFrom((this._attachedNode).absolutePosition);
  95226. // Detatch camera controls
  95227. if (this.detachCameraControls && this._scene.activeCamera && !this._scene.activeCamera.leftCamera) {
  95228. if (this._scene.activeCamera.inputs.attachedElement) {
  95229. this._attachedElement = this._scene.activeCamera.inputs.attachedElement;
  95230. this._scene.activeCamera.detachControl(this._scene.activeCamera.inputs.attachedElement);
  95231. }
  95232. else {
  95233. this._attachedElement = null;
  95234. }
  95235. }
  95236. }
  95237. BABYLON.BoundingBoxGizmo._RestorePivotPoint(this._attachedNode);
  95238. };
  95239. PointerDragBehavior.prototype._moveDrag = function (ray) {
  95240. this._moving = true;
  95241. var pickedPoint = this._pickWithRayOnDragPlane(ray);
  95242. if (pickedPoint) {
  95243. if (this.updateDragPlane) {
  95244. this._updateDragPlanePosition(ray, pickedPoint);
  95245. }
  95246. var dragLength = 0;
  95247. // depending on the drag mode option drag accordingly
  95248. if (this._options.dragAxis) {
  95249. // Convert local drag axis to world
  95250. BABYLON.Vector3.TransformCoordinatesToRef(this._options.dragAxis, this._attachedNode.getWorldMatrix().getRotationMatrix(), this._worldDragAxis);
  95251. // Project delta drag from the drag plane onto the drag axis
  95252. pickedPoint.subtractToRef(this.lastDragPosition, this._tmpVector);
  95253. dragLength = BABYLON.Vector3.Dot(this._tmpVector, this._worldDragAxis);
  95254. this._worldDragAxis.scaleToRef(dragLength, this._dragDelta);
  95255. }
  95256. else {
  95257. dragLength = this._dragDelta.length();
  95258. pickedPoint.subtractToRef(this.lastDragPosition, this._dragDelta);
  95259. }
  95260. this._targetPosition.addInPlace(this._dragDelta);
  95261. this.onDragObservable.notifyObservers({ dragDistance: dragLength, delta: this._dragDelta, dragPlanePoint: pickedPoint, dragPlaneNormal: this._dragPlane.forward, pointerId: this.currentDraggingPointerID });
  95262. this.lastDragPosition.copyFrom(pickedPoint);
  95263. }
  95264. };
  95265. PointerDragBehavior.prototype._pickWithRayOnDragPlane = function (ray) {
  95266. var _this = this;
  95267. if (!ray) {
  95268. return null;
  95269. }
  95270. // Calculate angle between plane normal and ray
  95271. var angle = Math.acos(BABYLON.Vector3.Dot(this._dragPlane.forward, ray.direction));
  95272. // Correct if ray is casted from oposite side
  95273. if (angle > Math.PI / 2) {
  95274. angle = Math.PI - angle;
  95275. }
  95276. // If the angle is too perpendicular to the plane pick another point on the plane where it is looking
  95277. if (this.maxDragAngle > 0 && angle > this.maxDragAngle) {
  95278. if (this._useAlternatePickedPointAboveMaxDragAngle) {
  95279. // Invert ray direction along the towards object axis
  95280. this._tmpVector.copyFrom(ray.direction);
  95281. (this._attachedNode).absolutePosition.subtractToRef(ray.origin, this._alternatePickedPoint);
  95282. this._alternatePickedPoint.normalize();
  95283. this._alternatePickedPoint.scaleInPlace(-2 * BABYLON.Vector3.Dot(this._alternatePickedPoint, this._tmpVector));
  95284. this._tmpVector.addInPlace(this._alternatePickedPoint);
  95285. // Project resulting vector onto the drag plane and add it to the attached nodes absolute position to get a picked point
  95286. var dot = BABYLON.Vector3.Dot(this._dragPlane.forward, this._tmpVector);
  95287. this._dragPlane.forward.scaleToRef(-dot, this._alternatePickedPoint);
  95288. this._alternatePickedPoint.addInPlace(this._tmpVector);
  95289. this._alternatePickedPoint.addInPlace((this._attachedNode).absolutePosition);
  95290. return this._alternatePickedPoint;
  95291. }
  95292. else {
  95293. return null;
  95294. }
  95295. }
  95296. var pickResult = PointerDragBehavior._planeScene.pickWithRay(ray, function (m) { return m == _this._dragPlane; });
  95297. if (pickResult && pickResult.hit && pickResult.pickedMesh && pickResult.pickedPoint) {
  95298. return pickResult.pickedPoint;
  95299. }
  95300. else {
  95301. return null;
  95302. }
  95303. };
  95304. // Position the drag plane based on the attached mesh position, for single axis rotate the plane along the axis to face the camera
  95305. PointerDragBehavior.prototype._updateDragPlanePosition = function (ray, dragPlanePosition) {
  95306. this._pointA.copyFrom(dragPlanePosition);
  95307. if (this._options.dragAxis) {
  95308. this.useObjectOrienationForDragging ? BABYLON.Vector3.TransformCoordinatesToRef(this._options.dragAxis, this._attachedNode.getWorldMatrix().getRotationMatrix(), this._localAxis) : this._localAxis.copyFrom(this._options.dragAxis);
  95309. // Calculate plane normal in direction of camera but perpendicular to drag axis
  95310. this._pointA.addToRef(this._localAxis, this._pointB); // towards drag axis
  95311. ray.origin.subtractToRef(this._pointA, this._pointC);
  95312. this._pointA.addToRef(this._pointC.normalize(), this._pointC); // towards camera
  95313. // Get perpendicular line from direction to camera and drag axis
  95314. this._pointB.subtractToRef(this._pointA, this._lineA);
  95315. this._pointC.subtractToRef(this._pointA, this._lineB);
  95316. BABYLON.Vector3.CrossToRef(this._lineA, this._lineB, this._lookAt);
  95317. // Get perpendicular line from previous result and drag axis to adjust lineB to be perpendiculat to camera
  95318. BABYLON.Vector3.CrossToRef(this._lineA, this._lookAt, this._lookAt);
  95319. this._lookAt.normalize();
  95320. this._dragPlane.position.copyFrom(this._pointA);
  95321. this._pointA.subtractToRef(this._lookAt, this._lookAt);
  95322. this._dragPlane.lookAt(this._lookAt);
  95323. }
  95324. else if (this._options.dragPlaneNormal) {
  95325. this.useObjectOrienationForDragging ? BABYLON.Vector3.TransformCoordinatesToRef(this._options.dragPlaneNormal, this._attachedNode.getWorldMatrix().getRotationMatrix(), this._localAxis) : this._localAxis.copyFrom(this._options.dragPlaneNormal);
  95326. this._dragPlane.position.copyFrom(this._pointA);
  95327. this._pointA.subtractToRef(this._localAxis, this._lookAt);
  95328. this._dragPlane.lookAt(this._lookAt);
  95329. }
  95330. else {
  95331. this._dragPlane.position.copyFrom(this._pointA);
  95332. this._dragPlane.lookAt(ray.origin);
  95333. }
  95334. this._dragPlane.computeWorldMatrix(true);
  95335. };
  95336. /**
  95337. * Detaches the behavior from the mesh
  95338. */
  95339. PointerDragBehavior.prototype.detach = function () {
  95340. if (this._pointerObserver) {
  95341. this._scene.onPointerObservable.remove(this._pointerObserver);
  95342. }
  95343. if (this._beforeRenderObserver) {
  95344. this._scene.onBeforeRenderObservable.remove(this._beforeRenderObserver);
  95345. }
  95346. };
  95347. PointerDragBehavior._AnyMouseID = -2;
  95348. return PointerDragBehavior;
  95349. }());
  95350. BABYLON.PointerDragBehavior = PointerDragBehavior;
  95351. })(BABYLON || (BABYLON = {}));
  95352. //# sourceMappingURL=babylon.pointerDragBehavior.js.map
  95353. var BABYLON;
  95354. (function (BABYLON) {
  95355. /**
  95356. * A behavior that when attached to a mesh will allow the mesh to be scaled
  95357. */
  95358. var MultiPointerScaleBehavior = /** @class */ (function () {
  95359. /**
  95360. * Instantiate a new behavior that when attached to a mesh will allow the mesh to be scaled
  95361. */
  95362. function MultiPointerScaleBehavior() {
  95363. this._startDistance = 0;
  95364. this._initialScale = new BABYLON.Vector3(0, 0, 0);
  95365. this._targetScale = new BABYLON.Vector3(0, 0, 0);
  95366. this._sceneRenderObserver = null;
  95367. this._dragBehaviorA = new BABYLON.PointerDragBehavior({});
  95368. this._dragBehaviorA.moveAttached = false;
  95369. this._dragBehaviorB = new BABYLON.PointerDragBehavior({});
  95370. this._dragBehaviorB.moveAttached = false;
  95371. }
  95372. Object.defineProperty(MultiPointerScaleBehavior.prototype, "name", {
  95373. /**
  95374. * The name of the behavior
  95375. */
  95376. get: function () {
  95377. return "MultiPointerScale";
  95378. },
  95379. enumerable: true,
  95380. configurable: true
  95381. });
  95382. /**
  95383. * Initializes the behavior
  95384. */
  95385. MultiPointerScaleBehavior.prototype.init = function () { };
  95386. MultiPointerScaleBehavior.prototype._getCurrentDistance = function () {
  95387. return this._dragBehaviorA.lastDragPosition.subtract(this._dragBehaviorB.lastDragPosition).length();
  95388. };
  95389. /**
  95390. * Attaches the scale behavior the passed in mesh
  95391. * @param ownerNode The mesh that will be scaled around once attached
  95392. */
  95393. MultiPointerScaleBehavior.prototype.attach = function (ownerNode) {
  95394. var _this = this;
  95395. this._ownerNode = ownerNode;
  95396. // Create 2 drag behaviors such that each will only be triggered by a separate pointer
  95397. this._dragBehaviorA.onDragStartObservable.add(function (e) {
  95398. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  95399. if (_this._dragBehaviorA.currentDraggingPointerID == _this._dragBehaviorB.currentDraggingPointerID) {
  95400. _this._dragBehaviorA.releaseDrag();
  95401. }
  95402. else {
  95403. _this._initialScale.copyFrom(ownerNode.scaling);
  95404. _this._startDistance = _this._getCurrentDistance();
  95405. }
  95406. }
  95407. });
  95408. this._dragBehaviorB.onDragStartObservable.add(function (e) {
  95409. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  95410. if (_this._dragBehaviorA.currentDraggingPointerID == _this._dragBehaviorB.currentDraggingPointerID) {
  95411. _this._dragBehaviorB.releaseDrag();
  95412. }
  95413. else {
  95414. _this._initialScale.copyFrom(ownerNode.scaling);
  95415. _this._startDistance = _this._getCurrentDistance();
  95416. }
  95417. }
  95418. });
  95419. // Once both drag behaviors are active scale based on the distance between the two pointers
  95420. [this._dragBehaviorA, this._dragBehaviorB].forEach(function (behavior) {
  95421. behavior.onDragObservable.add(function () {
  95422. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  95423. var ratio = _this._getCurrentDistance() / _this._startDistance;
  95424. _this._initialScale.scaleToRef(ratio, _this._targetScale);
  95425. }
  95426. });
  95427. });
  95428. ownerNode.addBehavior(this._dragBehaviorA);
  95429. ownerNode.addBehavior(this._dragBehaviorB);
  95430. // On every frame move towards target scaling to avoid jitter caused by vr controllers
  95431. this._sceneRenderObserver = ownerNode.getScene().onBeforeRenderObservable.add(function () {
  95432. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  95433. var change = _this._targetScale.subtract(ownerNode.scaling).scaleInPlace(0.1);
  95434. if (change.length() > 0.01) {
  95435. ownerNode.scaling.addInPlace(change);
  95436. }
  95437. }
  95438. });
  95439. };
  95440. /**
  95441. * Detaches the behavior from the mesh
  95442. */
  95443. MultiPointerScaleBehavior.prototype.detach = function () {
  95444. var _this = this;
  95445. this._ownerNode.getScene().onBeforeRenderObservable.remove(this._sceneRenderObserver);
  95446. [this._dragBehaviorA, this._dragBehaviorB].forEach(function (behavior) {
  95447. behavior.onDragStartObservable.clear();
  95448. behavior.onDragObservable.clear();
  95449. _this._ownerNode.removeBehavior(behavior);
  95450. });
  95451. };
  95452. return MultiPointerScaleBehavior;
  95453. }());
  95454. BABYLON.MultiPointerScaleBehavior = MultiPointerScaleBehavior;
  95455. })(BABYLON || (BABYLON = {}));
  95456. //# sourceMappingURL=babylon.multiPointerScaleBehavior.js.map
  95457. var BABYLON;
  95458. (function (BABYLON) {
  95459. /**
  95460. * 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
  95461. */
  95462. var SixDofDragBehavior = /** @class */ (function () {
  95463. /**
  95464. * Instantiates 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
  95465. */
  95466. function SixDofDragBehavior() {
  95467. this._sceneRenderObserver = null;
  95468. this._targetPosition = new BABYLON.Vector3(0, 0, 0);
  95469. this._moving = false;
  95470. this._startingOrientation = new BABYLON.Quaternion();
  95471. /**
  95472. * 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: 3)
  95473. */
  95474. this.zDragFactor = 3;
  95475. /**
  95476. * If the behavior is currently in a dragging state
  95477. */
  95478. this.dragging = false;
  95479. /**
  95480. * 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)
  95481. */
  95482. this.dragDeltaRatio = 0.2;
  95483. /**
  95484. * The id of the pointer that is currently interacting with the behavior (-1 when no pointer is active)
  95485. */
  95486. this.currentDraggingPointerID = -1;
  95487. /**
  95488. * If camera controls should be detached during the drag
  95489. */
  95490. this.detachCameraControls = true;
  95491. /**
  95492. * Fires each time a drag starts
  95493. */
  95494. this.onDragStartObservable = new BABYLON.Observable();
  95495. /**
  95496. * Fires each time a drag ends (eg. mouse release after drag)
  95497. */
  95498. this.onDragEndObservable = new BABYLON.Observable();
  95499. }
  95500. Object.defineProperty(SixDofDragBehavior.prototype, "name", {
  95501. /**
  95502. * The name of the behavior
  95503. */
  95504. get: function () {
  95505. return "SixDofDrag";
  95506. },
  95507. enumerable: true,
  95508. configurable: true
  95509. });
  95510. /**
  95511. * Initializes the behavior
  95512. */
  95513. SixDofDragBehavior.prototype.init = function () { };
  95514. /**
  95515. * Attaches the scale behavior the passed in mesh
  95516. * @param ownerNode The mesh that will be scaled around once attached
  95517. */
  95518. SixDofDragBehavior.prototype.attach = function (ownerNode) {
  95519. var _this = this;
  95520. this._ownerNode = ownerNode;
  95521. this._scene = this._ownerNode.getScene();
  95522. if (!SixDofDragBehavior._virtualScene) {
  95523. SixDofDragBehavior._virtualScene = new BABYLON.Scene(this._scene.getEngine());
  95524. this._scene.getEngine().scenes.pop();
  95525. }
  95526. var pickedMesh = null;
  95527. var lastSixDofOriginPosition = new BABYLON.Vector3(0, 0, 0);
  95528. // Setup virtual meshes to be used for dragging without dirtying the existing scene
  95529. this._virtualOriginMesh = new BABYLON.AbstractMesh("", SixDofDragBehavior._virtualScene);
  95530. this._virtualOriginMesh.rotationQuaternion = new BABYLON.Quaternion();
  95531. this._virtualDragMesh = new BABYLON.AbstractMesh("", SixDofDragBehavior._virtualScene);
  95532. this._virtualDragMesh.rotationQuaternion = new BABYLON.Quaternion();
  95533. var pickPredicate = function (m) {
  95534. return _this._ownerNode == m || m.isDescendantOf(_this._ownerNode);
  95535. };
  95536. var attachedElement = null;
  95537. this._pointerObserver = this._scene.onPointerObservable.add(function (pointerInfo, eventState) {
  95538. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  95539. if (!_this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.hit && pointerInfo.pickInfo.pickedMesh && pointerInfo.pickInfo.ray && pickPredicate(pointerInfo.pickInfo.pickedMesh)) {
  95540. if (_this._scene.activeCamera && _this._scene.activeCamera.cameraRigMode == BABYLON.Camera.RIG_MODE_NONE) {
  95541. pointerInfo.pickInfo.ray.origin.copyFrom(_this._scene.activeCamera.position);
  95542. }
  95543. pickedMesh = _this._ownerNode;
  95544. BABYLON.BoundingBoxGizmo._RemoveAndStorePivotPoint(pickedMesh);
  95545. lastSixDofOriginPosition.copyFrom(pointerInfo.pickInfo.ray.origin);
  95546. // Set position and orientation of the controller
  95547. _this._virtualOriginMesh.position.copyFrom(pointerInfo.pickInfo.ray.origin);
  95548. _this._virtualOriginMesh.lookAt(pointerInfo.pickInfo.ray.origin.subtract(pointerInfo.pickInfo.ray.direction));
  95549. // Attach the virtual drag mesh to the virtual origin mesh so it can be dragged
  95550. _this._virtualOriginMesh.removeChild(_this._virtualDragMesh);
  95551. pickedMesh.computeWorldMatrix();
  95552. _this._virtualDragMesh.position.copyFrom(pickedMesh.absolutePosition);
  95553. if (!pickedMesh.rotationQuaternion) {
  95554. pickedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(pickedMesh.rotation.y, pickedMesh.rotation.x, pickedMesh.rotation.z);
  95555. }
  95556. var oldParent = pickedMesh.parent;
  95557. pickedMesh.setParent(null);
  95558. _this._virtualDragMesh.rotationQuaternion.copyFrom(pickedMesh.rotationQuaternion);
  95559. pickedMesh.setParent(oldParent);
  95560. _this._virtualOriginMesh.addChild(_this._virtualDragMesh);
  95561. // Update state
  95562. _this._targetPosition.copyFrom(_this._virtualDragMesh.absolutePosition);
  95563. _this.dragging = true;
  95564. _this.currentDraggingPointerID = pointerInfo.event.pointerId;
  95565. // Detatch camera controls
  95566. if (_this.detachCameraControls && _this._scene.activeCamera && !_this._scene.activeCamera.leftCamera) {
  95567. if (_this._scene.activeCamera.inputs.attachedElement) {
  95568. attachedElement = _this._scene.activeCamera.inputs.attachedElement;
  95569. _this._scene.activeCamera.detachControl(_this._scene.activeCamera.inputs.attachedElement);
  95570. }
  95571. else {
  95572. attachedElement = null;
  95573. }
  95574. }
  95575. BABYLON.BoundingBoxGizmo._RestorePivotPoint(pickedMesh);
  95576. _this.onDragStartObservable.notifyObservers({});
  95577. }
  95578. }
  95579. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERUP) {
  95580. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId) {
  95581. _this.dragging = false;
  95582. _this._moving = false;
  95583. _this.currentDraggingPointerID = -1;
  95584. pickedMesh = null;
  95585. _this._virtualOriginMesh.removeChild(_this._virtualDragMesh);
  95586. // Reattach camera controls
  95587. if (_this.detachCameraControls && attachedElement && _this._scene.activeCamera && !_this._scene.activeCamera.leftCamera) {
  95588. _this._scene.activeCamera.attachControl(attachedElement, true);
  95589. }
  95590. _this.onDragEndObservable.notifyObservers({});
  95591. }
  95592. }
  95593. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERMOVE) {
  95594. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId && _this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.ray && pickedMesh) {
  95595. var zDragFactor = _this.zDragFactor;
  95596. if (_this._scene.activeCamera && _this._scene.activeCamera.cameraRigMode == BABYLON.Camera.RIG_MODE_NONE) {
  95597. pointerInfo.pickInfo.ray.origin.copyFrom(_this._scene.activeCamera.position);
  95598. zDragFactor = 0;
  95599. }
  95600. // Calculate controller drag distance in controller space
  95601. var originDragDifference = pointerInfo.pickInfo.ray.origin.subtract(lastSixDofOriginPosition);
  95602. lastSixDofOriginPosition.copyFrom(pointerInfo.pickInfo.ray.origin);
  95603. var localOriginDragDifference = -BABYLON.Vector3.Dot(originDragDifference, pointerInfo.pickInfo.ray.direction);
  95604. _this._virtualOriginMesh.addChild(_this._virtualDragMesh);
  95605. // Determine how much the controller moved to/away towards the dragged object and use this to move the object further when its further away
  95606. _this._virtualDragMesh.position.z -= _this._virtualDragMesh.position.z < 1 ? localOriginDragDifference * _this.zDragFactor : localOriginDragDifference * zDragFactor * _this._virtualDragMesh.position.z;
  95607. if (_this._virtualDragMesh.position.z < 0) {
  95608. _this._virtualDragMesh.position.z = 0;
  95609. }
  95610. // Update the controller position
  95611. _this._virtualOriginMesh.position.copyFrom(pointerInfo.pickInfo.ray.origin);
  95612. _this._virtualOriginMesh.lookAt(pointerInfo.pickInfo.ray.origin.subtract(pointerInfo.pickInfo.ray.direction));
  95613. _this._virtualOriginMesh.removeChild(_this._virtualDragMesh);
  95614. // Move the virtualObjectsPosition into the picked mesh's space if needed
  95615. _this._targetPosition.copyFrom(_this._virtualDragMesh.absolutePosition);
  95616. if (pickedMesh.parent) {
  95617. BABYLON.Vector3.TransformCoordinatesToRef(_this._targetPosition, BABYLON.Matrix.Invert(pickedMesh.parent.getWorldMatrix()), _this._targetPosition);
  95618. }
  95619. if (!_this._moving) {
  95620. _this._startingOrientation.copyFrom(_this._virtualDragMesh.rotationQuaternion);
  95621. }
  95622. _this._moving = true;
  95623. }
  95624. }
  95625. });
  95626. var tmpQuaternion = new BABYLON.Quaternion();
  95627. // On every frame move towards target scaling to avoid jitter caused by vr controllers
  95628. this._sceneRenderObserver = ownerNode.getScene().onBeforeRenderObservable.add(function () {
  95629. if (_this.dragging && _this._moving && pickedMesh) {
  95630. BABYLON.BoundingBoxGizmo._RemoveAndStorePivotPoint(pickedMesh);
  95631. // Slowly move mesh to avoid jitter
  95632. pickedMesh.position.addInPlace(_this._targetPosition.subtract(pickedMesh.position).scale(_this.dragDeltaRatio));
  95633. // Get change in rotation
  95634. tmpQuaternion.copyFrom(_this._startingOrientation);
  95635. tmpQuaternion.x = -tmpQuaternion.x;
  95636. tmpQuaternion.y = -tmpQuaternion.y;
  95637. tmpQuaternion.z = -tmpQuaternion.z;
  95638. _this._virtualDragMesh.rotationQuaternion.multiplyToRef(tmpQuaternion, tmpQuaternion);
  95639. // Convert change in rotation to only y axis rotation
  95640. BABYLON.Quaternion.RotationYawPitchRollToRef(tmpQuaternion.toEulerAngles("xyz").y, 0, 0, tmpQuaternion);
  95641. tmpQuaternion.multiplyToRef(_this._startingOrientation, tmpQuaternion);
  95642. // Slowly move mesh to avoid jitter
  95643. var oldParent = pickedMesh.parent;
  95644. pickedMesh.setParent(null);
  95645. BABYLON.Quaternion.SlerpToRef(pickedMesh.rotationQuaternion, tmpQuaternion, _this.dragDeltaRatio, pickedMesh.rotationQuaternion);
  95646. pickedMesh.setParent(oldParent);
  95647. BABYLON.BoundingBoxGizmo._RestorePivotPoint(pickedMesh);
  95648. }
  95649. });
  95650. };
  95651. /**
  95652. * Detaches the behavior from the mesh
  95653. */
  95654. SixDofDragBehavior.prototype.detach = function () {
  95655. if (this._scene) {
  95656. this._scene.onPointerObservable.remove(this._pointerObserver);
  95657. }
  95658. if (this._ownerNode) {
  95659. this._ownerNode.getScene().onBeforeRenderObservable.remove(this._sceneRenderObserver);
  95660. }
  95661. if (this._virtualOriginMesh) {
  95662. this._virtualOriginMesh.dispose();
  95663. }
  95664. if (this._virtualDragMesh) {
  95665. this._virtualDragMesh.dispose();
  95666. }
  95667. this.onDragEndObservable.clear();
  95668. this.onDragStartObservable.clear();
  95669. };
  95670. return SixDofDragBehavior;
  95671. }());
  95672. BABYLON.SixDofDragBehavior = SixDofDragBehavior;
  95673. })(BABYLON || (BABYLON = {}));
  95674. //# sourceMappingURL=babylon.sixDofDragBehavior.js.map
  95675. var BABYLON;
  95676. (function (BABYLON) {
  95677. /**
  95678. * @hidden
  95679. */
  95680. var FaceDirectionInfo = /** @class */ (function () {
  95681. function FaceDirectionInfo(direction, rotatedDirection, diff, ignore) {
  95682. if (rotatedDirection === void 0) { rotatedDirection = new BABYLON.Vector3(); }
  95683. if (diff === void 0) { diff = 0; }
  95684. if (ignore === void 0) { ignore = false; }
  95685. this.direction = direction;
  95686. this.rotatedDirection = rotatedDirection;
  95687. this.diff = diff;
  95688. this.ignore = ignore;
  95689. }
  95690. return FaceDirectionInfo;
  95691. }());
  95692. /**
  95693. * A behavior that when attached to a mesh will will place a specified node on the meshes face pointing towards the camera
  95694. */
  95695. var AttachToBoxBehavior = /** @class */ (function () {
  95696. /**
  95697. * Creates the AttachToBoxBehavior, used to attach UI to the closest face of the box to a camera
  95698. * @param ui The transform node that should be attched to the mesh
  95699. */
  95700. function AttachToBoxBehavior(ui) {
  95701. this.ui = ui;
  95702. /**
  95703. * The name of the behavior
  95704. */
  95705. this.name = "AttachToBoxBehavior";
  95706. /**
  95707. * The distance away from the face of the mesh that the UI should be attached to (default: 0.15)
  95708. */
  95709. this.distanceAwayFromFace = 0.15;
  95710. /**
  95711. * The distance from the bottom of the face that the UI should be attached to (default: 0.15)
  95712. */
  95713. this.distanceAwayFromBottomOfFace = 0.15;
  95714. this._faceVectors = [new FaceDirectionInfo(BABYLON.Vector3.Up()), new FaceDirectionInfo(BABYLON.Vector3.Down()), new FaceDirectionInfo(BABYLON.Vector3.Left()), new FaceDirectionInfo(BABYLON.Vector3.Right()), new FaceDirectionInfo(BABYLON.Vector3.Forward()), new FaceDirectionInfo(BABYLON.Vector3.Forward().scaleInPlace(-1))];
  95715. this._tmpMatrix = new BABYLON.Matrix();
  95716. this._tmpVector = new BABYLON.Vector3();
  95717. this._zeroVector = BABYLON.Vector3.Zero();
  95718. this._lookAtTmpMatrix = new BABYLON.Matrix();
  95719. /* Does nothing */
  95720. }
  95721. /**
  95722. * Initializes the behavior
  95723. */
  95724. AttachToBoxBehavior.prototype.init = function () {
  95725. /* Does nothing */
  95726. };
  95727. AttachToBoxBehavior.prototype._closestFace = function (targetDirection) {
  95728. var _this = this;
  95729. // Go over each face and calculate the angle between the face's normal and targetDirection
  95730. this._faceVectors.forEach(function (v) {
  95731. if (!_this._target.rotationQuaternion) {
  95732. _this._target.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this._target.rotation.y, _this._target.rotation.x, _this._target.rotation.z);
  95733. }
  95734. _this._target.rotationQuaternion.toRotationMatrix(_this._tmpMatrix);
  95735. BABYLON.Vector3.TransformCoordinatesToRef(v.direction, _this._tmpMatrix, v.rotatedDirection);
  95736. v.diff = BABYLON.Vector3.GetAngleBetweenVectors(v.rotatedDirection, targetDirection, BABYLON.Vector3.Cross(v.rotatedDirection, targetDirection));
  95737. });
  95738. // Return the face information of the one with the normal closeset to target direction
  95739. return this._faceVectors.reduce(function (min, p) {
  95740. if (min.ignore) {
  95741. return p;
  95742. }
  95743. else if (p.ignore) {
  95744. return min;
  95745. }
  95746. else {
  95747. return min.diff < p.diff ? min : p;
  95748. }
  95749. }, this._faceVectors[0]);
  95750. };
  95751. AttachToBoxBehavior.prototype._lookAtToRef = function (pos, up, ref) {
  95752. if (up === void 0) { up = new BABYLON.Vector3(0, 1, 0); }
  95753. BABYLON.Matrix.LookAtLHToRef(this._zeroVector, pos, up, this._lookAtTmpMatrix);
  95754. this._lookAtTmpMatrix.invert();
  95755. BABYLON.Quaternion.FromRotationMatrixToRef(this._lookAtTmpMatrix, ref);
  95756. };
  95757. /**
  95758. * Attaches the AttachToBoxBehavior to the passed in mesh
  95759. * @param target The mesh that the specified node will be attached to
  95760. */
  95761. AttachToBoxBehavior.prototype.attach = function (target) {
  95762. var _this = this;
  95763. this._target = target;
  95764. this._scene = this._target.getScene();
  95765. // Every frame, update the app bars position
  95766. this._onRenderObserver = this._scene.onBeforeRenderObservable.add(function () {
  95767. if (!_this._scene.activeCamera) {
  95768. return;
  95769. }
  95770. // Find the face closest to the cameras position
  95771. var cameraPos = _this._scene.activeCamera.position;
  95772. if (_this._scene.activeCamera.devicePosition) {
  95773. cameraPos = _this._scene.activeCamera.devicePosition;
  95774. }
  95775. var facing = _this._closestFace(cameraPos.subtract(target.position));
  95776. if (_this._scene.activeCamera.leftCamera) {
  95777. _this._scene.activeCamera.leftCamera.computeWorldMatrix().getRotationMatrixToRef(_this._tmpMatrix);
  95778. }
  95779. else {
  95780. _this._scene.activeCamera.computeWorldMatrix().getRotationMatrixToRef(_this._tmpMatrix);
  95781. }
  95782. // Get camera up direction
  95783. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Vector3.Up(), _this._tmpMatrix, _this._tmpVector);
  95784. // Ignore faces to not select a parrelel face for the up vector of the UI
  95785. _this._faceVectors.forEach(function (v) {
  95786. if (facing.direction.x && v.direction.x) {
  95787. v.ignore = true;
  95788. }
  95789. if (facing.direction.y && v.direction.y) {
  95790. v.ignore = true;
  95791. }
  95792. if (facing.direction.z && v.direction.z) {
  95793. v.ignore = true;
  95794. }
  95795. });
  95796. var facingUp = _this._closestFace(_this._tmpVector);
  95797. // Unignore faces
  95798. _this._faceVectors.forEach(function (v) {
  95799. v.ignore = false;
  95800. });
  95801. // Position the app bar on that face
  95802. _this.ui.position.copyFrom(target.position);
  95803. if (facing.direction.x) {
  95804. facing.rotatedDirection.scaleToRef((target.scaling.x / 2) + _this.distanceAwayFromFace, _this._tmpVector);
  95805. _this.ui.position.addInPlace(_this._tmpVector);
  95806. }
  95807. if (facing.direction.y) {
  95808. facing.rotatedDirection.scaleToRef((target.scaling.y / 2) + _this.distanceAwayFromFace, _this._tmpVector);
  95809. _this.ui.position.addInPlace(_this._tmpVector);
  95810. }
  95811. if (facing.direction.z) {
  95812. facing.rotatedDirection.scaleToRef((target.scaling.z / 2) + _this.distanceAwayFromFace, _this._tmpVector);
  95813. _this.ui.position.addInPlace(_this._tmpVector);
  95814. }
  95815. // Rotate to be oriented properly to the camera
  95816. if (!_this.ui.rotationQuaternion) {
  95817. _this.ui.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this.ui.rotation.y, _this.ui.rotation.x, _this.ui.rotation.z);
  95818. }
  95819. facing.rotatedDirection.scaleToRef(-1, _this._tmpVector);
  95820. _this._lookAtToRef(_this._tmpVector, facingUp.rotatedDirection, _this.ui.rotationQuaternion);
  95821. // Place ui the correct distance from the bottom of the mesh
  95822. if (facingUp.direction.x) {
  95823. _this.ui.up.scaleToRef(_this.distanceAwayFromBottomOfFace - target.scaling.x / 2, _this._tmpVector);
  95824. }
  95825. if (facingUp.direction.y) {
  95826. _this.ui.up.scaleToRef(_this.distanceAwayFromBottomOfFace - target.scaling.y / 2, _this._tmpVector);
  95827. }
  95828. if (facingUp.direction.z) {
  95829. _this.ui.up.scaleToRef(_this.distanceAwayFromBottomOfFace - target.scaling.z / 2, _this._tmpVector);
  95830. }
  95831. _this.ui.position.addInPlace(_this._tmpVector);
  95832. });
  95833. };
  95834. /**
  95835. * Detaches the behavior from the mesh
  95836. */
  95837. AttachToBoxBehavior.prototype.detach = function () {
  95838. this._scene.onBeforeRenderObservable.remove(this._onRenderObserver);
  95839. };
  95840. return AttachToBoxBehavior;
  95841. }());
  95842. BABYLON.AttachToBoxBehavior = AttachToBoxBehavior;
  95843. })(BABYLON || (BABYLON = {}));
  95844. //# sourceMappingURL=babylon.attachToBoxBehavior.js.map
  95845. var BABYLON;
  95846. (function (BABYLON) {
  95847. /**
  95848. * A behavior that when attached to a mesh will allow the mesh to fade in and out
  95849. */
  95850. var FadeInOutBehavior = /** @class */ (function () {
  95851. /**
  95852. * Instatiates the FadeInOutBehavior
  95853. */
  95854. function FadeInOutBehavior() {
  95855. var _this = this;
  95856. /**
  95857. * Time in milliseconds to delay before fading in (Default: 0)
  95858. */
  95859. this.delay = 0;
  95860. /**
  95861. * Time in milliseconds for the mesh to fade in (Default: 300)
  95862. */
  95863. this.fadeInTime = 300;
  95864. this._millisecondsPerFrame = 1000 / 60;
  95865. this._hovered = false;
  95866. this._hoverValue = 0;
  95867. this._ownerNode = null;
  95868. this._update = function () {
  95869. if (_this._ownerNode) {
  95870. _this._hoverValue += _this._hovered ? _this._millisecondsPerFrame : -_this._millisecondsPerFrame;
  95871. _this._setAllVisibility(_this._ownerNode, (_this._hoverValue - _this.delay) / _this.fadeInTime);
  95872. if (_this._ownerNode.visibility > 1) {
  95873. _this._setAllVisibility(_this._ownerNode, 1);
  95874. _this._hoverValue = _this.fadeInTime + _this.delay;
  95875. return;
  95876. }
  95877. else if (_this._ownerNode.visibility < 0) {
  95878. _this._setAllVisibility(_this._ownerNode, 0);
  95879. if (_this._hoverValue < 0) {
  95880. _this._hoverValue = 0;
  95881. return;
  95882. }
  95883. }
  95884. setTimeout(_this._update, _this._millisecondsPerFrame);
  95885. }
  95886. };
  95887. }
  95888. Object.defineProperty(FadeInOutBehavior.prototype, "name", {
  95889. /**
  95890. * The name of the behavior
  95891. */
  95892. get: function () {
  95893. return "FadeInOut";
  95894. },
  95895. enumerable: true,
  95896. configurable: true
  95897. });
  95898. /**
  95899. * Initializes the behavior
  95900. */
  95901. FadeInOutBehavior.prototype.init = function () {
  95902. };
  95903. /**
  95904. * Attaches the fade behavior on the passed in mesh
  95905. * @param ownerNode The mesh that will be faded in/out once attached
  95906. */
  95907. FadeInOutBehavior.prototype.attach = function (ownerNode) {
  95908. this._ownerNode = ownerNode;
  95909. this._setAllVisibility(this._ownerNode, 0);
  95910. };
  95911. /**
  95912. * Detaches the behavior from the mesh
  95913. */
  95914. FadeInOutBehavior.prototype.detach = function () {
  95915. this._ownerNode = null;
  95916. };
  95917. /**
  95918. * Triggers the mesh to begin fading in or out
  95919. * @param value if the object should fade in or out (true to fade in)
  95920. */
  95921. FadeInOutBehavior.prototype.fadeIn = function (value) {
  95922. this._hovered = value;
  95923. this._update();
  95924. };
  95925. FadeInOutBehavior.prototype._setAllVisibility = function (mesh, value) {
  95926. var _this = this;
  95927. mesh.visibility = value;
  95928. mesh.getChildMeshes().forEach(function (c) {
  95929. _this._setAllVisibility(c, value);
  95930. });
  95931. };
  95932. return FadeInOutBehavior;
  95933. }());
  95934. BABYLON.FadeInOutBehavior = FadeInOutBehavior;
  95935. })(BABYLON || (BABYLON = {}));
  95936. //# sourceMappingURL=babylon.fadeInOutBehavior.js.map
  95937. var BABYLON;
  95938. (function (BABYLON) {
  95939. /**
  95940. * Renders gizmos on top of an existing scene which provide controls for position, rotation, etc.
  95941. */
  95942. var Gizmo = /** @class */ (function () {
  95943. /**
  95944. * Creates a gizmo
  95945. * @param gizmoLayer The utility layer the gizmo will be added to
  95946. */
  95947. function Gizmo(
  95948. /** The utility layer the gizmo will be added to */
  95949. gizmoLayer) {
  95950. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  95951. var _this = this;
  95952. this.gizmoLayer = gizmoLayer;
  95953. /**
  95954. * Ratio for the scale of the gizmo (Default: 1)
  95955. */
  95956. this.scaleRatio = 1;
  95957. this._tmpMatrix = new BABYLON.Matrix();
  95958. /**
  95959. * If a custom mesh has been set (Default: false)
  95960. */
  95961. this._customMeshSet = false;
  95962. /**
  95963. * If set the gizmo's rotation will be updated to match the attached mesh each frame (Default: true)
  95964. */
  95965. this.updateGizmoRotationToMatchAttachedMesh = true;
  95966. /**
  95967. * If set the gizmo's position will be updated to match the attached mesh each frame (Default: true)
  95968. */
  95969. this.updateGizmoPositionToMatchAttachedMesh = true;
  95970. /**
  95971. * When set, the gizmo will always appear the same size no matter where the camera is (default: false)
  95972. */
  95973. this._updateScale = true;
  95974. this._interactionsEnabled = true;
  95975. this._tempVector = new BABYLON.Vector3();
  95976. this._rootMesh = new BABYLON.Mesh("gizmoRootNode", gizmoLayer.utilityLayerScene);
  95977. this._beforeRenderObserver = this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.add(function () {
  95978. _this._update();
  95979. });
  95980. this.attachedMesh = null;
  95981. }
  95982. Object.defineProperty(Gizmo.prototype, "attachedMesh", {
  95983. /**
  95984. * Mesh that the gizmo will be attached to. (eg. on a drag gizmo the mesh that will be dragged)
  95985. * * When set, interactions will be enabled
  95986. */
  95987. get: function () {
  95988. return this._attachedMesh;
  95989. },
  95990. set: function (value) {
  95991. this._attachedMesh = value;
  95992. this._rootMesh.setEnabled(value ? true : false);
  95993. this._attachedMeshChanged(value);
  95994. },
  95995. enumerable: true,
  95996. configurable: true
  95997. });
  95998. /**
  95999. * Disposes and replaces the current meshes in the gizmo with the specified mesh
  96000. * @param mesh The mesh to replace the default mesh of the gizmo
  96001. */
  96002. Gizmo.prototype.setCustomMesh = function (mesh) {
  96003. if (mesh.getScene() != this.gizmoLayer.utilityLayerScene) {
  96004. throw "When setting a custom mesh on a gizmo, the custom meshes scene must be the same as the gizmos (eg. gizmo.gizmoLayer.utilityLayerScene)";
  96005. }
  96006. this._rootMesh.getChildMeshes().forEach(function (c) {
  96007. c.dispose();
  96008. });
  96009. mesh.parent = this._rootMesh;
  96010. this._customMeshSet = true;
  96011. };
  96012. Gizmo.prototype._attachedMeshChanged = function (value) {
  96013. };
  96014. /**
  96015. * @hidden
  96016. * Updates the gizmo to match the attached mesh's position/rotation
  96017. */
  96018. Gizmo.prototype._update = function () {
  96019. if (this.attachedMesh) {
  96020. if (this.updateGizmoRotationToMatchAttachedMesh) {
  96021. if (!this._rootMesh.rotationQuaternion) {
  96022. this._rootMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this._rootMesh.rotation.y, this._rootMesh.rotation.x, this._rootMesh.rotation.z);
  96023. }
  96024. // Remove scaling before getting rotation matrix to get rotation matrix unmodified by scale
  96025. this._tempVector.copyFrom(this.attachedMesh.scaling);
  96026. if (this.attachedMesh.scaling.x < 0) {
  96027. this.attachedMesh.scaling.x *= -1;
  96028. }
  96029. if (this.attachedMesh.scaling.y < 0) {
  96030. this.attachedMesh.scaling.y *= -1;
  96031. }
  96032. if (this.attachedMesh.scaling.z < 0) {
  96033. this.attachedMesh.scaling.z *= -1;
  96034. }
  96035. this.attachedMesh.computeWorldMatrix().getRotationMatrixToRef(this._tmpMatrix);
  96036. this.attachedMesh.scaling.copyFrom(this._tempVector);
  96037. this.attachedMesh.computeWorldMatrix();
  96038. BABYLON.Quaternion.FromRotationMatrixToRef(this._tmpMatrix, this._rootMesh.rotationQuaternion);
  96039. }
  96040. else if (this._rootMesh.rotationQuaternion) {
  96041. this._rootMesh.rotationQuaternion.set(0, 0, 0, 1);
  96042. }
  96043. if (this.updateGizmoPositionToMatchAttachedMesh) {
  96044. this._rootMesh.position.copyFrom(this.attachedMesh.absolutePosition);
  96045. }
  96046. if (this._updateScale && this.gizmoLayer.utilityLayerScene.activeCamera && this.attachedMesh) {
  96047. var cameraPosition = this.gizmoLayer.utilityLayerScene.activeCamera.position;
  96048. if (this.gizmoLayer.utilityLayerScene.activeCamera.devicePosition) {
  96049. cameraPosition = this.gizmoLayer.utilityLayerScene.activeCamera.devicePosition;
  96050. }
  96051. this._rootMesh.position.subtractToRef(cameraPosition, this._tempVector);
  96052. var dist = this._tempVector.length() * this.scaleRatio;
  96053. this._rootMesh.scaling.set(dist, dist, dist);
  96054. }
  96055. }
  96056. };
  96057. /**
  96058. * Disposes of the gizmo
  96059. */
  96060. Gizmo.prototype.dispose = function () {
  96061. this._rootMesh.dispose();
  96062. if (this._beforeRenderObserver) {
  96063. this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.remove(this._beforeRenderObserver);
  96064. }
  96065. };
  96066. return Gizmo;
  96067. }());
  96068. BABYLON.Gizmo = Gizmo;
  96069. })(BABYLON || (BABYLON = {}));
  96070. //# sourceMappingURL=babylon.gizmo.js.map
  96071. var BABYLON;
  96072. (function (BABYLON) {
  96073. /**
  96074. * Single axis drag gizmo
  96075. */
  96076. var AxisDragGizmo = /** @class */ (function (_super) {
  96077. __extends(AxisDragGizmo, _super);
  96078. /**
  96079. * Creates an AxisDragGizmo
  96080. * @param gizmoLayer The utility layer the gizmo will be added to
  96081. * @param dragAxis The axis which the gizmo will be able to drag on
  96082. * @param color The color of the gizmo
  96083. */
  96084. function AxisDragGizmo(dragAxis, color, gizmoLayer) {
  96085. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  96086. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  96087. var _this = _super.call(this, gizmoLayer) || this;
  96088. _this._pointerObserver = null;
  96089. /**
  96090. * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  96091. */
  96092. _this.snapDistance = 0;
  96093. /**
  96094. * Event that fires each time the gizmo snaps to a new location.
  96095. * * snapDistance is the the change in distance
  96096. */
  96097. _this.onSnapObservable = new BABYLON.Observable();
  96098. // Create Material
  96099. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  96100. coloredMaterial.disableLighting = true;
  96101. coloredMaterial.emissiveColor = color;
  96102. var hoverMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  96103. hoverMaterial.disableLighting = true;
  96104. hoverMaterial.emissiveColor = color.add(new BABYLON.Color3(0.3, 0.3, 0.3));
  96105. // Build mesh on root node
  96106. var arrow = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  96107. var arrowMesh = BABYLON.MeshBuilder.CreateCylinder("yPosMesh", { diameterTop: 0, height: 1.5, diameterBottom: 0.75, tessellation: 96 }, gizmoLayer.utilityLayerScene);
  96108. var arrowTail = BABYLON.MeshBuilder.CreateLines("yPosMesh", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 1.1, 0)] }, gizmoLayer.utilityLayerScene);
  96109. arrowTail.color = coloredMaterial.emissiveColor;
  96110. arrow.addChild(arrowMesh);
  96111. arrow.addChild(arrowTail);
  96112. // Position arrow pointing in its drag axis
  96113. arrowMesh.scaling.scaleInPlace(0.05);
  96114. arrowMesh.material = coloredMaterial;
  96115. arrowMesh.rotation.x = Math.PI / 2;
  96116. arrowMesh.position.z += 0.3;
  96117. arrowTail.scaling.scaleInPlace(0.26);
  96118. arrowTail.rotation.x = Math.PI / 2;
  96119. arrowTail.material = coloredMaterial;
  96120. arrow.lookAt(_this._rootMesh.position.subtract(dragAxis));
  96121. arrow.scaling.scaleInPlace(1 / 3);
  96122. _this._rootMesh.addChild(arrow);
  96123. var currentSnapDragDistance = 0;
  96124. var tmpVector = new BABYLON.Vector3();
  96125. var tmpSnapEvent = { snapDistance: 0 };
  96126. // Add drag behavior to handle events when the gizmo is dragged
  96127. _this.dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });
  96128. _this.dragBehavior.moveAttached = false;
  96129. _this._rootMesh.addBehavior(_this.dragBehavior);
  96130. var localDelta = new BABYLON.Vector3();
  96131. var tmpMatrix = new BABYLON.Matrix();
  96132. _this.dragBehavior.onDragObservable.add(function (event) {
  96133. if (_this.attachedMesh) {
  96134. // Convert delta to local translation if it has a parent
  96135. if (_this.attachedMesh.parent) {
  96136. _this.attachedMesh.parent.computeWorldMatrix().invertToRef(tmpMatrix);
  96137. tmpMatrix.setTranslationFromFloats(0, 0, 0);
  96138. BABYLON.Vector3.TransformCoordinatesToRef(event.delta, tmpMatrix, localDelta);
  96139. }
  96140. else {
  96141. localDelta.copyFrom(event.delta);
  96142. }
  96143. // Snapping logic
  96144. if (_this.snapDistance == 0) {
  96145. _this.attachedMesh.position.addInPlace(localDelta);
  96146. }
  96147. else {
  96148. currentSnapDragDistance += event.dragDistance;
  96149. if (Math.abs(currentSnapDragDistance) > _this.snapDistance) {
  96150. var dragSteps = Math.floor(Math.abs(currentSnapDragDistance) / _this.snapDistance);
  96151. currentSnapDragDistance = currentSnapDragDistance % _this.snapDistance;
  96152. localDelta.normalizeToRef(tmpVector);
  96153. tmpVector.scaleInPlace(_this.snapDistance * dragSteps);
  96154. _this.attachedMesh.position.addInPlace(tmpVector);
  96155. tmpSnapEvent.snapDistance = _this.snapDistance * dragSteps;
  96156. _this.onSnapObservable.notifyObservers(tmpSnapEvent);
  96157. }
  96158. }
  96159. }
  96160. });
  96161. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  96162. if (_this._customMeshSet) {
  96163. return;
  96164. }
  96165. var isHovered = pointerInfo.pickInfo && (_this._rootMesh.getChildMeshes().indexOf(pointerInfo.pickInfo.pickedMesh) != -1);
  96166. var material = isHovered ? hoverMaterial : coloredMaterial;
  96167. _this._rootMesh.getChildMeshes().forEach(function (m) {
  96168. m.material = material;
  96169. if (m.color) {
  96170. m.color = material.emissiveColor;
  96171. }
  96172. });
  96173. });
  96174. return _this;
  96175. }
  96176. AxisDragGizmo.prototype._attachedMeshChanged = function (value) {
  96177. if (this.dragBehavior) {
  96178. this.dragBehavior.enabled = value ? true : false;
  96179. }
  96180. };
  96181. /**
  96182. * Disposes of the gizmo
  96183. */
  96184. AxisDragGizmo.prototype.dispose = function () {
  96185. this.onSnapObservable.clear();
  96186. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  96187. this.dragBehavior.detach();
  96188. _super.prototype.dispose.call(this);
  96189. };
  96190. return AxisDragGizmo;
  96191. }(BABYLON.Gizmo));
  96192. BABYLON.AxisDragGizmo = AxisDragGizmo;
  96193. })(BABYLON || (BABYLON = {}));
  96194. //# sourceMappingURL=babylon.axisDragGizmo.js.map
  96195. var BABYLON;
  96196. (function (BABYLON) {
  96197. /**
  96198. * Single axis scale gizmo
  96199. */
  96200. var AxisScaleGizmo = /** @class */ (function (_super) {
  96201. __extends(AxisScaleGizmo, _super);
  96202. /**
  96203. * Creates an AxisScaleGizmo
  96204. * @param gizmoLayer The utility layer the gizmo will be added to
  96205. * @param dragAxis The axis which the gizmo will be able to scale on
  96206. * @param color The color of the gizmo
  96207. */
  96208. function AxisScaleGizmo(dragAxis, color, gizmoLayer) {
  96209. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  96210. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  96211. var _this = _super.call(this, gizmoLayer) || this;
  96212. _this._pointerObserver = null;
  96213. /**
  96214. * Scale distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  96215. */
  96216. _this.snapDistance = 0;
  96217. /**
  96218. * Event that fires each time the gizmo snaps to a new location.
  96219. * * snapDistance is the the change in distance
  96220. */
  96221. _this.onSnapObservable = new BABYLON.Observable();
  96222. /**
  96223. * If the scaling operation should be done on all axis (default: false)
  96224. */
  96225. _this.uniformScaling = false;
  96226. // Create Material
  96227. _this._coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  96228. _this._coloredMaterial.disableLighting = true;
  96229. _this._coloredMaterial.emissiveColor = color;
  96230. var hoverMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  96231. hoverMaterial.disableLighting = true;
  96232. hoverMaterial.emissiveColor = color.add(new BABYLON.Color3(0.3, 0.3, 0.3));
  96233. // Build mesh on root node
  96234. var arrow = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  96235. var arrowMesh = BABYLON.MeshBuilder.CreateBox("yPosMesh", { size: 0.4 }, gizmoLayer.utilityLayerScene);
  96236. var arrowTail = BABYLON.MeshBuilder.CreateLines("yPosMesh", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 1.1, 0)] }, gizmoLayer.utilityLayerScene);
  96237. arrowTail.color = _this._coloredMaterial.emissiveColor;
  96238. arrow.addChild(arrowMesh);
  96239. arrow.addChild(arrowTail);
  96240. // Position arrow pointing in its drag axis
  96241. arrowMesh.scaling.scaleInPlace(0.1);
  96242. arrowMesh.material = _this._coloredMaterial;
  96243. arrowMesh.rotation.x = Math.PI / 2;
  96244. arrowMesh.position.z += 0.3;
  96245. arrowTail.scaling.scaleInPlace(0.26);
  96246. arrowTail.rotation.x = Math.PI / 2;
  96247. arrowTail.material = _this._coloredMaterial;
  96248. arrow.lookAt(_this._rootMesh.position.subtract(dragAxis));
  96249. _this._rootMesh.addChild(arrow);
  96250. arrow.scaling.scaleInPlace(1 / 3);
  96251. // Add drag behavior to handle events when the gizmo is dragged
  96252. _this.dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });
  96253. _this.dragBehavior.moveAttached = false;
  96254. _this._rootMesh.addBehavior(_this.dragBehavior);
  96255. var currentSnapDragDistance = 0;
  96256. var tmpVector = new BABYLON.Vector3();
  96257. var tmpSnapEvent = { snapDistance: 0 };
  96258. _this.dragBehavior.onDragObservable.add(function (event) {
  96259. if (_this.attachedMesh) {
  96260. // Snapping logic
  96261. var snapped = false;
  96262. var dragSteps = 0;
  96263. if (_this.uniformScaling) {
  96264. _this.attachedMesh.scaling.normalizeToRef(tmpVector);
  96265. if (tmpVector.y < 0) {
  96266. tmpVector.scaleInPlace(-1);
  96267. }
  96268. }
  96269. else {
  96270. tmpVector.copyFrom(dragAxis);
  96271. }
  96272. if (_this.snapDistance == 0) {
  96273. tmpVector.scaleToRef(event.dragDistance, tmpVector);
  96274. }
  96275. else {
  96276. currentSnapDragDistance += event.dragDistance;
  96277. if (Math.abs(currentSnapDragDistance) > _this.snapDistance) {
  96278. dragSteps = Math.floor(currentSnapDragDistance / _this.snapDistance);
  96279. currentSnapDragDistance = currentSnapDragDistance % _this.snapDistance;
  96280. tmpVector.scaleToRef(_this.snapDistance * dragSteps, tmpVector);
  96281. snapped = true;
  96282. }
  96283. else {
  96284. tmpVector.scaleInPlace(0);
  96285. }
  96286. }
  96287. _this.attachedMesh.scaling.addInPlace(tmpVector);
  96288. if (snapped) {
  96289. tmpSnapEvent.snapDistance = _this.snapDistance * dragSteps;
  96290. _this.onSnapObservable.notifyObservers(tmpSnapEvent);
  96291. }
  96292. }
  96293. });
  96294. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  96295. if (_this._customMeshSet) {
  96296. return;
  96297. }
  96298. var isHovered = pointerInfo.pickInfo && (_this._rootMesh.getChildMeshes().indexOf(pointerInfo.pickInfo.pickedMesh) != -1);
  96299. var material = isHovered ? hoverMaterial : _this._coloredMaterial;
  96300. _this._rootMesh.getChildMeshes().forEach(function (m) {
  96301. m.material = material;
  96302. if (m.color) {
  96303. m.color = material.emissiveColor;
  96304. }
  96305. });
  96306. });
  96307. return _this;
  96308. }
  96309. AxisScaleGizmo.prototype._attachedMeshChanged = function (value) {
  96310. if (this.dragBehavior) {
  96311. this.dragBehavior.enabled = value ? true : false;
  96312. }
  96313. };
  96314. /**
  96315. * Disposes of the gizmo
  96316. */
  96317. AxisScaleGizmo.prototype.dispose = function () {
  96318. this.onSnapObservable.clear();
  96319. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  96320. this.dragBehavior.detach();
  96321. _super.prototype.dispose.call(this);
  96322. };
  96323. /**
  96324. * Disposes and replaces the current meshes in the gizmo with the specified mesh
  96325. * @param mesh The mesh to replace the default mesh of the gizmo
  96326. * @param useGizmoMaterial If the gizmo's default material should be used (default: false)
  96327. */
  96328. AxisScaleGizmo.prototype.setCustomMesh = function (mesh, useGizmoMaterial) {
  96329. var _this = this;
  96330. if (useGizmoMaterial === void 0) { useGizmoMaterial = false; }
  96331. _super.prototype.setCustomMesh.call(this, mesh);
  96332. if (useGizmoMaterial) {
  96333. this._rootMesh.getChildMeshes().forEach(function (m) {
  96334. m.material = _this._coloredMaterial;
  96335. if (m.color) {
  96336. m.color = _this._coloredMaterial.emissiveColor;
  96337. }
  96338. });
  96339. this._customMeshSet = false;
  96340. }
  96341. };
  96342. return AxisScaleGizmo;
  96343. }(BABYLON.Gizmo));
  96344. BABYLON.AxisScaleGizmo = AxisScaleGizmo;
  96345. })(BABYLON || (BABYLON = {}));
  96346. //# sourceMappingURL=babylon.axisScaleGizmo.js.map
  96347. var BABYLON;
  96348. (function (BABYLON) {
  96349. /**
  96350. * Single plane rotation gizmo
  96351. */
  96352. var PlaneRotationGizmo = /** @class */ (function (_super) {
  96353. __extends(PlaneRotationGizmo, _super);
  96354. /**
  96355. * Creates a PlaneRotationGizmo
  96356. * @param gizmoLayer The utility layer the gizmo will be added to
  96357. * @param planeNormal The normal of the plane which the gizmo will be able to rotate on
  96358. * @param color The color of the gizmo
  96359. */
  96360. function PlaneRotationGizmo(planeNormal, color, gizmoLayer) {
  96361. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  96362. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  96363. var _this = _super.call(this, gizmoLayer) || this;
  96364. _this._pointerObserver = null;
  96365. /**
  96366. * Rotation distance in radians that the gizmo will snap to (Default: 0)
  96367. */
  96368. _this.snapDistance = 0;
  96369. /**
  96370. * Event that fires each time the gizmo snaps to a new location.
  96371. * * snapDistance is the the change in distance
  96372. */
  96373. _this.onSnapObservable = new BABYLON.Observable();
  96374. // Create Material
  96375. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  96376. coloredMaterial.disableLighting = true;
  96377. coloredMaterial.emissiveColor = color;
  96378. var hoverMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  96379. hoverMaterial.disableLighting = true;
  96380. hoverMaterial.emissiveColor = color.add(new BABYLON.Color3(0.3, 0.3, 0.3));
  96381. // Build mesh on root node
  96382. var parentMesh = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  96383. // Create circle out of lines
  96384. var tessellation = 20;
  96385. var radius = 0.8;
  96386. var points = new Array();
  96387. for (var i = 0; i < tessellation; i++) {
  96388. var radian = (2 * Math.PI) * (i / (tessellation - 1));
  96389. points.push(new BABYLON.Vector3(radius * Math.sin(radian), 0, radius * Math.cos(radian)));
  96390. }
  96391. var rotationMesh = BABYLON.Mesh.CreateLines("", points, gizmoLayer.utilityLayerScene);
  96392. rotationMesh.color = coloredMaterial.emissiveColor;
  96393. // Position arrow pointing in its drag axis
  96394. rotationMesh.scaling.scaleInPlace(0.26);
  96395. rotationMesh.material = coloredMaterial;
  96396. rotationMesh.rotation.x = Math.PI / 2;
  96397. parentMesh.addChild(rotationMesh);
  96398. parentMesh.lookAt(_this._rootMesh.position.subtract(planeNormal));
  96399. _this._rootMesh.addChild(parentMesh);
  96400. parentMesh.scaling.scaleInPlace(1 / 3);
  96401. // Add drag behavior to handle events when the gizmo is dragged
  96402. _this.dragBehavior = new BABYLON.PointerDragBehavior({ dragPlaneNormal: planeNormal });
  96403. _this.dragBehavior.moveAttached = false;
  96404. _this.dragBehavior.maxDragAngle = Math.PI * 9 / 20;
  96405. _this.dragBehavior._useAlternatePickedPointAboveMaxDragAngle = true;
  96406. _this._rootMesh.addBehavior(_this.dragBehavior);
  96407. var lastDragPosition = new BABYLON.Vector3();
  96408. _this.dragBehavior.onDragStartObservable.add(function (e) {
  96409. if (_this.attachedMesh) {
  96410. lastDragPosition.copyFrom(e.dragPlanePoint);
  96411. }
  96412. });
  96413. var rotationMatrix = new BABYLON.Matrix();
  96414. var planeNormalTowardsCamera = new BABYLON.Vector3();
  96415. var localPlaneNormalTowardsCamera = new BABYLON.Vector3();
  96416. var tmpSnapEvent = { snapDistance: 0 };
  96417. var currentSnapDragDistance = 0;
  96418. var tmpMatrix = new BABYLON.Matrix();
  96419. var tmpVector = new BABYLON.Vector3();
  96420. var amountToRotate = new BABYLON.Quaternion();
  96421. _this.dragBehavior.onDragObservable.add(function (event) {
  96422. if (_this.attachedMesh) {
  96423. if (!_this.attachedMesh.rotationQuaternion) {
  96424. _this.attachedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this.attachedMesh.rotation.y, _this.attachedMesh.rotation.x, _this.attachedMesh.rotation.z);
  96425. }
  96426. // Calc angle over full 360 degree (https://stackoverflow.com/questions/43493711/the-angle-between-two-3d-vectors-with-a-result-range-0-360)
  96427. var newVector = event.dragPlanePoint.subtract(_this.attachedMesh.absolutePosition).normalize();
  96428. var originalVector = lastDragPosition.subtract(_this.attachedMesh.absolutePosition).normalize();
  96429. var cross = BABYLON.Vector3.Cross(newVector, originalVector);
  96430. var dot = BABYLON.Vector3.Dot(newVector, originalVector);
  96431. var angle = Math.atan2(cross.length(), dot);
  96432. planeNormalTowardsCamera.copyFrom(planeNormal);
  96433. localPlaneNormalTowardsCamera.copyFrom(planeNormal);
  96434. if (_this.updateGizmoRotationToMatchAttachedMesh) {
  96435. _this.attachedMesh.rotationQuaternion.toRotationMatrix(rotationMatrix);
  96436. localPlaneNormalTowardsCamera = BABYLON.Vector3.TransformCoordinates(planeNormalTowardsCamera, rotationMatrix);
  96437. }
  96438. // Flip up vector depending on which side the camera is on
  96439. if (gizmoLayer.utilityLayerScene.activeCamera) {
  96440. var camVec = gizmoLayer.utilityLayerScene.activeCamera.position.subtract(_this.attachedMesh.position);
  96441. if (BABYLON.Vector3.Dot(camVec, localPlaneNormalTowardsCamera) > 0) {
  96442. planeNormalTowardsCamera.scaleInPlace(-1);
  96443. localPlaneNormalTowardsCamera.scaleInPlace(-1);
  96444. }
  96445. }
  96446. var halfCircleSide = BABYLON.Vector3.Dot(localPlaneNormalTowardsCamera, cross) > 0.0;
  96447. if (halfCircleSide)
  96448. angle = -angle;
  96449. // Snapping logic
  96450. var snapped = false;
  96451. if (_this.snapDistance != 0) {
  96452. currentSnapDragDistance += angle;
  96453. if (Math.abs(currentSnapDragDistance) > _this.snapDistance) {
  96454. var dragSteps = Math.floor(currentSnapDragDistance / _this.snapDistance);
  96455. currentSnapDragDistance = currentSnapDragDistance % _this.snapDistance;
  96456. angle = _this.snapDistance * dragSteps;
  96457. snapped = true;
  96458. }
  96459. else {
  96460. angle = 0;
  96461. }
  96462. }
  96463. // If the mesh has a parent, convert needed world rotation to local rotation
  96464. tmpMatrix.reset();
  96465. if (_this.attachedMesh.parent) {
  96466. _this.attachedMesh.parent.computeWorldMatrix().invertToRef(tmpMatrix);
  96467. tmpMatrix.getRotationMatrixToRef(tmpMatrix);
  96468. BABYLON.Vector3.TransformCoordinatesToRef(planeNormalTowardsCamera, tmpMatrix, planeNormalTowardsCamera);
  96469. }
  96470. // Convert angle and axis to quaternion (http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm)
  96471. var quaternionCoefficient = Math.sin(angle / 2);
  96472. amountToRotate.set(planeNormalTowardsCamera.x * quaternionCoefficient, planeNormalTowardsCamera.y * quaternionCoefficient, planeNormalTowardsCamera.z * quaternionCoefficient, Math.cos(angle / 2));
  96473. // If the meshes local scale is inverted (eg. loaded gltf file parent with z scale of -1) the rotation needs to be inverted on the y axis
  96474. if (tmpMatrix.determinant() > 0) {
  96475. amountToRotate.toEulerAnglesToRef(tmpVector);
  96476. BABYLON.Quaternion.RotationYawPitchRollToRef(tmpVector.y, -tmpVector.x, -tmpVector.z, amountToRotate);
  96477. }
  96478. if (_this.updateGizmoRotationToMatchAttachedMesh) {
  96479. // Rotate selected mesh quaternion over fixed axis
  96480. _this.attachedMesh.rotationQuaternion.multiplyToRef(amountToRotate, _this.attachedMesh.rotationQuaternion);
  96481. }
  96482. else {
  96483. // Rotate selected mesh quaternion over rotated axis
  96484. amountToRotate.multiplyToRef(_this.attachedMesh.rotationQuaternion, _this.attachedMesh.rotationQuaternion);
  96485. }
  96486. lastDragPosition.copyFrom(event.dragPlanePoint);
  96487. if (snapped) {
  96488. tmpSnapEvent.snapDistance = angle;
  96489. _this.onSnapObservable.notifyObservers(tmpSnapEvent);
  96490. }
  96491. }
  96492. });
  96493. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  96494. if (_this._customMeshSet) {
  96495. return;
  96496. }
  96497. var isHovered = pointerInfo.pickInfo && (_this._rootMesh.getChildMeshes().indexOf(pointerInfo.pickInfo.pickedMesh) != -1);
  96498. var material = isHovered ? hoverMaterial : coloredMaterial;
  96499. _this._rootMesh.getChildMeshes().forEach(function (m) {
  96500. m.material = material;
  96501. if (m.color) {
  96502. m.color = material.emissiveColor;
  96503. }
  96504. });
  96505. });
  96506. return _this;
  96507. }
  96508. PlaneRotationGizmo.prototype._attachedMeshChanged = function (value) {
  96509. if (this.dragBehavior) {
  96510. this.dragBehavior.enabled = value ? true : false;
  96511. }
  96512. };
  96513. /**
  96514. * Disposes of the gizmo
  96515. */
  96516. PlaneRotationGizmo.prototype.dispose = function () {
  96517. this.onSnapObservable.clear();
  96518. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  96519. this.dragBehavior.detach();
  96520. _super.prototype.dispose.call(this);
  96521. };
  96522. return PlaneRotationGizmo;
  96523. }(BABYLON.Gizmo));
  96524. BABYLON.PlaneRotationGizmo = PlaneRotationGizmo;
  96525. })(BABYLON || (BABYLON = {}));
  96526. //# sourceMappingURL=babylon.planeRotationGizmo.js.map
  96527. var BABYLON;
  96528. (function (BABYLON) {
  96529. /**
  96530. * Gizmo that enables dragging a mesh along 3 axis
  96531. */
  96532. var PositionGizmo = /** @class */ (function (_super) {
  96533. __extends(PositionGizmo, _super);
  96534. /**
  96535. * Creates a PositionGizmo
  96536. * @param gizmoLayer The utility layer the gizmo will be added to
  96537. */
  96538. function PositionGizmo(gizmoLayer) {
  96539. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  96540. var _this = _super.call(this, gizmoLayer) || this;
  96541. _this.xGizmo = new BABYLON.AxisDragGizmo(new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.Green().scale(0.5), gizmoLayer);
  96542. _this.yGizmo = new BABYLON.AxisDragGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Red().scale(0.5), gizmoLayer);
  96543. _this.zGizmo = new BABYLON.AxisDragGizmo(new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.Blue().scale(0.5), gizmoLayer);
  96544. _this.attachedMesh = null;
  96545. return _this;
  96546. }
  96547. Object.defineProperty(PositionGizmo.prototype, "attachedMesh", {
  96548. set: function (mesh) {
  96549. if (this.xGizmo) {
  96550. this.xGizmo.attachedMesh = mesh;
  96551. this.yGizmo.attachedMesh = mesh;
  96552. this.zGizmo.attachedMesh = mesh;
  96553. }
  96554. },
  96555. enumerable: true,
  96556. configurable: true
  96557. });
  96558. Object.defineProperty(PositionGizmo.prototype, "updateGizmoRotationToMatchAttachedMesh", {
  96559. get: function () {
  96560. return this.xGizmo.updateGizmoRotationToMatchAttachedMesh;
  96561. },
  96562. set: function (value) {
  96563. if (this.xGizmo) {
  96564. this.xGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  96565. this.yGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  96566. this.zGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  96567. }
  96568. },
  96569. enumerable: true,
  96570. configurable: true
  96571. });
  96572. Object.defineProperty(PositionGizmo.prototype, "snapDistance", {
  96573. get: function () {
  96574. return this.xGizmo.snapDistance;
  96575. },
  96576. /**
  96577. * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  96578. */
  96579. set: function (value) {
  96580. if (this.xGizmo) {
  96581. this.xGizmo.snapDistance = value;
  96582. this.yGizmo.snapDistance = value;
  96583. this.zGizmo.snapDistance = value;
  96584. }
  96585. },
  96586. enumerable: true,
  96587. configurable: true
  96588. });
  96589. Object.defineProperty(PositionGizmo.prototype, "scaleRatio", {
  96590. get: function () {
  96591. return this.xGizmo.scaleRatio;
  96592. },
  96593. /**
  96594. * Ratio for the scale of the gizmo (Default: 1)
  96595. */
  96596. set: function (value) {
  96597. if (this.xGizmo) {
  96598. this.xGizmo.scaleRatio = value;
  96599. this.yGizmo.scaleRatio = value;
  96600. this.zGizmo.scaleRatio = value;
  96601. }
  96602. },
  96603. enumerable: true,
  96604. configurable: true
  96605. });
  96606. /**
  96607. * Disposes of the gizmo
  96608. */
  96609. PositionGizmo.prototype.dispose = function () {
  96610. this.xGizmo.dispose();
  96611. this.yGizmo.dispose();
  96612. this.zGizmo.dispose();
  96613. };
  96614. /**
  96615. * CustomMeshes are not supported by this gizmo
  96616. * @param mesh The mesh to replace the default mesh of the gizmo
  96617. */
  96618. PositionGizmo.prototype.setCustomMesh = function (mesh) {
  96619. BABYLON.Tools.Error("Custom meshes are not supported on this gizmo, please set the custom meshes on the gizmos contained within this one (gizmo.xGizmo, gizmo.yGizmo, gizmo.zGizmo)");
  96620. };
  96621. return PositionGizmo;
  96622. }(BABYLON.Gizmo));
  96623. BABYLON.PositionGizmo = PositionGizmo;
  96624. })(BABYLON || (BABYLON = {}));
  96625. //# sourceMappingURL=babylon.positionGizmo.js.map
  96626. var BABYLON;
  96627. (function (BABYLON) {
  96628. /**
  96629. * Gizmo that enables rotating a mesh along 3 axis
  96630. */
  96631. var RotationGizmo = /** @class */ (function (_super) {
  96632. __extends(RotationGizmo, _super);
  96633. /**
  96634. * Creates a RotationGizmo
  96635. * @param gizmoLayer The utility layer the gizmo will be added to
  96636. */
  96637. function RotationGizmo(gizmoLayer) {
  96638. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  96639. var _this = _super.call(this, gizmoLayer) || this;
  96640. _this.xGizmo = new BABYLON.PlaneRotationGizmo(new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.Green().scale(0.5), gizmoLayer);
  96641. _this.yGizmo = new BABYLON.PlaneRotationGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Red().scale(0.5), gizmoLayer);
  96642. _this.zGizmo = new BABYLON.PlaneRotationGizmo(new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.Blue().scale(0.5), gizmoLayer);
  96643. _this.attachedMesh = null;
  96644. return _this;
  96645. }
  96646. Object.defineProperty(RotationGizmo.prototype, "attachedMesh", {
  96647. set: function (mesh) {
  96648. if (this.xGizmo) {
  96649. this.xGizmo.attachedMesh = mesh;
  96650. this.yGizmo.attachedMesh = mesh;
  96651. this.zGizmo.attachedMesh = mesh;
  96652. }
  96653. },
  96654. enumerable: true,
  96655. configurable: true
  96656. });
  96657. Object.defineProperty(RotationGizmo.prototype, "updateGizmoRotationToMatchAttachedMesh", {
  96658. get: function () {
  96659. return this.xGizmo.updateGizmoRotationToMatchAttachedMesh;
  96660. },
  96661. set: function (value) {
  96662. if (this.xGizmo) {
  96663. this.xGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  96664. this.yGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  96665. this.zGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  96666. }
  96667. },
  96668. enumerable: true,
  96669. configurable: true
  96670. });
  96671. Object.defineProperty(RotationGizmo.prototype, "snapDistance", {
  96672. get: function () {
  96673. return this.xGizmo.snapDistance;
  96674. },
  96675. /**
  96676. * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  96677. */
  96678. set: function (value) {
  96679. if (this.xGizmo) {
  96680. this.xGizmo.snapDistance = value;
  96681. this.yGizmo.snapDistance = value;
  96682. this.zGizmo.snapDistance = value;
  96683. }
  96684. },
  96685. enumerable: true,
  96686. configurable: true
  96687. });
  96688. Object.defineProperty(RotationGizmo.prototype, "scaleRatio", {
  96689. get: function () {
  96690. return this.xGizmo.scaleRatio;
  96691. },
  96692. /**
  96693. * Ratio for the scale of the gizmo (Default: 1)
  96694. */
  96695. set: function (value) {
  96696. if (this.xGizmo) {
  96697. this.xGizmo.scaleRatio = value;
  96698. this.yGizmo.scaleRatio = value;
  96699. this.zGizmo.scaleRatio = value;
  96700. }
  96701. },
  96702. enumerable: true,
  96703. configurable: true
  96704. });
  96705. /**
  96706. * Disposes of the gizmo
  96707. */
  96708. RotationGizmo.prototype.dispose = function () {
  96709. this.xGizmo.dispose();
  96710. this.yGizmo.dispose();
  96711. this.zGizmo.dispose();
  96712. };
  96713. /**
  96714. * CustomMeshes are not supported by this gizmo
  96715. * @param mesh The mesh to replace the default mesh of the gizmo
  96716. */
  96717. RotationGizmo.prototype.setCustomMesh = function (mesh) {
  96718. BABYLON.Tools.Error("Custom meshes are not supported on this gizmo, please set the custom meshes on the gizmos contained within this one (gizmo.xGizmo, gizmo.yGizmo, gizmo.zGizmo)");
  96719. };
  96720. return RotationGizmo;
  96721. }(BABYLON.Gizmo));
  96722. BABYLON.RotationGizmo = RotationGizmo;
  96723. })(BABYLON || (BABYLON = {}));
  96724. //# sourceMappingURL=babylon.rotationGizmo.js.map
  96725. var BABYLON;
  96726. (function (BABYLON) {
  96727. /**
  96728. * Gizmo that enables scaling a mesh along 3 axis
  96729. */
  96730. var ScaleGizmo = /** @class */ (function (_super) {
  96731. __extends(ScaleGizmo, _super);
  96732. /**
  96733. * Creates a ScaleGizmo
  96734. * @param gizmoLayer The utility layer the gizmo will be added to
  96735. */
  96736. function ScaleGizmo(gizmoLayer) {
  96737. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  96738. var _this = _super.call(this, gizmoLayer) || this;
  96739. _this.xGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.Green().scale(0.5), gizmoLayer);
  96740. _this.yGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Red().scale(0.5), gizmoLayer);
  96741. _this.zGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.Blue().scale(0.5), gizmoLayer);
  96742. // Create uniform scale gizmo
  96743. _this.uniformScaleGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Yellow().scale(0.5), gizmoLayer);
  96744. _this.uniformScaleGizmo.updateGizmoRotationToMatchAttachedMesh = false;
  96745. _this.uniformScaleGizmo.uniformScaling = true;
  96746. var octahedron = BABYLON.Mesh.CreatePolyhedron("", { type: 1 }, _this.uniformScaleGizmo.gizmoLayer.utilityLayerScene);
  96747. octahedron.scaling.scaleInPlace(0.007);
  96748. _this.uniformScaleGizmo.setCustomMesh(octahedron, true);
  96749. _this.attachedMesh = null;
  96750. return _this;
  96751. }
  96752. Object.defineProperty(ScaleGizmo.prototype, "attachedMesh", {
  96753. set: function (mesh) {
  96754. if (this.xGizmo) {
  96755. this.xGizmo.attachedMesh = mesh;
  96756. this.yGizmo.attachedMesh = mesh;
  96757. this.zGizmo.attachedMesh = mesh;
  96758. this.uniformScaleGizmo.attachedMesh = mesh;
  96759. }
  96760. },
  96761. enumerable: true,
  96762. configurable: true
  96763. });
  96764. Object.defineProperty(ScaleGizmo.prototype, "updateGizmoRotationToMatchAttachedMesh", {
  96765. get: function () {
  96766. return this.xGizmo.updateGizmoRotationToMatchAttachedMesh;
  96767. },
  96768. set: function (value) {
  96769. if (this.xGizmo) {
  96770. this.xGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  96771. this.yGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  96772. this.zGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  96773. }
  96774. },
  96775. enumerable: true,
  96776. configurable: true
  96777. });
  96778. Object.defineProperty(ScaleGizmo.prototype, "snapDistance", {
  96779. get: function () {
  96780. return this.xGizmo.snapDistance;
  96781. },
  96782. /**
  96783. * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  96784. */
  96785. set: function (value) {
  96786. if (this.xGizmo) {
  96787. this.xGizmo.snapDistance = value;
  96788. this.yGizmo.snapDistance = value;
  96789. this.zGizmo.snapDistance = value;
  96790. this.uniformScaleGizmo.snapDistance = value;
  96791. }
  96792. },
  96793. enumerable: true,
  96794. configurable: true
  96795. });
  96796. Object.defineProperty(ScaleGizmo.prototype, "scaleRatio", {
  96797. get: function () {
  96798. return this.xGizmo.scaleRatio;
  96799. },
  96800. /**
  96801. * Ratio for the scale of the gizmo (Default: 1)
  96802. */
  96803. set: function (value) {
  96804. if (this.xGizmo) {
  96805. this.xGizmo.scaleRatio = value;
  96806. this.yGizmo.scaleRatio = value;
  96807. this.zGizmo.scaleRatio = value;
  96808. this.uniformScaleGizmo.scaleRatio = value;
  96809. }
  96810. },
  96811. enumerable: true,
  96812. configurable: true
  96813. });
  96814. /**
  96815. * Disposes of the gizmo
  96816. */
  96817. ScaleGizmo.prototype.dispose = function () {
  96818. this.xGizmo.dispose();
  96819. this.yGizmo.dispose();
  96820. this.zGizmo.dispose();
  96821. this.uniformScaleGizmo.dispose();
  96822. };
  96823. return ScaleGizmo;
  96824. }(BABYLON.Gizmo));
  96825. BABYLON.ScaleGizmo = ScaleGizmo;
  96826. })(BABYLON || (BABYLON = {}));
  96827. //# sourceMappingURL=babylon.scaleGizmo.js.map
  96828. var BABYLON;
  96829. (function (BABYLON) {
  96830. /**
  96831. * Bounding box gizmo
  96832. */
  96833. var BoundingBoxGizmo = /** @class */ (function (_super) {
  96834. __extends(BoundingBoxGizmo, _super);
  96835. /**
  96836. * Creates an BoundingBoxGizmo
  96837. * @param gizmoLayer The utility layer the gizmo will be added to
  96838. * @param color The color of the gizmo
  96839. */
  96840. function BoundingBoxGizmo(color, gizmoLayer) {
  96841. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  96842. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultKeepDepthUtilityLayer; }
  96843. var _this = _super.call(this, gizmoLayer) || this;
  96844. _this._boundingDimensions = new BABYLON.Vector3(1, 1, 1);
  96845. _this._renderObserver = null;
  96846. _this._pointerObserver = null;
  96847. _this._scaleDragSpeed = 0.2;
  96848. _this._tmpQuaternion = new BABYLON.Quaternion();
  96849. _this._tmpVector = new BABYLON.Vector3(0, 0, 0);
  96850. _this._tmpRotationMatrix = new BABYLON.Matrix();
  96851. /**
  96852. * If child meshes should be ignored when calculating the boudning box. This should be set to true to avoid perf hits with heavily nested meshes (Default: false)
  96853. */
  96854. _this.ignoreChildren = false;
  96855. /**
  96856. * Returns true if a descendant should be included when computing the bounding box. When null, all descendants are included. If ignoreChildren is set this will be ignored. (Default: null)
  96857. */
  96858. _this.includeChildPredicate = null;
  96859. /**
  96860. * The size of the rotation spheres attached to the bounding box (Default: 0.1)
  96861. */
  96862. _this.rotationSphereSize = 0.1;
  96863. /**
  96864. * The size of the scale boxes attached to the bounding box (Default: 0.1)
  96865. */
  96866. _this.scaleBoxSize = 0.1;
  96867. /**
  96868. * If set, the rotation spheres and scale boxes will increase in size based on the distance away from the camera to have a consistent screen size (Default: false)
  96869. */
  96870. _this.fixedDragMeshScreenSize = false;
  96871. /**
  96872. * The distance away from the object which the draggable meshes should appear world sized when fixedDragMeshScreenSize is set to true (default: 10)
  96873. */
  96874. _this.fixedDragMeshScreenSizeDistanceFactor = 10;
  96875. /**
  96876. * Fired when a rotation sphere or scale box is dragged
  96877. */
  96878. _this.onDragStartObservable = new BABYLON.Observable();
  96879. /**
  96880. * Fired when a scale box is dragged
  96881. */
  96882. _this.onScaleBoxDragObservable = new BABYLON.Observable();
  96883. /**
  96884. * Fired when a scale box drag is ended
  96885. */
  96886. _this.onScaleBoxDragEndObservable = new BABYLON.Observable();
  96887. /**
  96888. * Fired when a rotation sphere is dragged
  96889. */
  96890. _this.onRotationSphereDragObservable = new BABYLON.Observable();
  96891. /**
  96892. * Fired when a rotation sphere drag is ended
  96893. */
  96894. _this.onRotationSphereDragEndObservable = new BABYLON.Observable();
  96895. /**
  96896. * Relative bounding box pivot used when scaling the attached mesh. When null object with scale from the opposite corner. 0.5,0.5,0.5 for center and 0.5,0,0.5 for bottom (Default: null)
  96897. */
  96898. _this.scalePivot = null;
  96899. _this._existingMeshScale = new BABYLON.Vector3();
  96900. // Do not update the gizmo's scale so it has a fixed size to the object its attached to
  96901. _this._updateScale = false;
  96902. _this._anchorMesh = new BABYLON.AbstractMesh("anchor", gizmoLayer.utilityLayerScene);
  96903. // Create Materials
  96904. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  96905. coloredMaterial.disableLighting = true;
  96906. coloredMaterial.emissiveColor = color;
  96907. var hoverColoredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  96908. hoverColoredMaterial.disableLighting = true;
  96909. hoverColoredMaterial.emissiveColor = color.clone().add(new BABYLON.Color3(0.3, 0.3, 0.3));
  96910. // Build bounding box out of lines
  96911. _this._lineBoundingBox = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  96912. _this._lineBoundingBox.rotationQuaternion = new BABYLON.Quaternion();
  96913. var lines = [];
  96914. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(_this._boundingDimensions.x, 0, 0)] }, gizmoLayer.utilityLayerScene));
  96915. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, _this._boundingDimensions.y, 0)] }, gizmoLayer.utilityLayerScene));
  96916. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));
  96917. 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));
  96918. 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));
  96919. 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));
  96920. 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));
  96921. 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));
  96922. 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));
  96923. 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));
  96924. 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));
  96925. 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));
  96926. lines.forEach(function (l) {
  96927. l.color = color;
  96928. l.position.addInPlace(new BABYLON.Vector3(-_this._boundingDimensions.x / 2, -_this._boundingDimensions.y / 2, -_this._boundingDimensions.z / 2));
  96929. l.isPickable = false;
  96930. _this._lineBoundingBox.addChild(l);
  96931. });
  96932. _this._rootMesh.addChild(_this._lineBoundingBox);
  96933. // Create rotation spheres
  96934. _this._rotateSpheresParent = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  96935. _this._rotateSpheresParent.rotationQuaternion = new BABYLON.Quaternion();
  96936. var _loop_1 = function (i_1) {
  96937. var sphere = BABYLON.MeshBuilder.CreateSphere("", { diameter: 1 }, gizmoLayer.utilityLayerScene);
  96938. sphere.rotationQuaternion = new BABYLON.Quaternion();
  96939. sphere.material = coloredMaterial;
  96940. // Drag behavior
  96941. _dragBehavior = new BABYLON.PointerDragBehavior({});
  96942. _dragBehavior.moveAttached = false;
  96943. _dragBehavior.updateDragPlane = false;
  96944. sphere.addBehavior(_dragBehavior);
  96945. var startingTurnDirection = new BABYLON.Vector3(1, 0, 0);
  96946. var totalTurnAmountOfDrag = 0;
  96947. _dragBehavior.onDragStartObservable.add(function (event) {
  96948. startingTurnDirection.copyFrom(sphere.forward);
  96949. totalTurnAmountOfDrag = 0;
  96950. });
  96951. _dragBehavior.onDragObservable.add(function (event) {
  96952. _this.onRotationSphereDragObservable.notifyObservers({});
  96953. if (_this.attachedMesh) {
  96954. BoundingBoxGizmo._RemoveAndStorePivotPoint(_this.attachedMesh);
  96955. var worldDragDirection = startingTurnDirection;
  96956. // Project the world right on to the drag plane
  96957. var toSub = event.dragPlaneNormal.scale(BABYLON.Vector3.Dot(event.dragPlaneNormal, worldDragDirection));
  96958. var dragAxis = worldDragDirection.subtract(toSub).normalizeToNew();
  96959. // project drag delta on to the resulting drag axis and rotate based on that
  96960. var projectDist = -BABYLON.Vector3.Dot(dragAxis, event.delta);
  96961. // Make rotation relative to size of mesh.
  96962. projectDist = (projectDist / _this._boundingDimensions.length()) * _this._anchorMesh.scaling.length();
  96963. // Rotate based on axis
  96964. if (!_this.attachedMesh.rotationQuaternion) {
  96965. _this.attachedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this.attachedMesh.rotation.y, _this.attachedMesh.rotation.x, _this.attachedMesh.rotation.z);
  96966. }
  96967. if (!_this._anchorMesh.rotationQuaternion) {
  96968. _this._anchorMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this._anchorMesh.rotation.y, _this._anchorMesh.rotation.x, _this._anchorMesh.rotation.z);
  96969. }
  96970. // Do not allow the object to turn more than a full circle
  96971. totalTurnAmountOfDrag += projectDist;
  96972. if (Math.abs(totalTurnAmountOfDrag) <= 2 * Math.PI) {
  96973. if (i_1 >= 8) {
  96974. BABYLON.Quaternion.RotationYawPitchRollToRef(0, 0, projectDist, _this._tmpQuaternion);
  96975. }
  96976. else if (i_1 >= 4) {
  96977. BABYLON.Quaternion.RotationYawPitchRollToRef(projectDist, 0, 0, _this._tmpQuaternion);
  96978. }
  96979. else {
  96980. BABYLON.Quaternion.RotationYawPitchRollToRef(0, projectDist, 0, _this._tmpQuaternion);
  96981. }
  96982. // Rotate around center of bounding box
  96983. _this._anchorMesh.addChild(_this.attachedMesh);
  96984. _this._anchorMesh.rotationQuaternion.multiplyToRef(_this._tmpQuaternion, _this._anchorMesh.rotationQuaternion);
  96985. _this._anchorMesh.removeChild(_this.attachedMesh);
  96986. }
  96987. _this.updateBoundingBox();
  96988. BoundingBoxGizmo._RestorePivotPoint(_this.attachedMesh);
  96989. }
  96990. });
  96991. // Selection/deselection
  96992. _dragBehavior.onDragStartObservable.add(function () {
  96993. _this.onDragStartObservable.notifyObservers({});
  96994. _this._selectNode(sphere);
  96995. });
  96996. _dragBehavior.onDragEndObservable.add(function () {
  96997. _this.onRotationSphereDragEndObservable.notifyObservers({});
  96998. _this._selectNode(null);
  96999. });
  97000. this_1._rotateSpheresParent.addChild(sphere);
  97001. };
  97002. var this_1 = this, _dragBehavior;
  97003. for (var i_1 = 0; i_1 < 12; i_1++) {
  97004. _loop_1(i_1);
  97005. }
  97006. _this._rootMesh.addChild(_this._rotateSpheresParent);
  97007. // Create scale cubes
  97008. _this._scaleBoxesParent = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  97009. _this._scaleBoxesParent.rotationQuaternion = new BABYLON.Quaternion();
  97010. for (var i = 0; i < 2; i++) {
  97011. for (var j = 0; j < 2; j++) {
  97012. var _loop_2 = function () {
  97013. var box = BABYLON.MeshBuilder.CreateBox("", { size: 1 }, gizmoLayer.utilityLayerScene);
  97014. box.material = coloredMaterial;
  97015. // Dragging logic
  97016. var dragAxis = new BABYLON.Vector3(i == 0 ? -1 : 1, j == 0 ? -1 : 1, k == 0 ? -1 : 1);
  97017. _dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });
  97018. _dragBehavior.moveAttached = false;
  97019. box.addBehavior(_dragBehavior);
  97020. _dragBehavior.onDragObservable.add(function (event) {
  97021. _this.onScaleBoxDragObservable.notifyObservers({});
  97022. if (_this.attachedMesh) {
  97023. BoundingBoxGizmo._RemoveAndStorePivotPoint(_this.attachedMesh);
  97024. var relativeDragDistance = (event.dragDistance / _this._boundingDimensions.length()) * _this._anchorMesh.scaling.length();
  97025. var deltaScale = new BABYLON.Vector3(relativeDragDistance, relativeDragDistance, relativeDragDistance);
  97026. deltaScale.scaleInPlace(_this._scaleDragSpeed);
  97027. _this.updateBoundingBox();
  97028. if (_this.scalePivot) {
  97029. _this.attachedMesh.getWorldMatrix().getRotationMatrixToRef(_this._tmpRotationMatrix);
  97030. // Move anchor to desired pivot point (Bottom left corner + dimension/2)
  97031. _this._boundingDimensions.scaleToRef(0.5, _this._tmpVector);
  97032. BABYLON.Vector3.TransformCoordinatesToRef(_this._tmpVector, _this._tmpRotationMatrix, _this._tmpVector);
  97033. _this._anchorMesh.position.subtractInPlace(_this._tmpVector);
  97034. _this._boundingDimensions.multiplyToRef(_this.scalePivot, _this._tmpVector);
  97035. BABYLON.Vector3.TransformCoordinatesToRef(_this._tmpVector, _this._tmpRotationMatrix, _this._tmpVector);
  97036. _this._anchorMesh.position.addInPlace(_this._tmpVector);
  97037. }
  97038. else {
  97039. // Scale from the position of the opposite corner
  97040. box.absolutePosition.subtractToRef(_this._anchorMesh.position, _this._tmpVector);
  97041. _this._anchorMesh.position.subtractInPlace(_this._tmpVector);
  97042. }
  97043. _this._anchorMesh.addChild(_this.attachedMesh);
  97044. _this._anchorMesh.scaling.addInPlace(deltaScale);
  97045. if (_this._anchorMesh.scaling.x < 0 || _this._anchorMesh.scaling.y < 0 || _this._anchorMesh.scaling.z < 0) {
  97046. _this._anchorMesh.scaling.subtractInPlace(deltaScale);
  97047. }
  97048. _this._anchorMesh.removeChild(_this.attachedMesh);
  97049. BoundingBoxGizmo._RestorePivotPoint(_this.attachedMesh);
  97050. }
  97051. });
  97052. // Selection/deselection
  97053. _dragBehavior.onDragStartObservable.add(function () {
  97054. _this.onDragStartObservable.notifyObservers({});
  97055. _this._selectNode(box);
  97056. });
  97057. _dragBehavior.onDragEndObservable.add(function () {
  97058. _this.onScaleBoxDragEndObservable.notifyObservers({});
  97059. _this._selectNode(null);
  97060. });
  97061. this_2._scaleBoxesParent.addChild(box);
  97062. };
  97063. var this_2 = this, _dragBehavior;
  97064. for (var k = 0; k < 2; k++) {
  97065. _loop_2();
  97066. }
  97067. }
  97068. }
  97069. _this._rootMesh.addChild(_this._scaleBoxesParent);
  97070. // Hover color change
  97071. var pointerIds = new Array();
  97072. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  97073. if (!pointerIds[pointerInfo.event.pointerId]) {
  97074. _this._rotateSpheresParent.getChildMeshes().concat(_this._scaleBoxesParent.getChildMeshes()).forEach(function (mesh) {
  97075. if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh == mesh) {
  97076. pointerIds[pointerInfo.event.pointerId] = mesh;
  97077. mesh.material = hoverColoredMaterial;
  97078. }
  97079. });
  97080. }
  97081. else {
  97082. if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh != pointerIds[pointerInfo.event.pointerId]) {
  97083. pointerIds[pointerInfo.event.pointerId].material = coloredMaterial;
  97084. delete pointerIds[pointerInfo.event.pointerId];
  97085. }
  97086. }
  97087. });
  97088. // Update bounding box positions
  97089. _this._renderObserver = _this.gizmoLayer.originalScene.onBeforeRenderObservable.add(function () {
  97090. // Only update the bouding box if scaling has changed
  97091. if (_this.attachedMesh && !_this._existingMeshScale.equals(_this.attachedMesh.scaling)) {
  97092. _this.updateBoundingBox();
  97093. }
  97094. });
  97095. _this.updateBoundingBox();
  97096. return _this;
  97097. }
  97098. /** @hidden */
  97099. BoundingBoxGizmo._RemoveAndStorePivotPoint = function (mesh) {
  97100. if (mesh && BoundingBoxGizmo._PivotCached === 0) {
  97101. // Save old pivot and set pivot to 0,0,0
  97102. mesh.getPivotPointToRef(BoundingBoxGizmo._OldPivotPoint);
  97103. if (!BoundingBoxGizmo._OldPivotPoint.equalsToFloats(0, 0, 0)) {
  97104. mesh.setPivotMatrix(BABYLON.Matrix.IdentityReadOnly);
  97105. BoundingBoxGizmo._OldPivotPoint.subtractToRef(mesh.getPivotPoint(), BoundingBoxGizmo._PivotTranslation);
  97106. BoundingBoxGizmo._PivotTmpVector.copyFromFloats(1, 1, 1);
  97107. BoundingBoxGizmo._PivotTmpVector.subtractInPlace(mesh.scaling);
  97108. BoundingBoxGizmo._PivotTmpVector.multiplyInPlace(BoundingBoxGizmo._PivotTranslation);
  97109. mesh.position.addInPlace(BoundingBoxGizmo._PivotTmpVector);
  97110. }
  97111. }
  97112. BoundingBoxGizmo._PivotCached++;
  97113. };
  97114. /** @hidden */
  97115. BoundingBoxGizmo._RestorePivotPoint = function (mesh) {
  97116. if (mesh && !BoundingBoxGizmo._OldPivotPoint.equalsToFloats(0, 0, 0) && BoundingBoxGizmo._PivotCached === 1) {
  97117. mesh.setPivotPoint(BoundingBoxGizmo._OldPivotPoint);
  97118. BoundingBoxGizmo._PivotTmpVector.copyFromFloats(1, 1, 1);
  97119. BoundingBoxGizmo._PivotTmpVector.subtractInPlace(mesh.scaling);
  97120. BoundingBoxGizmo._PivotTmpVector.multiplyInPlace(BoundingBoxGizmo._PivotTranslation);
  97121. mesh.position.subtractInPlace(BoundingBoxGizmo._PivotTmpVector);
  97122. }
  97123. this._PivotCached--;
  97124. };
  97125. BoundingBoxGizmo.prototype._attachedMeshChanged = function (value) {
  97126. if (value) {
  97127. // Reset anchor mesh to match attached mesh's scale
  97128. // This is needed to avoid invalid box/sphere position on first drag
  97129. BoundingBoxGizmo._RemoveAndStorePivotPoint(value);
  97130. this._anchorMesh.addChild(value);
  97131. this._anchorMesh.removeChild(value);
  97132. BoundingBoxGizmo._RestorePivotPoint(value);
  97133. this.updateBoundingBox();
  97134. }
  97135. };
  97136. BoundingBoxGizmo.prototype._selectNode = function (selectedMesh) {
  97137. this._rotateSpheresParent.getChildMeshes()
  97138. .concat(this._scaleBoxesParent.getChildMeshes()).forEach(function (m, i) {
  97139. m.isVisible = (!selectedMesh || m == selectedMesh);
  97140. });
  97141. };
  97142. /**
  97143. * Updates the bounding box information for the Gizmo
  97144. */
  97145. BoundingBoxGizmo.prototype.updateBoundingBox = function () {
  97146. if (this.attachedMesh) {
  97147. BoundingBoxGizmo._RemoveAndStorePivotPoint(this.attachedMesh);
  97148. this._update();
  97149. // Rotate based on axis
  97150. if (!this.attachedMesh.rotationQuaternion) {
  97151. this.attachedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.attachedMesh.rotation.y, this.attachedMesh.rotation.x, this.attachedMesh.rotation.z);
  97152. }
  97153. if (!this._anchorMesh.rotationQuaternion) {
  97154. this._anchorMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this._anchorMesh.rotation.y, this._anchorMesh.rotation.x, this._anchorMesh.rotation.z);
  97155. }
  97156. this._anchorMesh.rotationQuaternion.copyFrom(this.attachedMesh.rotationQuaternion);
  97157. // Store original position and reset mesh to origin before computing the bounding box
  97158. this._tmpQuaternion.copyFrom(this.attachedMesh.rotationQuaternion);
  97159. this._tmpVector.copyFrom(this.attachedMesh.position);
  97160. this.attachedMesh.rotationQuaternion.set(0, 0, 0, 1);
  97161. this.attachedMesh.position.set(0, 0, 0);
  97162. // Update bounding dimensions/positions
  97163. var boundingMinMax = this.attachedMesh.getHierarchyBoundingVectors(!this.ignoreChildren, this.includeChildPredicate);
  97164. boundingMinMax.max.subtractToRef(boundingMinMax.min, this._boundingDimensions);
  97165. // Update gizmo to match bounding box scaling and rotation
  97166. this._lineBoundingBox.scaling.copyFrom(this._boundingDimensions);
  97167. this._lineBoundingBox.position.set((boundingMinMax.max.x + boundingMinMax.min.x) / 2, (boundingMinMax.max.y + boundingMinMax.min.y) / 2, (boundingMinMax.max.z + boundingMinMax.min.z) / 2);
  97168. this._rotateSpheresParent.position.copyFrom(this._lineBoundingBox.position);
  97169. this._scaleBoxesParent.position.copyFrom(this._lineBoundingBox.position);
  97170. this._lineBoundingBox.computeWorldMatrix();
  97171. this._anchorMesh.position.copyFrom(this._lineBoundingBox.absolutePosition);
  97172. // restore position/rotation values
  97173. this.attachedMesh.rotationQuaternion.copyFrom(this._tmpQuaternion);
  97174. this.attachedMesh.position.copyFrom(this._tmpVector);
  97175. }
  97176. // Update rotation sphere locations
  97177. var rotateSpheres = this._rotateSpheresParent.getChildMeshes();
  97178. for (var i = 0; i < 3; i++) {
  97179. for (var j = 0; j < 2; j++) {
  97180. for (var k = 0; k < 2; k++) {
  97181. var index = ((i * 4) + (j * 2)) + k;
  97182. if (i == 0) {
  97183. rotateSpheres[index].position.set(this._boundingDimensions.x / 2, this._boundingDimensions.y * j, this._boundingDimensions.z * k);
  97184. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  97185. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Right(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
  97186. }
  97187. if (i == 1) {
  97188. rotateSpheres[index].position.set(this._boundingDimensions.x * j, this._boundingDimensions.y / 2, this._boundingDimensions.z * k);
  97189. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  97190. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Up(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
  97191. }
  97192. if (i == 2) {
  97193. rotateSpheres[index].position.set(this._boundingDimensions.x * j, this._boundingDimensions.y * k, this._boundingDimensions.z / 2);
  97194. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  97195. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Forward(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
  97196. }
  97197. if (this.fixedDragMeshScreenSize) {
  97198. this._rootMesh.computeWorldMatrix();
  97199. this._rotateSpheresParent.computeWorldMatrix();
  97200. rotateSpheres[index].computeWorldMatrix();
  97201. rotateSpheres[index].absolutePosition.subtractToRef(this.gizmoLayer.utilityLayerScene.activeCamera.position, this._tmpVector);
  97202. var distanceFromCamera = this.rotationSphereSize * this._tmpVector.length() / this.fixedDragMeshScreenSizeDistanceFactor;
  97203. rotateSpheres[index].scaling.set(distanceFromCamera, distanceFromCamera, distanceFromCamera);
  97204. }
  97205. else {
  97206. rotateSpheres[index].scaling.set(this.rotationSphereSize, this.rotationSphereSize, this.rotationSphereSize);
  97207. }
  97208. }
  97209. }
  97210. }
  97211. // Update scale box locations
  97212. var scaleBoxes = this._scaleBoxesParent.getChildMeshes();
  97213. for (var i = 0; i < 2; i++) {
  97214. for (var j = 0; j < 2; j++) {
  97215. for (var k = 0; k < 2; k++) {
  97216. var index = ((i * 4) + (j * 2)) + k;
  97217. if (scaleBoxes[index]) {
  97218. scaleBoxes[index].position.set(this._boundingDimensions.x * i, this._boundingDimensions.y * j, this._boundingDimensions.z * k);
  97219. scaleBoxes[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  97220. if (this.fixedDragMeshScreenSize) {
  97221. this._rootMesh.computeWorldMatrix();
  97222. this._scaleBoxesParent.computeWorldMatrix();
  97223. scaleBoxes[index].computeWorldMatrix();
  97224. scaleBoxes[index].absolutePosition.subtractToRef(this.gizmoLayer.utilityLayerScene.activeCamera.position, this._tmpVector);
  97225. var distanceFromCamera = this.scaleBoxSize * this._tmpVector.length() / this.fixedDragMeshScreenSizeDistanceFactor;
  97226. scaleBoxes[index].scaling.set(distanceFromCamera, distanceFromCamera, distanceFromCamera);
  97227. }
  97228. else {
  97229. scaleBoxes[index].scaling.set(this.scaleBoxSize, this.scaleBoxSize, this.scaleBoxSize);
  97230. }
  97231. }
  97232. }
  97233. }
  97234. }
  97235. if (this.attachedMesh) {
  97236. this._existingMeshScale.copyFrom(this.attachedMesh.scaling);
  97237. BoundingBoxGizmo._RestorePivotPoint(this.attachedMesh);
  97238. }
  97239. };
  97240. /**
  97241. * Enables rotation on the specified axis and disables rotation on the others
  97242. * @param axis The list of axis that should be enabled (eg. "xy" or "xyz")
  97243. */
  97244. BoundingBoxGizmo.prototype.setEnabledRotationAxis = function (axis) {
  97245. this._rotateSpheresParent.getChildMeshes().forEach(function (m, i) {
  97246. if (i < 4) {
  97247. m.setEnabled(axis.indexOf("x") != -1);
  97248. }
  97249. else if (i < 8) {
  97250. m.setEnabled(axis.indexOf("y") != -1);
  97251. }
  97252. else {
  97253. m.setEnabled(axis.indexOf("z") != -1);
  97254. }
  97255. });
  97256. };
  97257. /**
  97258. * Disposes of the gizmo
  97259. */
  97260. BoundingBoxGizmo.prototype.dispose = function () {
  97261. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  97262. this.gizmoLayer.originalScene.onBeforeRenderObservable.remove(this._renderObserver);
  97263. this._lineBoundingBox.dispose();
  97264. this._rotateSpheresParent.dispose();
  97265. this._scaleBoxesParent.dispose();
  97266. _super.prototype.dispose.call(this);
  97267. };
  97268. /**
  97269. * Makes a mesh not pickable and wraps the mesh inside of a bounding box mesh that is pickable. (This is useful to avoid picking within complex geometry)
  97270. * @param mesh the mesh to wrap in the bounding box mesh and make not pickable
  97271. * @returns the bounding box mesh with the passed in mesh as a child
  97272. */
  97273. BoundingBoxGizmo.MakeNotPickableAndWrapInBoundingBox = function (mesh) {
  97274. var makeNotPickable = function (root) {
  97275. root.isPickable = false;
  97276. root.getChildMeshes().forEach(function (c) {
  97277. makeNotPickable(c);
  97278. });
  97279. };
  97280. makeNotPickable(mesh);
  97281. // Reset position to get boudning box from origin with no rotation
  97282. if (!mesh.rotationQuaternion) {
  97283. mesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(mesh.rotation.y, mesh.rotation.x, mesh.rotation.z);
  97284. }
  97285. var oldPos = mesh.position.clone();
  97286. var oldRot = mesh.rotationQuaternion.clone();
  97287. mesh.rotationQuaternion.set(0, 0, 0, 1);
  97288. mesh.position.set(0, 0, 0);
  97289. // Update bounding dimensions/positions
  97290. var box = BABYLON.MeshBuilder.CreateBox("box", { size: 1 }, mesh.getScene());
  97291. var boundingMinMax = mesh.getHierarchyBoundingVectors();
  97292. boundingMinMax.max.subtractToRef(boundingMinMax.min, box.scaling);
  97293. box.position.set((boundingMinMax.max.x + boundingMinMax.min.x) / 2, (boundingMinMax.max.y + boundingMinMax.min.y) / 2, (boundingMinMax.max.z + boundingMinMax.min.z) / 2);
  97294. // Restore original positions
  97295. mesh.addChild(box);
  97296. mesh.rotationQuaternion.copyFrom(oldRot);
  97297. mesh.position.copyFrom(oldPos);
  97298. // Reverse parenting
  97299. mesh.removeChild(box);
  97300. box.addChild(mesh);
  97301. box.visibility = 0;
  97302. return box;
  97303. };
  97304. /**
  97305. * CustomMeshes are not supported by this gizmo
  97306. * @param mesh The mesh to replace the default mesh of the gizmo
  97307. */
  97308. BoundingBoxGizmo.prototype.setCustomMesh = function (mesh) {
  97309. BABYLON.Tools.Error("Custom meshes are not supported on this gizmo");
  97310. };
  97311. // Stores the state of the pivot cache (_oldPivotPoint, _pivotTranslation)
  97312. // store/remove pivot point should only be applied during their outermost calls
  97313. BoundingBoxGizmo._PivotCached = 0;
  97314. BoundingBoxGizmo._OldPivotPoint = new BABYLON.Vector3();
  97315. BoundingBoxGizmo._PivotTranslation = new BABYLON.Vector3();
  97316. BoundingBoxGizmo._PivotTmpVector = new BABYLON.Vector3();
  97317. return BoundingBoxGizmo;
  97318. }(BABYLON.Gizmo));
  97319. BABYLON.BoundingBoxGizmo = BoundingBoxGizmo;
  97320. })(BABYLON || (BABYLON = {}));
  97321. //# sourceMappingURL=babylon.boundingBoxGizmo.js.map
  97322. var BABYLON;
  97323. (function (BABYLON) {
  97324. /**
  97325. * Helps setup gizmo's in the scene to rotate/scale/position meshes
  97326. */
  97327. var GizmoManager = /** @class */ (function () {
  97328. /**
  97329. * Instatiates a gizmo manager
  97330. * @param scene the scene to overlay the gizmos on top of
  97331. */
  97332. function GizmoManager(scene) {
  97333. var _this = this;
  97334. this.scene = scene;
  97335. this._gizmosEnabled = { positionGizmo: false, rotationGizmo: false, scaleGizmo: false, boundingBoxGizmo: false };
  97336. this._pointerObserver = null;
  97337. this._attachedMesh = null;
  97338. this._boundingBoxColor = BABYLON.Color3.FromHexString("#0984e3");
  97339. /**
  97340. * When bounding box gizmo is enabled, this can be used to track drag/end events
  97341. */
  97342. this.boundingBoxDragBehavior = new BABYLON.SixDofDragBehavior();
  97343. /**
  97344. * Array of meshes which will have the gizmo attached when a pointer selected them. If null, all meshes are attachable. (Default: null)
  97345. */
  97346. this.attachableMeshes = null;
  97347. /**
  97348. * If pointer events should perform attaching/detaching a gizmo, if false this can be done manually via attachToMesh. (Default: true)
  97349. */
  97350. this.usePointerToAttachGizmos = true;
  97351. this.gizmos = { positionGizmo: null, rotationGizmo: null, scaleGizmo: null, boundingBoxGizmo: null };
  97352. // Instatiate/dispose gizmos based on pointer actions
  97353. this._pointerObserver = scene.onPointerObservable.add(function (pointerInfo, state) {
  97354. if (!_this.usePointerToAttachGizmos) {
  97355. return;
  97356. }
  97357. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  97358. if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh) {
  97359. var node = pointerInfo.pickInfo.pickedMesh;
  97360. if (_this.attachableMeshes == null) {
  97361. // Attach to the most parent node
  97362. while (node && node.parent != null) {
  97363. node = node.parent;
  97364. }
  97365. }
  97366. else {
  97367. // Attach to the parent node that is an attachableMesh
  97368. var found = false;
  97369. _this.attachableMeshes.forEach(function (mesh) {
  97370. if (node && (node == mesh || node.isDescendantOf(mesh))) {
  97371. node = mesh;
  97372. found = true;
  97373. }
  97374. });
  97375. if (!found) {
  97376. node = null;
  97377. }
  97378. }
  97379. if (node instanceof BABYLON.AbstractMesh) {
  97380. _this.attachToMesh(node);
  97381. }
  97382. else {
  97383. _this.attachToMesh(null);
  97384. }
  97385. }
  97386. else {
  97387. _this.attachToMesh(null);
  97388. }
  97389. }
  97390. });
  97391. }
  97392. /**
  97393. * Attaches a set of gizmos to the specified mesh
  97394. * @param mesh The mesh the gizmo's should be attached to
  97395. */
  97396. GizmoManager.prototype.attachToMesh = function (mesh) {
  97397. if (this._attachedMesh) {
  97398. this._attachedMesh.removeBehavior(this.boundingBoxDragBehavior);
  97399. }
  97400. this._attachedMesh = mesh;
  97401. for (var key in this.gizmos) {
  97402. var gizmo = (this.gizmos[key]);
  97403. if (gizmo && this._gizmosEnabled[key]) {
  97404. gizmo.attachedMesh = mesh;
  97405. }
  97406. }
  97407. if (this.boundingBoxGizmoEnabled && this._attachedMesh) {
  97408. this._attachedMesh.addBehavior(this.boundingBoxDragBehavior);
  97409. }
  97410. };
  97411. Object.defineProperty(GizmoManager.prototype, "positionGizmoEnabled", {
  97412. get: function () {
  97413. return this._gizmosEnabled.positionGizmo;
  97414. },
  97415. /**
  97416. * If the position gizmo is enabled
  97417. */
  97418. set: function (value) {
  97419. if (value) {
  97420. if (!this.gizmos.positionGizmo) {
  97421. this.gizmos.positionGizmo = new BABYLON.PositionGizmo();
  97422. this.gizmos.positionGizmo.updateGizmoRotationToMatchAttachedMesh = false;
  97423. }
  97424. this.gizmos.positionGizmo.attachedMesh = this._attachedMesh;
  97425. }
  97426. else if (this.gizmos.positionGizmo) {
  97427. this.gizmos.positionGizmo.attachedMesh = null;
  97428. }
  97429. this._gizmosEnabled.positionGizmo = value;
  97430. },
  97431. enumerable: true,
  97432. configurable: true
  97433. });
  97434. Object.defineProperty(GizmoManager.prototype, "rotationGizmoEnabled", {
  97435. get: function () {
  97436. return this._gizmosEnabled.rotationGizmo;
  97437. },
  97438. /**
  97439. * If the rotation gizmo is enabled
  97440. */
  97441. set: function (value) {
  97442. if (value) {
  97443. if (!this.gizmos.rotationGizmo) {
  97444. this.gizmos.rotationGizmo = new BABYLON.RotationGizmo();
  97445. this.gizmos.rotationGizmo.updateGizmoRotationToMatchAttachedMesh = false;
  97446. }
  97447. this.gizmos.rotationGizmo.attachedMesh = this._attachedMesh;
  97448. }
  97449. else if (this.gizmos.rotationGizmo) {
  97450. this.gizmos.rotationGizmo.attachedMesh = null;
  97451. }
  97452. this._gizmosEnabled.rotationGizmo = value;
  97453. },
  97454. enumerable: true,
  97455. configurable: true
  97456. });
  97457. Object.defineProperty(GizmoManager.prototype, "scaleGizmoEnabled", {
  97458. get: function () {
  97459. return this._gizmosEnabled.scaleGizmo;
  97460. },
  97461. /**
  97462. * If the scale gizmo is enabled
  97463. */
  97464. set: function (value) {
  97465. if (value) {
  97466. this.gizmos.scaleGizmo = this.gizmos.scaleGizmo || new BABYLON.ScaleGizmo();
  97467. this.gizmos.scaleGizmo.attachedMesh = this._attachedMesh;
  97468. }
  97469. else if (this.gizmos.scaleGizmo) {
  97470. this.gizmos.scaleGizmo.attachedMesh = null;
  97471. }
  97472. this._gizmosEnabled.scaleGizmo = value;
  97473. },
  97474. enumerable: true,
  97475. configurable: true
  97476. });
  97477. Object.defineProperty(GizmoManager.prototype, "boundingBoxGizmoEnabled", {
  97478. get: function () {
  97479. return this._gizmosEnabled.boundingBoxGizmo;
  97480. },
  97481. /**
  97482. * If the boundingBox gizmo is enabled
  97483. */
  97484. set: function (value) {
  97485. if (value) {
  97486. this.gizmos.boundingBoxGizmo = this.gizmos.boundingBoxGizmo || new BABYLON.BoundingBoxGizmo(this._boundingBoxColor);
  97487. this.gizmos.boundingBoxGizmo.attachedMesh = this._attachedMesh;
  97488. if (this._attachedMesh) {
  97489. this._attachedMesh.removeBehavior(this.boundingBoxDragBehavior);
  97490. this._attachedMesh.addBehavior(this.boundingBoxDragBehavior);
  97491. }
  97492. }
  97493. else if (this.gizmos.boundingBoxGizmo) {
  97494. this.gizmos.boundingBoxGizmo.attachedMesh = null;
  97495. }
  97496. this._gizmosEnabled.boundingBoxGizmo = value;
  97497. },
  97498. enumerable: true,
  97499. configurable: true
  97500. });
  97501. /**
  97502. * Disposes of the gizmo manager
  97503. */
  97504. GizmoManager.prototype.dispose = function () {
  97505. this.scene.onPointerObservable.remove(this._pointerObserver);
  97506. for (var key in this.gizmos) {
  97507. var gizmo = (this.gizmos[key]);
  97508. if (gizmo) {
  97509. gizmo.dispose();
  97510. }
  97511. }
  97512. this.boundingBoxDragBehavior.detach();
  97513. };
  97514. return GizmoManager;
  97515. }());
  97516. BABYLON.GizmoManager = GizmoManager;
  97517. })(BABYLON || (BABYLON = {}));
  97518. //# sourceMappingURL=babylon.gizmoManager.js.map
  97519. var BABYLON;
  97520. (function (BABYLON) {
  97521. /**
  97522. * Defines a target to use with MorphTargetManager
  97523. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  97524. */
  97525. var MorphTarget = /** @class */ (function () {
  97526. /**
  97527. * Creates a new MorphTarget
  97528. * @param name defines the name of the target
  97529. * @param influence defines the influence to use
  97530. */
  97531. function MorphTarget(
  97532. /** defines the name of the target */
  97533. name, influence, scene) {
  97534. if (influence === void 0) { influence = 0; }
  97535. if (scene === void 0) { scene = null; }
  97536. this.name = name;
  97537. /**
  97538. * Gets or sets the list of animations
  97539. */
  97540. this.animations = new Array();
  97541. this._positions = null;
  97542. this._normals = null;
  97543. this._tangents = null;
  97544. /**
  97545. * Observable raised when the influence changes
  97546. */
  97547. this.onInfluenceChanged = new BABYLON.Observable();
  97548. this._animationPropertiesOverride = null;
  97549. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  97550. this.influence = influence;
  97551. }
  97552. Object.defineProperty(MorphTarget.prototype, "influence", {
  97553. /**
  97554. * Gets or sets the influence of this target (ie. its weight in the overall morphing)
  97555. */
  97556. get: function () {
  97557. return this._influence;
  97558. },
  97559. set: function (influence) {
  97560. if (this._influence === influence) {
  97561. return;
  97562. }
  97563. var previous = this._influence;
  97564. this._influence = influence;
  97565. if (this.onInfluenceChanged.hasObservers) {
  97566. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  97567. }
  97568. },
  97569. enumerable: true,
  97570. configurable: true
  97571. });
  97572. Object.defineProperty(MorphTarget.prototype, "animationPropertiesOverride", {
  97573. /**
  97574. * Gets or sets the animation properties override
  97575. */
  97576. get: function () {
  97577. if (!this._animationPropertiesOverride && this._scene) {
  97578. return this._scene.animationPropertiesOverride;
  97579. }
  97580. return this._animationPropertiesOverride;
  97581. },
  97582. set: function (value) {
  97583. this._animationPropertiesOverride = value;
  97584. },
  97585. enumerable: true,
  97586. configurable: true
  97587. });
  97588. Object.defineProperty(MorphTarget.prototype, "hasPositions", {
  97589. /**
  97590. * Gets a boolean defining if the target contains position data
  97591. */
  97592. get: function () {
  97593. return !!this._positions;
  97594. },
  97595. enumerable: true,
  97596. configurable: true
  97597. });
  97598. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  97599. /**
  97600. * Gets a boolean defining if the target contains normal data
  97601. */
  97602. get: function () {
  97603. return !!this._normals;
  97604. },
  97605. enumerable: true,
  97606. configurable: true
  97607. });
  97608. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  97609. /**
  97610. * Gets a boolean defining if the target contains tangent data
  97611. */
  97612. get: function () {
  97613. return !!this._tangents;
  97614. },
  97615. enumerable: true,
  97616. configurable: true
  97617. });
  97618. /**
  97619. * Affects position data to this target
  97620. * @param data defines the position data to use
  97621. */
  97622. MorphTarget.prototype.setPositions = function (data) {
  97623. this._positions = data;
  97624. };
  97625. /**
  97626. * Gets the position data stored in this target
  97627. * @returns a FloatArray containing the position data (or null if not present)
  97628. */
  97629. MorphTarget.prototype.getPositions = function () {
  97630. return this._positions;
  97631. };
  97632. /**
  97633. * Affects normal data to this target
  97634. * @param data defines the normal data to use
  97635. */
  97636. MorphTarget.prototype.setNormals = function (data) {
  97637. this._normals = data;
  97638. };
  97639. /**
  97640. * Gets the normal data stored in this target
  97641. * @returns a FloatArray containing the normal data (or null if not present)
  97642. */
  97643. MorphTarget.prototype.getNormals = function () {
  97644. return this._normals;
  97645. };
  97646. /**
  97647. * Affects tangent data to this target
  97648. * @param data defines the tangent data to use
  97649. */
  97650. MorphTarget.prototype.setTangents = function (data) {
  97651. this._tangents = data;
  97652. };
  97653. /**
  97654. * Gets the tangent data stored in this target
  97655. * @returns a FloatArray containing the tangent data (or null if not present)
  97656. */
  97657. MorphTarget.prototype.getTangents = function () {
  97658. return this._tangents;
  97659. };
  97660. /**
  97661. * Serializes the current target into a Serialization object
  97662. * @returns the serialized object
  97663. */
  97664. MorphTarget.prototype.serialize = function () {
  97665. var serializationObject = {};
  97666. serializationObject.name = this.name;
  97667. serializationObject.influence = this.influence;
  97668. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  97669. if (this.hasNormals) {
  97670. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  97671. }
  97672. if (this.hasTangents) {
  97673. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  97674. }
  97675. // Animations
  97676. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  97677. return serializationObject;
  97678. };
  97679. // Statics
  97680. /**
  97681. * Creates a new target from serialized data
  97682. * @param serializationObject defines the serialized data to use
  97683. * @returns a new MorphTarget
  97684. */
  97685. MorphTarget.Parse = function (serializationObject) {
  97686. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  97687. result.setPositions(serializationObject.positions);
  97688. if (serializationObject.normals) {
  97689. result.setNormals(serializationObject.normals);
  97690. }
  97691. if (serializationObject.tangents) {
  97692. result.setTangents(serializationObject.tangents);
  97693. }
  97694. // Animations
  97695. if (serializationObject.animations) {
  97696. for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {
  97697. var parsedAnimation = serializationObject.animations[animationIndex];
  97698. result.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  97699. }
  97700. }
  97701. return result;
  97702. };
  97703. /**
  97704. * Creates a MorphTarget from mesh data
  97705. * @param mesh defines the source mesh
  97706. * @param name defines the name to use for the new target
  97707. * @param influence defines the influence to attach to the target
  97708. * @returns a new MorphTarget
  97709. */
  97710. MorphTarget.FromMesh = function (mesh, name, influence) {
  97711. if (!name) {
  97712. name = mesh.name;
  97713. }
  97714. var result = new MorphTarget(name, influence, mesh.getScene());
  97715. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  97716. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  97717. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  97718. }
  97719. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  97720. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  97721. }
  97722. return result;
  97723. };
  97724. return MorphTarget;
  97725. }());
  97726. BABYLON.MorphTarget = MorphTarget;
  97727. })(BABYLON || (BABYLON = {}));
  97728. //# sourceMappingURL=babylon.morphTarget.js.map
  97729. var BABYLON;
  97730. (function (BABYLON) {
  97731. /**
  97732. * This class is used to deform meshes using morphing between different targets
  97733. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  97734. */
  97735. var MorphTargetManager = /** @class */ (function () {
  97736. /**
  97737. * Creates a new MorphTargetManager
  97738. * @param scene defines the current scene
  97739. */
  97740. function MorphTargetManager(scene) {
  97741. if (scene === void 0) { scene = null; }
  97742. this._targets = new Array();
  97743. this._targetObservable = new Array();
  97744. this._activeTargets = new BABYLON.SmartArray(16);
  97745. this._supportsNormals = false;
  97746. this._supportsTangents = false;
  97747. this._vertexCount = 0;
  97748. this._uniqueId = 0;
  97749. this._tempInfluences = new Array();
  97750. if (!scene) {
  97751. scene = BABYLON.Engine.LastCreatedScene;
  97752. }
  97753. this._scene = scene;
  97754. if (this._scene) {
  97755. this._scene.morphTargetManagers.push(this);
  97756. this._uniqueId = this._scene.getUniqueId();
  97757. }
  97758. }
  97759. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  97760. /**
  97761. * Gets the unique ID of this manager
  97762. */
  97763. get: function () {
  97764. return this._uniqueId;
  97765. },
  97766. enumerable: true,
  97767. configurable: true
  97768. });
  97769. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  97770. /**
  97771. * Gets the number of vertices handled by this manager
  97772. */
  97773. get: function () {
  97774. return this._vertexCount;
  97775. },
  97776. enumerable: true,
  97777. configurable: true
  97778. });
  97779. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  97780. /**
  97781. * Gets a boolean indicating if this manager supports morphing of normals
  97782. */
  97783. get: function () {
  97784. return this._supportsNormals;
  97785. },
  97786. enumerable: true,
  97787. configurable: true
  97788. });
  97789. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  97790. /**
  97791. * Gets a boolean indicating if this manager supports morphing of tangents
  97792. */
  97793. get: function () {
  97794. return this._supportsTangents;
  97795. },
  97796. enumerable: true,
  97797. configurable: true
  97798. });
  97799. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  97800. /**
  97801. * Gets the number of targets stored in this manager
  97802. */
  97803. get: function () {
  97804. return this._targets.length;
  97805. },
  97806. enumerable: true,
  97807. configurable: true
  97808. });
  97809. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  97810. /**
  97811. * Gets the number of influencers (ie. the number of targets with influences > 0)
  97812. */
  97813. get: function () {
  97814. return this._activeTargets.length;
  97815. },
  97816. enumerable: true,
  97817. configurable: true
  97818. });
  97819. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  97820. /**
  97821. * Gets the list of influences (one per target)
  97822. */
  97823. get: function () {
  97824. return this._influences;
  97825. },
  97826. enumerable: true,
  97827. configurable: true
  97828. });
  97829. /**
  97830. * Gets the active target at specified index. An active target is a target with an influence > 0
  97831. * @param index defines the index to check
  97832. * @returns the requested target
  97833. */
  97834. MorphTargetManager.prototype.getActiveTarget = function (index) {
  97835. return this._activeTargets.data[index];
  97836. };
  97837. /**
  97838. * Gets the target at specified index
  97839. * @param index defines the index to check
  97840. * @returns the requested target
  97841. */
  97842. MorphTargetManager.prototype.getTarget = function (index) {
  97843. return this._targets[index];
  97844. };
  97845. /**
  97846. * Add a new target to this manager
  97847. * @param target defines the target to add
  97848. */
  97849. MorphTargetManager.prototype.addTarget = function (target) {
  97850. var _this = this;
  97851. this._targets.push(target);
  97852. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  97853. _this._syncActiveTargets(needUpdate);
  97854. }));
  97855. this._syncActiveTargets(true);
  97856. };
  97857. /**
  97858. * Removes a target from the manager
  97859. * @param target defines the target to remove
  97860. */
  97861. MorphTargetManager.prototype.removeTarget = function (target) {
  97862. var index = this._targets.indexOf(target);
  97863. if (index >= 0) {
  97864. this._targets.splice(index, 1);
  97865. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  97866. this._syncActiveTargets(true);
  97867. }
  97868. };
  97869. /**
  97870. * Serializes the current manager into a Serialization object
  97871. * @returns the serialized object
  97872. */
  97873. MorphTargetManager.prototype.serialize = function () {
  97874. var serializationObject = {};
  97875. serializationObject.id = this.uniqueId;
  97876. serializationObject.targets = [];
  97877. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  97878. var target = _a[_i];
  97879. serializationObject.targets.push(target.serialize());
  97880. }
  97881. return serializationObject;
  97882. };
  97883. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  97884. var influenceCount = 0;
  97885. this._activeTargets.reset();
  97886. this._supportsNormals = true;
  97887. this._supportsTangents = true;
  97888. this._vertexCount = 0;
  97889. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  97890. var target = _a[_i];
  97891. this._activeTargets.push(target);
  97892. this._tempInfluences[influenceCount++] = target.influence;
  97893. var positions = target.getPositions();
  97894. if (positions) {
  97895. this._supportsNormals = this._supportsNormals && target.hasNormals;
  97896. this._supportsTangents = this._supportsTangents && target.hasTangents;
  97897. var vertexCount = positions.length / 3;
  97898. if (this._vertexCount === 0) {
  97899. this._vertexCount = vertexCount;
  97900. }
  97901. else if (this._vertexCount !== vertexCount) {
  97902. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  97903. return;
  97904. }
  97905. }
  97906. }
  97907. if (!this._influences || this._influences.length !== influenceCount) {
  97908. this._influences = new Float32Array(influenceCount);
  97909. }
  97910. for (var index = 0; index < influenceCount; index++) {
  97911. this._influences[index] = this._tempInfluences[index];
  97912. }
  97913. if (needUpdate) {
  97914. this.synchronize();
  97915. }
  97916. };
  97917. /**
  97918. * Syncrhonize the targets with all the meshes using this morph target manager
  97919. */
  97920. MorphTargetManager.prototype.synchronize = function () {
  97921. if (!this._scene) {
  97922. return;
  97923. }
  97924. // Flag meshes as dirty to resync with the active targets
  97925. for (var _i = 0, _a = this._scene.meshes; _i < _a.length; _i++) {
  97926. var mesh = _a[_i];
  97927. if (mesh.morphTargetManager === this) {
  97928. mesh._syncGeometryWithMorphTargetManager();
  97929. }
  97930. }
  97931. };
  97932. // Statics
  97933. /**
  97934. * Creates a new MorphTargetManager from serialized data
  97935. * @param serializationObject defines the serialized data
  97936. * @param scene defines the hosting scene
  97937. * @returns the new MorphTargetManager
  97938. */
  97939. MorphTargetManager.Parse = function (serializationObject, scene) {
  97940. var result = new MorphTargetManager(scene);
  97941. result._uniqueId = serializationObject.id;
  97942. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  97943. var targetData = _a[_i];
  97944. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  97945. }
  97946. return result;
  97947. };
  97948. return MorphTargetManager;
  97949. }());
  97950. BABYLON.MorphTargetManager = MorphTargetManager;
  97951. })(BABYLON || (BABYLON = {}));
  97952. //# sourceMappingURL=babylon.morphTargetManager.js.map
  97953. var BABYLON;
  97954. (function (BABYLON) {
  97955. var Octree = /** @class */ (function () {
  97956. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  97957. if (maxDepth === void 0) { maxDepth = 2; }
  97958. this.maxDepth = maxDepth;
  97959. this.dynamicContent = new Array();
  97960. this._maxBlockCapacity = maxBlockCapacity || 64;
  97961. this._selectionContent = new BABYLON.SmartArrayNoDuplicate(1024);
  97962. this._creationFunc = creationFunc;
  97963. }
  97964. // Methods
  97965. Octree.prototype.update = function (worldMin, worldMax, entries) {
  97966. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  97967. };
  97968. Octree.prototype.addMesh = function (entry) {
  97969. for (var index = 0; index < this.blocks.length; index++) {
  97970. var block = this.blocks[index];
  97971. block.addEntry(entry);
  97972. }
  97973. };
  97974. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  97975. this._selectionContent.reset();
  97976. for (var index = 0; index < this.blocks.length; index++) {
  97977. var block = this.blocks[index];
  97978. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  97979. }
  97980. if (allowDuplicate) {
  97981. this._selectionContent.concat(this.dynamicContent);
  97982. }
  97983. else {
  97984. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  97985. }
  97986. return this._selectionContent;
  97987. };
  97988. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  97989. this._selectionContent.reset();
  97990. for (var index = 0; index < this.blocks.length; index++) {
  97991. var block = this.blocks[index];
  97992. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  97993. }
  97994. if (allowDuplicate) {
  97995. this._selectionContent.concat(this.dynamicContent);
  97996. }
  97997. else {
  97998. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  97999. }
  98000. return this._selectionContent;
  98001. };
  98002. Octree.prototype.intersectsRay = function (ray) {
  98003. this._selectionContent.reset();
  98004. for (var index = 0; index < this.blocks.length; index++) {
  98005. var block = this.blocks[index];
  98006. block.intersectsRay(ray, this._selectionContent);
  98007. }
  98008. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  98009. return this._selectionContent;
  98010. };
  98011. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  98012. target.blocks = new Array();
  98013. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  98014. // Segmenting space
  98015. for (var x = 0; x < 2; x++) {
  98016. for (var y = 0; y < 2; y++) {
  98017. for (var z = 0; z < 2; z++) {
  98018. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  98019. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  98020. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  98021. block.addEntries(entries);
  98022. target.blocks.push(block);
  98023. }
  98024. }
  98025. }
  98026. };
  98027. Octree.CreationFuncForMeshes = function (entry, block) {
  98028. var boundingInfo = entry.getBoundingInfo();
  98029. if (!entry.isBlocked && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  98030. block.entries.push(entry);
  98031. }
  98032. };
  98033. Octree.CreationFuncForSubMeshes = function (entry, block) {
  98034. var boundingInfo = entry.getBoundingInfo();
  98035. if (boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  98036. block.entries.push(entry);
  98037. }
  98038. };
  98039. return Octree;
  98040. }());
  98041. BABYLON.Octree = Octree;
  98042. })(BABYLON || (BABYLON = {}));
  98043. //# sourceMappingURL=babylon.octree.js.map
  98044. var BABYLON;
  98045. (function (BABYLON) {
  98046. /**
  98047. * Class used to store a cell in an octree
  98048. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  98049. */
  98050. var OctreeBlock = /** @class */ (function () {
  98051. /**
  98052. * Creates a new block
  98053. * @param minPoint defines the minimum vector (in world space) of the block's bounding box
  98054. * @param maxPoint defines the maximum vector (in world space) of the block's bounding box
  98055. * @param capacity defines the maximum capacity of this block (if capacity is reached the block will be split into sub blocks)
  98056. * @param depth defines the current depth of this block in the octree
  98057. * @param maxDepth defines the maximal depth allowed (beyond this value, the capacity is ignored)
  98058. * @param creationFunc defines a callback to call when an element is added to the block
  98059. */
  98060. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  98061. /**
  98062. * Gets the content of the current block
  98063. */
  98064. this.entries = new Array();
  98065. this._boundingVectors = new Array();
  98066. this._capacity = capacity;
  98067. this._depth = depth;
  98068. this._maxDepth = maxDepth;
  98069. this._creationFunc = creationFunc;
  98070. this._minPoint = minPoint;
  98071. this._maxPoint = maxPoint;
  98072. this._boundingVectors.push(minPoint.clone());
  98073. this._boundingVectors.push(maxPoint.clone());
  98074. this._boundingVectors.push(minPoint.clone());
  98075. this._boundingVectors[2].x = maxPoint.x;
  98076. this._boundingVectors.push(minPoint.clone());
  98077. this._boundingVectors[3].y = maxPoint.y;
  98078. this._boundingVectors.push(minPoint.clone());
  98079. this._boundingVectors[4].z = maxPoint.z;
  98080. this._boundingVectors.push(maxPoint.clone());
  98081. this._boundingVectors[5].z = minPoint.z;
  98082. this._boundingVectors.push(maxPoint.clone());
  98083. this._boundingVectors[6].x = minPoint.x;
  98084. this._boundingVectors.push(maxPoint.clone());
  98085. this._boundingVectors[7].y = minPoint.y;
  98086. }
  98087. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  98088. // Property
  98089. /**
  98090. * Gets the maximum capacity of this block (if capacity is reached the block will be split into sub blocks)
  98091. */
  98092. get: function () {
  98093. return this._capacity;
  98094. },
  98095. enumerable: true,
  98096. configurable: true
  98097. });
  98098. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  98099. /**
  98100. * Gets the minimum vector (in world space) of the block's bounding box
  98101. */
  98102. get: function () {
  98103. return this._minPoint;
  98104. },
  98105. enumerable: true,
  98106. configurable: true
  98107. });
  98108. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  98109. /**
  98110. * Gets the maximum vector (in world space) of the block's bounding box
  98111. */
  98112. get: function () {
  98113. return this._maxPoint;
  98114. },
  98115. enumerable: true,
  98116. configurable: true
  98117. });
  98118. // Methods
  98119. /**
  98120. * Add a new element to this block
  98121. * @param entry defines the element to add
  98122. */
  98123. OctreeBlock.prototype.addEntry = function (entry) {
  98124. if (this.blocks) {
  98125. for (var index = 0; index < this.blocks.length; index++) {
  98126. var block = this.blocks[index];
  98127. block.addEntry(entry);
  98128. }
  98129. return;
  98130. }
  98131. this._creationFunc(entry, this);
  98132. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  98133. this.createInnerBlocks();
  98134. }
  98135. };
  98136. /**
  98137. * Add an array of elements to this block
  98138. * @param entries defines the array of elements to add
  98139. */
  98140. OctreeBlock.prototype.addEntries = function (entries) {
  98141. for (var index = 0; index < entries.length; index++) {
  98142. var mesh = entries[index];
  98143. this.addEntry(mesh);
  98144. }
  98145. };
  98146. /**
  98147. * Test if the current block intersects the furstum planes and if yes, then add its content to the selection array
  98148. * @param frustumPlanes defines the frustum planes to test
  98149. * @param selection defines the array to store current content if selection is positive
  98150. * @param allowDuplicate defines if the selection array can contains duplicated entries
  98151. */
  98152. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  98153. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  98154. if (this.blocks) {
  98155. for (var index = 0; index < this.blocks.length; index++) {
  98156. var block = this.blocks[index];
  98157. block.select(frustumPlanes, selection, allowDuplicate);
  98158. }
  98159. return;
  98160. }
  98161. if (allowDuplicate) {
  98162. selection.concat(this.entries);
  98163. }
  98164. else {
  98165. selection.concatWithNoDuplicate(this.entries);
  98166. }
  98167. }
  98168. };
  98169. /**
  98170. * Test if the current block intersect with the given bounding sphere and if yes, then add its content to the selection array
  98171. * @param sphereCenter defines the bounding sphere center
  98172. * @param sphereRadius defines the bounding sphere radius
  98173. * @param selection defines the array to store current content if selection is positive
  98174. * @param allowDuplicate defines if the selection array can contains duplicated entries
  98175. */
  98176. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  98177. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  98178. if (this.blocks) {
  98179. for (var index = 0; index < this.blocks.length; index++) {
  98180. var block = this.blocks[index];
  98181. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  98182. }
  98183. return;
  98184. }
  98185. if (allowDuplicate) {
  98186. selection.concat(this.entries);
  98187. }
  98188. else {
  98189. selection.concatWithNoDuplicate(this.entries);
  98190. }
  98191. }
  98192. };
  98193. /**
  98194. * Test if the current block intersect with the given ray and if yes, then add its content to the selection array
  98195. * @param ray defines the ray to test with
  98196. * @param selection defines the array to store current content if selection is positive
  98197. */
  98198. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  98199. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  98200. if (this.blocks) {
  98201. for (var index = 0; index < this.blocks.length; index++) {
  98202. var block = this.blocks[index];
  98203. block.intersectsRay(ray, selection);
  98204. }
  98205. return;
  98206. }
  98207. selection.concatWithNoDuplicate(this.entries);
  98208. }
  98209. };
  98210. /**
  98211. * Subdivide the content into child blocks (this block will then be empty)
  98212. */
  98213. OctreeBlock.prototype.createInnerBlocks = function () {
  98214. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  98215. };
  98216. return OctreeBlock;
  98217. }());
  98218. BABYLON.OctreeBlock = OctreeBlock;
  98219. })(BABYLON || (BABYLON = {}));
  98220. //# sourceMappingURL=babylon.octreeBlock.js.map
  98221. var BABYLON;
  98222. (function (BABYLON) {
  98223. BABYLON.Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  98224. if (maxCapacity === void 0) { maxCapacity = 64; }
  98225. if (maxDepth === void 0) { maxDepth = 2; }
  98226. var component = this._getComponent(BABYLON.SceneComponentConstants.NAME_OCTREE);
  98227. if (!component) {
  98228. component = new OctreeSceneComponent(this);
  98229. this._addComponent(component);
  98230. }
  98231. if (!this._selectionOctree) {
  98232. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  98233. }
  98234. var worldExtends = this.getWorldExtends();
  98235. // Update octree
  98236. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  98237. return this._selectionOctree;
  98238. };
  98239. Object.defineProperty(BABYLON.Scene.prototype, "selectionOctree", {
  98240. get: function () {
  98241. return this._selectionOctree;
  98242. },
  98243. enumerable: true,
  98244. configurable: true
  98245. });
  98246. /**
  98247. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  98248. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree
  98249. * @param maxCapacity defines the maximum size of each block (64 by default)
  98250. * @param maxDepth defines the maximum depth to use (no more than 2 levels by default)
  98251. * @returns the new octree
  98252. * @see https://www.babylonjs-playground.com/#NA4OQ#12
  98253. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  98254. */
  98255. BABYLON.AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  98256. if (maxCapacity === void 0) { maxCapacity = 64; }
  98257. if (maxDepth === void 0) { maxDepth = 2; }
  98258. var scene = this.getScene();
  98259. var component = scene._getComponent(BABYLON.SceneComponentConstants.NAME_OCTREE);
  98260. if (!component) {
  98261. component = new OctreeSceneComponent(scene);
  98262. scene._addComponent(component);
  98263. }
  98264. if (!this._submeshesOctree) {
  98265. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  98266. }
  98267. this.computeWorldMatrix(true);
  98268. var boundingInfo = this.getBoundingInfo();
  98269. // Update octree
  98270. var bbox = boundingInfo.boundingBox;
  98271. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  98272. return this._submeshesOctree;
  98273. };
  98274. /**
  98275. * Defines the octree scene component responsible to manage any octrees
  98276. * in a given scene.
  98277. */
  98278. var OctreeSceneComponent = /** @class */ (function () {
  98279. /**
  98280. * Creates a new instance of the component for the given scene
  98281. * @param scene Defines the scene to register the component in
  98282. */
  98283. function OctreeSceneComponent(scene) {
  98284. /**
  98285. * The component name helpfull to identify the component in the list of scene components.
  98286. */
  98287. this.name = BABYLON.SceneComponentConstants.NAME_OCTREE;
  98288. /**
  98289. * Indicates if the meshes have been checked to make sure they are isEnabled()
  98290. */
  98291. this.checksIsEnabled = true;
  98292. this._tempRay = new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(1, 1, 1));
  98293. this.scene = scene;
  98294. this.scene.getActiveMeshCandidates = this.getActiveMeshCandidates.bind(this);
  98295. this.scene.getActiveSubMeshCandidates = this.getActiveSubMeshCandidates.bind(this);
  98296. this.scene.getCollidingSubMeshCandidates = this.getCollidingSubMeshCandidates.bind(this);
  98297. this.scene.getIntersectingSubMeshCandidates = this.getIntersectingSubMeshCandidates.bind(this);
  98298. }
  98299. /**
  98300. * Registers the component in a given scene
  98301. */
  98302. OctreeSceneComponent.prototype.register = function () {
  98303. var _this = this;
  98304. this.scene.onMeshRemovedObservable.add(function (mesh) {
  98305. var sceneOctree = _this.scene.selectionOctree;
  98306. if (sceneOctree !== undefined && sceneOctree !== null) {
  98307. var index = sceneOctree.dynamicContent.indexOf(mesh);
  98308. if (index !== -1) {
  98309. sceneOctree.dynamicContent.splice(index, 1);
  98310. }
  98311. }
  98312. });
  98313. this.scene.onMeshImportedObservable.add(function (mesh) {
  98314. var sceneOctree = _this.scene.selectionOctree;
  98315. if (sceneOctree !== undefined && sceneOctree !== null) {
  98316. sceneOctree.addMesh(mesh);
  98317. }
  98318. });
  98319. };
  98320. /**
  98321. * Return the list of active meshes
  98322. * @returns the list of active meshes
  98323. */
  98324. OctreeSceneComponent.prototype.getActiveMeshCandidates = function () {
  98325. if (this.scene._selectionOctree) {
  98326. var selection = this.scene._selectionOctree.select(this.scene.frustumPlanes);
  98327. return selection;
  98328. }
  98329. return this.scene._getDefaultMeshCandidates();
  98330. };
  98331. /**
  98332. * Return the list of active sub meshes
  98333. * @param mesh The mesh to get the candidates sub meshes from
  98334. * @returns the list of active sub meshes
  98335. */
  98336. OctreeSceneComponent.prototype.getActiveSubMeshCandidates = function (mesh) {
  98337. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  98338. var intersections = mesh._submeshesOctree.select(this.scene.frustumPlanes);
  98339. return intersections;
  98340. }
  98341. return this.scene._getDefaultSubMeshCandidates(mesh);
  98342. };
  98343. /**
  98344. * Return the list of sub meshes intersecting with a given local ray
  98345. * @param mesh defines the mesh to find the submesh for
  98346. * @param localRay defines the ray in local space
  98347. * @returns the list of intersecting sub meshes
  98348. */
  98349. OctreeSceneComponent.prototype.getIntersectingSubMeshCandidates = function (mesh, localRay) {
  98350. if (mesh._submeshesOctree && mesh.useOctreeForPicking) {
  98351. BABYLON.Ray.TransformToRef(localRay, mesh.getWorldMatrix(), this._tempRay);
  98352. var intersections = mesh._submeshesOctree.intersectsRay(this._tempRay);
  98353. return intersections;
  98354. }
  98355. return this.scene._getDefaultSubMeshCandidates(mesh);
  98356. };
  98357. /**
  98358. * Return the list of sub meshes colliding with a collider
  98359. * @param mesh defines the mesh to find the submesh for
  98360. * @param collider defines the collider to evaluate the collision against
  98361. * @returns the list of colliding sub meshes
  98362. */
  98363. OctreeSceneComponent.prototype.getCollidingSubMeshCandidates = function (mesh, collider) {
  98364. if (mesh._submeshesOctree && mesh.useOctreeForCollisions) {
  98365. var radius = collider._velocityWorldLength + Math.max(collider._radius.x, collider._radius.y, collider._radius.z);
  98366. var intersections = mesh._submeshesOctree.intersects(collider._basePointWorld, radius);
  98367. return intersections;
  98368. }
  98369. return this.scene._getDefaultSubMeshCandidates(mesh);
  98370. };
  98371. /**
  98372. * Rebuilds the elements related to this component in case of
  98373. * context lost for instance.
  98374. */
  98375. OctreeSceneComponent.prototype.rebuild = function () {
  98376. // Nothing to do here.
  98377. };
  98378. /**
  98379. * Disposes the component and the associated ressources.
  98380. */
  98381. OctreeSceneComponent.prototype.dispose = function () {
  98382. // Nothing to do here.
  98383. };
  98384. return OctreeSceneComponent;
  98385. }());
  98386. BABYLON.OctreeSceneComponent = OctreeSceneComponent;
  98387. })(BABYLON || (BABYLON = {}));
  98388. //# sourceMappingURL=babylon.octreeSceneComponent.js.map
  98389. var BABYLON;
  98390. (function (BABYLON) {
  98391. /**
  98392. * Postprocess used to generate anaglyphic rendering
  98393. */
  98394. var AnaglyphPostProcess = /** @class */ (function (_super) {
  98395. __extends(AnaglyphPostProcess, _super);
  98396. /**
  98397. * Creates a new AnaglyphPostProcess
  98398. * @param name defines postprocess name
  98399. * @param options defines creation options or target ratio scale
  98400. * @param rigCameras defines cameras using this postprocess
  98401. * @param samplingMode defines required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  98402. * @param engine defines hosting engine
  98403. * @param reusable defines if the postprocess will be reused multiple times per frame
  98404. */
  98405. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  98406. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  98407. _this._passedProcess = rigCameras[0]._rigPostProcess;
  98408. _this.onApplyObservable.add(function (effect) {
  98409. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  98410. });
  98411. return _this;
  98412. }
  98413. return AnaglyphPostProcess;
  98414. }(BABYLON.PostProcess));
  98415. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  98416. })(BABYLON || (BABYLON = {}));
  98417. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  98418. var BABYLON;
  98419. (function (BABYLON) {
  98420. BABYLON.Node.AddNodeConstructor("AnaglyphArcRotateCamera", function (name, scene, options) {
  98421. return function () { return new AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  98422. });
  98423. /**
  98424. * Camera used to simulate anaglyphic rendering (based on ArcRotateCamera)
  98425. * @see http://doc.babylonjs.com/features/cameras#anaglyph-cameras
  98426. */
  98427. var AnaglyphArcRotateCamera = /** @class */ (function (_super) {
  98428. __extends(AnaglyphArcRotateCamera, _super);
  98429. /**
  98430. * Creates a new AnaglyphArcRotateCamera
  98431. * @param name defines camera name
  98432. * @param alpha defines alpha angle (in radians)
  98433. * @param beta defines beta angle (in radians)
  98434. * @param radius defines radius
  98435. * @param target defines camera target
  98436. * @param interaxialDistance defines distance between each color axis
  98437. * @param scene defines the hosting scene
  98438. */
  98439. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  98440. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  98441. _this.interaxialDistance = interaxialDistance;
  98442. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  98443. return _this;
  98444. }
  98445. /**
  98446. * Gets camera class name
  98447. * @returns AnaglyphArcRotateCamera
  98448. */
  98449. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  98450. return "AnaglyphArcRotateCamera";
  98451. };
  98452. return AnaglyphArcRotateCamera;
  98453. }(BABYLON.ArcRotateCamera));
  98454. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  98455. })(BABYLON || (BABYLON = {}));
  98456. //# sourceMappingURL=babylon.anaglyphArcRotateCamera.js.map
  98457. var BABYLON;
  98458. (function (BABYLON) {
  98459. BABYLON.Node.AddNodeConstructor("AnaglyphFreeCamera", function (name, scene, options) {
  98460. return function () { return new AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  98461. });
  98462. /**
  98463. * Camera used to simulate anaglyphic rendering (based on FreeCamera)
  98464. * @see http://doc.babylonjs.com/features/cameras#anaglyph-cameras
  98465. */
  98466. var AnaglyphFreeCamera = /** @class */ (function (_super) {
  98467. __extends(AnaglyphFreeCamera, _super);
  98468. /**
  98469. * Creates a new AnaglyphFreeCamera
  98470. * @param name defines camera name
  98471. * @param position defines initial position
  98472. * @param interaxialDistance defines distance between each color axis
  98473. * @param scene defines the hosting scene
  98474. */
  98475. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  98476. var _this = _super.call(this, name, position, scene) || this;
  98477. _this.interaxialDistance = interaxialDistance;
  98478. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  98479. return _this;
  98480. }
  98481. /**
  98482. * Gets camera class name
  98483. * @returns AnaglyphFreeCamera
  98484. */
  98485. AnaglyphFreeCamera.prototype.getClassName = function () {
  98486. return "AnaglyphFreeCamera";
  98487. };
  98488. return AnaglyphFreeCamera;
  98489. }(BABYLON.FreeCamera));
  98490. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  98491. })(BABYLON || (BABYLON = {}));
  98492. //# sourceMappingURL=babylon.anaglyphFreeCamera.js.map
  98493. var BABYLON;
  98494. (function (BABYLON) {
  98495. BABYLON.Node.AddNodeConstructor("AnaglyphGamepadCamera", function (name, scene, options) {
  98496. return function () { return new AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  98497. });
  98498. /**
  98499. * Camera used to simulate anaglyphic rendering (based on GamepadCamera)
  98500. * @see http://doc.babylonjs.com/features/cameras#anaglyph-cameras
  98501. */
  98502. var AnaglyphGamepadCamera = /** @class */ (function (_super) {
  98503. __extends(AnaglyphGamepadCamera, _super);
  98504. /**
  98505. * Creates a new AnaglyphGamepadCamera
  98506. * @param name defines camera name
  98507. * @param position defines initial position
  98508. * @param interaxialDistance defines distance between each color axis
  98509. * @param scene defines the hosting scene
  98510. */
  98511. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  98512. var _this = _super.call(this, name, position, scene) || this;
  98513. _this.interaxialDistance = interaxialDistance;
  98514. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  98515. return _this;
  98516. }
  98517. /**
  98518. * Gets camera class name
  98519. * @returns AnaglyphGamepadCamera
  98520. */
  98521. AnaglyphGamepadCamera.prototype.getClassName = function () {
  98522. return "AnaglyphGamepadCamera";
  98523. };
  98524. return AnaglyphGamepadCamera;
  98525. }(BABYLON.GamepadCamera));
  98526. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  98527. })(BABYLON || (BABYLON = {}));
  98528. //# sourceMappingURL=babylon.anaglyphGamepadCamera.js.map
  98529. var BABYLON;
  98530. (function (BABYLON) {
  98531. BABYLON.Node.AddNodeConstructor("AnaglyphUniversalCamera", function (name, scene, options) {
  98532. return function () { return new AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  98533. });
  98534. /**
  98535. * Camera used to simulate anaglyphic rendering (based on UniversalCamera)
  98536. * @see http://doc.babylonjs.com/features/cameras#anaglyph-cameras
  98537. */
  98538. var AnaglyphUniversalCamera = /** @class */ (function (_super) {
  98539. __extends(AnaglyphUniversalCamera, _super);
  98540. /**
  98541. * Creates a new AnaglyphUniversalCamera
  98542. * @param name defines camera name
  98543. * @param position defines initial position
  98544. * @param interaxialDistance defines distance between each color axis
  98545. * @param scene defines the hosting scene
  98546. */
  98547. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  98548. var _this = _super.call(this, name, position, scene) || this;
  98549. _this.interaxialDistance = interaxialDistance;
  98550. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  98551. return _this;
  98552. }
  98553. /**
  98554. * Gets camera class name
  98555. * @returns AnaglyphUniversalCamera
  98556. */
  98557. AnaglyphUniversalCamera.prototype.getClassName = function () {
  98558. return "AnaglyphUniversalCamera";
  98559. };
  98560. return AnaglyphUniversalCamera;
  98561. }(BABYLON.UniversalCamera));
  98562. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  98563. })(BABYLON || (BABYLON = {}));
  98564. //# sourceMappingURL=babylon.anaglyphUniversalCamera.js.map
  98565. var BABYLON;
  98566. (function (BABYLON) {
  98567. var StereoscopicInterlacePostProcess = /** @class */ (function (_super) {
  98568. __extends(StereoscopicInterlacePostProcess, _super);
  98569. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  98570. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  98571. _this._passedProcess = rigCameras[0]._rigPostProcess;
  98572. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  98573. _this.onSizeChangedObservable.add(function () {
  98574. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  98575. });
  98576. _this.onApplyObservable.add(function (effect) {
  98577. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  98578. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  98579. });
  98580. return _this;
  98581. }
  98582. return StereoscopicInterlacePostProcess;
  98583. }(BABYLON.PostProcess));
  98584. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  98585. })(BABYLON || (BABYLON = {}));
  98586. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  98587. var BABYLON;
  98588. (function (BABYLON) {
  98589. BABYLON.Node.AddNodeConstructor("StereoscopicArcRotateCamera", function (name, scene, options) {
  98590. return function () { return new StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };
  98591. });
  98592. /**
  98593. * Camera used to simulate stereoscopic rendering (based on ArcRotateCamera)
  98594. * @see http://doc.babylonjs.com/features/cameras
  98595. */
  98596. var StereoscopicArcRotateCamera = /** @class */ (function (_super) {
  98597. __extends(StereoscopicArcRotateCamera, _super);
  98598. /**
  98599. * Creates a new StereoscopicArcRotateCamera
  98600. * @param name defines camera name
  98601. * @param alpha defines alpha angle (in radians)
  98602. * @param beta defines beta angle (in radians)
  98603. * @param radius defines radius
  98604. * @param target defines camera target
  98605. * @param interaxialDistance defines distance between each color axis
  98606. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  98607. * @param scene defines the hosting scene
  98608. */
  98609. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  98610. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  98611. _this.interaxialDistance = interaxialDistance;
  98612. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  98613. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  98614. return _this;
  98615. }
  98616. /**
  98617. * Gets camera class name
  98618. * @returns StereoscopicArcRotateCamera
  98619. */
  98620. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  98621. return "StereoscopicArcRotateCamera";
  98622. };
  98623. return StereoscopicArcRotateCamera;
  98624. }(BABYLON.ArcRotateCamera));
  98625. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  98626. })(BABYLON || (BABYLON = {}));
  98627. //# sourceMappingURL=babylon.stereoscopicArcRotateCamera.js.map
  98628. var BABYLON;
  98629. (function (BABYLON) {
  98630. BABYLON.Node.AddNodeConstructor("StereoscopicFreeCamera", function (name, scene, options) {
  98631. return function () { return new StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };
  98632. });
  98633. /**
  98634. * Camera used to simulate stereoscopic rendering (based on FreeCamera)
  98635. * @see http://doc.babylonjs.com/features/cameras
  98636. */
  98637. var StereoscopicFreeCamera = /** @class */ (function (_super) {
  98638. __extends(StereoscopicFreeCamera, _super);
  98639. /**
  98640. * Creates a new StereoscopicFreeCamera
  98641. * @param name defines camera name
  98642. * @param position defines initial position
  98643. * @param interaxialDistance defines distance between each color axis
  98644. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  98645. * @param scene defines the hosting scene
  98646. */
  98647. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  98648. var _this = _super.call(this, name, position, scene) || this;
  98649. _this.interaxialDistance = interaxialDistance;
  98650. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  98651. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  98652. return _this;
  98653. }
  98654. /**
  98655. * Gets camera class name
  98656. * @returns StereoscopicFreeCamera
  98657. */
  98658. StereoscopicFreeCamera.prototype.getClassName = function () {
  98659. return "StereoscopicFreeCamera";
  98660. };
  98661. return StereoscopicFreeCamera;
  98662. }(BABYLON.FreeCamera));
  98663. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  98664. })(BABYLON || (BABYLON = {}));
  98665. //# sourceMappingURL=babylon.stereoscopicFreeCamera.js.map
  98666. var BABYLON;
  98667. (function (BABYLON) {
  98668. BABYLON.Node.AddNodeConstructor("StereoscopicGamepadCamera", function (name, scene, options) {
  98669. return function () { return new StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };
  98670. });
  98671. /**
  98672. * Camera used to simulate stereoscopic rendering (based on GamepadCamera)
  98673. * @see http://doc.babylonjs.com/features/cameras
  98674. */
  98675. var StereoscopicGamepadCamera = /** @class */ (function (_super) {
  98676. __extends(StereoscopicGamepadCamera, _super);
  98677. /**
  98678. * Creates a new StereoscopicGamepadCamera
  98679. * @param name defines camera name
  98680. * @param position defines initial position
  98681. * @param interaxialDistance defines distance between each color axis
  98682. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  98683. * @param scene defines the hosting scene
  98684. */
  98685. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  98686. var _this = _super.call(this, name, position, scene) || this;
  98687. _this.interaxialDistance = interaxialDistance;
  98688. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  98689. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  98690. return _this;
  98691. }
  98692. /**
  98693. * Gets camera class name
  98694. * @returns StereoscopicGamepadCamera
  98695. */
  98696. StereoscopicGamepadCamera.prototype.getClassName = function () {
  98697. return "StereoscopicGamepadCamera";
  98698. };
  98699. return StereoscopicGamepadCamera;
  98700. }(BABYLON.GamepadCamera));
  98701. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  98702. })(BABYLON || (BABYLON = {}));
  98703. //# sourceMappingURL=babylon.stereoscopicGamepadCamera.js.map
  98704. var BABYLON;
  98705. (function (BABYLON) {
  98706. BABYLON.Node.AddNodeConstructor("StereoscopicFreeCamera", function (name, scene, options) {
  98707. return function () { return new StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };
  98708. });
  98709. /**
  98710. * Camera used to simulate stereoscopic rendering (based on UniversalCamera)
  98711. * @see http://doc.babylonjs.com/features/cameras
  98712. */
  98713. var StereoscopicUniversalCamera = /** @class */ (function (_super) {
  98714. __extends(StereoscopicUniversalCamera, _super);
  98715. /**
  98716. * Creates a new StereoscopicUniversalCamera
  98717. * @param name defines camera name
  98718. * @param position defines initial position
  98719. * @param interaxialDistance defines distance between each color axis
  98720. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  98721. * @param scene defines the hosting scene
  98722. */
  98723. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  98724. var _this = _super.call(this, name, position, scene) || this;
  98725. _this.interaxialDistance = interaxialDistance;
  98726. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  98727. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  98728. return _this;
  98729. }
  98730. /**
  98731. * Gets camera class name
  98732. * @returns StereoscopicUniversalCamera
  98733. */
  98734. StereoscopicUniversalCamera.prototype.getClassName = function () {
  98735. return "StereoscopicUniversalCamera";
  98736. };
  98737. return StereoscopicUniversalCamera;
  98738. }(BABYLON.UniversalCamera));
  98739. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  98740. })(BABYLON || (BABYLON = {}));
  98741. //# sourceMappingURL=babylon.stereoscopicUniversalCamera.js.map
  98742. var BABYLON;
  98743. (function (BABYLON) {
  98744. var VRDistortionCorrectionPostProcess = /** @class */ (function (_super) {
  98745. __extends(VRDistortionCorrectionPostProcess, _super);
  98746. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  98747. var _this = _super.call(this, name, "vrDistortionCorrection", [
  98748. 'LensCenter',
  98749. 'Scale',
  98750. 'ScaleIn',
  98751. 'HmdWarpParam'
  98752. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE) || this;
  98753. _this._isRightEye = isRightEye;
  98754. _this._distortionFactors = vrMetrics.distortionK;
  98755. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  98756. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  98757. _this.adaptScaleToCurrentViewport = true;
  98758. _this.onSizeChangedObservable.add(function () {
  98759. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  98760. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  98761. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  98762. });
  98763. _this.onApplyObservable.add(function (effect) {
  98764. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  98765. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  98766. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  98767. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  98768. });
  98769. return _this;
  98770. }
  98771. return VRDistortionCorrectionPostProcess;
  98772. }(BABYLON.PostProcess));
  98773. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  98774. })(BABYLON || (BABYLON = {}));
  98775. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  98776. var BABYLON;
  98777. (function (BABYLON) {
  98778. /**
  98779. * Takes information about the orientation of the device as reported by the deviceorientation event to orient the camera.
  98780. * Screen rotation is taken into account.
  98781. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  98782. */
  98783. var FreeCameraDeviceOrientationInput = /** @class */ (function () {
  98784. /**
  98785. * Instantiates a new input
  98786. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  98787. */
  98788. function FreeCameraDeviceOrientationInput() {
  98789. var _this = this;
  98790. this._screenOrientationAngle = 0;
  98791. this._screenQuaternion = new BABYLON.Quaternion();
  98792. this._alpha = 0;
  98793. this._beta = 0;
  98794. this._gamma = 0;
  98795. this._orientationChanged = function () {
  98796. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  98797. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  98798. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  98799. };
  98800. this._deviceOrientation = function (evt) {
  98801. _this._alpha = evt.alpha !== null ? evt.alpha : 0;
  98802. _this._beta = evt.beta !== null ? evt.beta : 0;
  98803. _this._gamma = evt.gamma !== null ? evt.gamma : 0;
  98804. };
  98805. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  98806. this._orientationChanged();
  98807. }
  98808. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  98809. /**
  98810. * Define the camera controlled by the input.
  98811. */
  98812. get: function () {
  98813. return this._camera;
  98814. },
  98815. set: function (camera) {
  98816. this._camera = camera;
  98817. if (this._camera != null && !this._camera.rotationQuaternion) {
  98818. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  98819. }
  98820. },
  98821. enumerable: true,
  98822. configurable: true
  98823. });
  98824. /**
  98825. * Attach the input controls to a specific dom element to get the input from.
  98826. * @param element Defines the element the controls should be listened from
  98827. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  98828. */
  98829. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  98830. window.addEventListener("orientationchange", this._orientationChanged);
  98831. window.addEventListener("deviceorientation", this._deviceOrientation);
  98832. //In certain cases, the attach control is called AFTER orientation was changed,
  98833. //So this is needed.
  98834. this._orientationChanged();
  98835. };
  98836. /**
  98837. * Detach the current controls from the specified dom element.
  98838. * @param element Defines the element to stop listening the inputs from
  98839. */
  98840. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  98841. window.removeEventListener("orientationchange", this._orientationChanged);
  98842. window.removeEventListener("deviceorientation", this._deviceOrientation);
  98843. };
  98844. /**
  98845. * Update the current camera state depending on the inputs that have been used this frame.
  98846. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
  98847. */
  98848. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  98849. //if no device orientation provided, don't update the rotation.
  98850. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  98851. if (!this._alpha)
  98852. return;
  98853. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  98854. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  98855. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  98856. //Mirror on XY Plane
  98857. this._camera.rotationQuaternion.z *= -1;
  98858. this._camera.rotationQuaternion.w *= -1;
  98859. };
  98860. /**
  98861. * Gets the class name of the current intput.
  98862. * @returns the class name
  98863. */
  98864. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  98865. return "FreeCameraDeviceOrientationInput";
  98866. };
  98867. /**
  98868. * Get the friendly name associated with the input class.
  98869. * @returns the input friendly name
  98870. */
  98871. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  98872. return "deviceOrientation";
  98873. };
  98874. return FreeCameraDeviceOrientationInput;
  98875. }());
  98876. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  98877. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  98878. })(BABYLON || (BABYLON = {}));
  98879. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  98880. var BABYLON;
  98881. (function (BABYLON) {
  98882. /**
  98883. * Manage the device orientation inputs (gyroscope) to control an arc rotate camera.
  98884. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  98885. */
  98886. var ArcRotateCameraVRDeviceOrientationInput = /** @class */ (function () {
  98887. /**
  98888. * Instantiate a new ArcRotateCameraVRDeviceOrientationInput.
  98889. */
  98890. function ArcRotateCameraVRDeviceOrientationInput() {
  98891. /**
  98892. * Defines a correction factor applied on the alpha value retrieved from the orientation events.
  98893. */
  98894. this.alphaCorrection = 1;
  98895. /**
  98896. * Defines a correction factor applied on the beta value retrieved from the orientation events.
  98897. */
  98898. this.betaCorrection = 1;
  98899. /**
  98900. * Defines a correction factor applied on the gamma value retrieved from the orientation events.
  98901. */
  98902. this.gammaCorrection = 1;
  98903. this._alpha = 0;
  98904. this._gamma = 0;
  98905. this._dirty = false;
  98906. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  98907. }
  98908. /**
  98909. * Attach the input controls to a specific dom element to get the input from.
  98910. * @param element Defines the element the controls should be listened from
  98911. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  98912. */
  98913. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  98914. this.camera.attachControl(element, noPreventDefault);
  98915. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  98916. };
  98917. /** @hidden */
  98918. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  98919. if (evt.alpha !== null) {
  98920. this._alpha = +evt.alpha | 0;
  98921. }
  98922. if (evt.gamma !== null) {
  98923. this._gamma = +evt.gamma | 0;
  98924. }
  98925. this._dirty = true;
  98926. };
  98927. /**
  98928. * Update the current camera state depending on the inputs that have been used this frame.
  98929. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
  98930. */
  98931. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  98932. if (this._dirty) {
  98933. this._dirty = false;
  98934. if (this._gamma < 0) {
  98935. this._gamma = 180 + this._gamma;
  98936. }
  98937. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  98938. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  98939. }
  98940. };
  98941. /**
  98942. * Detach the current controls from the specified dom element.
  98943. * @param element Defines the element to stop listening the inputs from
  98944. */
  98945. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  98946. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  98947. };
  98948. /**
  98949. * Gets the class name of the current intput.
  98950. * @returns the class name
  98951. */
  98952. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  98953. return "ArcRotateCameraVRDeviceOrientationInput";
  98954. };
  98955. /**
  98956. * Get the friendly name associated with the input class.
  98957. * @returns the input friendly name
  98958. */
  98959. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  98960. return "VRDeviceOrientation";
  98961. };
  98962. return ArcRotateCameraVRDeviceOrientationInput;
  98963. }());
  98964. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  98965. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  98966. })(BABYLON || (BABYLON = {}));
  98967. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  98968. var BABYLON;
  98969. (function (BABYLON) {
  98970. /**
  98971. * This represents all the required metrics to create a VR camera.
  98972. * @see http://doc.babylonjs.com/babylon101/cameras#device-orientation-camera
  98973. */
  98974. var VRCameraMetrics = /** @class */ (function () {
  98975. function VRCameraMetrics() {
  98976. /**
  98977. * Define if the current vr camera should compensate the distortion of the lense or not.
  98978. */
  98979. this.compensateDistortion = true;
  98980. }
  98981. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  98982. /**
  98983. * Gets the rendering aspect ratio based on the provided resolutions.
  98984. */
  98985. get: function () {
  98986. return this.hResolution / (2 * this.vResolution);
  98987. },
  98988. enumerable: true,
  98989. configurable: true
  98990. });
  98991. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  98992. /**
  98993. * Gets the aspect ratio based on the FOV, scale factors, and real screen sizes.
  98994. */
  98995. get: function () {
  98996. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  98997. },
  98998. enumerable: true,
  98999. configurable: true
  99000. });
  99001. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  99002. /**
  99003. * @hidden
  99004. */
  99005. get: function () {
  99006. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  99007. var h = (4 * meters) / this.hScreenSize;
  99008. return BABYLON.Matrix.Translation(h, 0, 0);
  99009. },
  99010. enumerable: true,
  99011. configurable: true
  99012. });
  99013. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  99014. /**
  99015. * @hidden
  99016. */
  99017. get: function () {
  99018. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  99019. var h = (4 * meters) / this.hScreenSize;
  99020. return BABYLON.Matrix.Translation(-h, 0, 0);
  99021. },
  99022. enumerable: true,
  99023. configurable: true
  99024. });
  99025. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  99026. /**
  99027. * @hidden
  99028. */
  99029. get: function () {
  99030. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  99031. },
  99032. enumerable: true,
  99033. configurable: true
  99034. });
  99035. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  99036. /**
  99037. * @hidden
  99038. */
  99039. get: function () {
  99040. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  99041. },
  99042. enumerable: true,
  99043. configurable: true
  99044. });
  99045. /**
  99046. * Get the default VRMetrics based on the most generic setup.
  99047. * @returns the default vr metrics
  99048. */
  99049. VRCameraMetrics.GetDefault = function () {
  99050. var result = new VRCameraMetrics();
  99051. result.hResolution = 1280;
  99052. result.vResolution = 800;
  99053. result.hScreenSize = 0.149759993;
  99054. result.vScreenSize = 0.0935999975;
  99055. result.vScreenCenter = 0.0467999987;
  99056. result.eyeToScreenDistance = 0.0410000011;
  99057. result.lensSeparationDistance = 0.0635000020;
  99058. result.interpupillaryDistance = 0.0640000030;
  99059. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  99060. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  99061. result.postProcessScaleFactor = 1.714605507808412;
  99062. result.lensCenterOffset = 0.151976421;
  99063. return result;
  99064. };
  99065. return VRCameraMetrics;
  99066. }());
  99067. BABYLON.VRCameraMetrics = VRCameraMetrics;
  99068. })(BABYLON || (BABYLON = {}));
  99069. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  99070. var BABYLON;
  99071. (function (BABYLON) {
  99072. BABYLON.Node.AddNodeConstructor("WebVRFreeCamera", function (name, scene) {
  99073. return function () { return new WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  99074. });
  99075. BABYLON.Node.AddNodeConstructor("WebVRGamepadCamera", function (name, scene) {
  99076. return function () { return new WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  99077. });
  99078. /**
  99079. * This represents a WebVR camera.
  99080. * The WebVR camera is Babylon's simple interface to interaction with Windows Mixed Reality, HTC Vive and Oculus Rift.
  99081. * @example http://doc.babylonjs.com/how_to/webvr_camera
  99082. */
  99083. var WebVRFreeCamera = /** @class */ (function (_super) {
  99084. __extends(WebVRFreeCamera, _super);
  99085. /**
  99086. * Instantiates a WebVRFreeCamera.
  99087. * @param name The name of the WebVRFreeCamera
  99088. * @param position The starting anchor position for the camera
  99089. * @param scene The scene the camera belongs to
  99090. * @param webVROptions a set of customizable options for the webVRCamera
  99091. */
  99092. function WebVRFreeCamera(name, position, scene, webVROptions) {
  99093. if (webVROptions === void 0) { webVROptions = {}; }
  99094. var _this = _super.call(this, name, position, scene) || this;
  99095. _this.webVROptions = webVROptions;
  99096. /**
  99097. * @hidden
  99098. * The vrDisplay tied to the camera. See https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay
  99099. */
  99100. _this._vrDevice = null;
  99101. /**
  99102. * The rawPose of the vrDevice.
  99103. */
  99104. _this.rawPose = null;
  99105. _this._specsVersion = "1.1";
  99106. _this._attached = false;
  99107. _this._descendants = [];
  99108. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  99109. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  99110. /** @hidden */
  99111. _this._deviceRoomRotationQuaternion = BABYLON.Quaternion.Identity();
  99112. _this._standingMatrix = null;
  99113. /**
  99114. * Represents device position in babylon space.
  99115. */
  99116. _this.devicePosition = BABYLON.Vector3.Zero();
  99117. /**
  99118. * Represents device rotation in babylon space.
  99119. */
  99120. _this.deviceRotationQuaternion = BABYLON.Quaternion.Identity();
  99121. /**
  99122. * The scale of the device to be used when translating from device space to babylon space.
  99123. */
  99124. _this.deviceScaleFactor = 1;
  99125. _this._deviceToWorld = BABYLON.Matrix.Identity();
  99126. _this._worldToDevice = BABYLON.Matrix.Identity();
  99127. /**
  99128. * References to the webVR controllers for the vrDevice.
  99129. */
  99130. _this.controllers = [];
  99131. /**
  99132. * Emits an event when a controller is attached.
  99133. */
  99134. _this.onControllersAttachedObservable = new BABYLON.Observable();
  99135. /**
  99136. * Emits an event when a controller's mesh has been loaded;
  99137. */
  99138. _this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  99139. /**
  99140. * Emits an event when the HMD's pose has been updated.
  99141. */
  99142. _this.onPoseUpdatedFromDeviceObservable = new BABYLON.Observable();
  99143. _this._poseSet = false;
  99144. /**
  99145. * If the rig cameras be used as parent instead of this camera.
  99146. */
  99147. _this.rigParenting = true;
  99148. _this._defaultHeight = undefined;
  99149. _this._htmlElementAttached = null;
  99150. _this._detachIfAttached = function () {
  99151. var vrDisplay = _this.getEngine().getVRDevice();
  99152. if (vrDisplay && !vrDisplay.isPresenting && _this._htmlElementAttached) {
  99153. _this.detachControl(_this._htmlElementAttached);
  99154. }
  99155. };
  99156. _this._workingVector = BABYLON.Vector3.Zero();
  99157. _this._oneVector = BABYLON.Vector3.One();
  99158. _this._workingMatrix = BABYLON.Matrix.Identity();
  99159. _this._tmpMatrix = new BABYLON.Matrix();
  99160. _this._cache.position = BABYLON.Vector3.Zero();
  99161. if (webVROptions.defaultHeight) {
  99162. _this._defaultHeight = webVROptions.defaultHeight;
  99163. _this.position.y = _this._defaultHeight;
  99164. }
  99165. _this.minZ = 0.1;
  99166. //legacy support - the compensation boolean was removed.
  99167. if (arguments.length === 5) {
  99168. _this.webVROptions = arguments[4];
  99169. }
  99170. // default webVR options
  99171. if (_this.webVROptions.trackPosition == undefined) {
  99172. _this.webVROptions.trackPosition = true;
  99173. }
  99174. if (_this.webVROptions.controllerMeshes == undefined) {
  99175. _this.webVROptions.controllerMeshes = true;
  99176. }
  99177. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  99178. _this.webVROptions.defaultLightingOnControllers = true;
  99179. }
  99180. _this.rotationQuaternion = new BABYLON.Quaternion();
  99181. if (_this.webVROptions && _this.webVROptions.positionScale) {
  99182. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  99183. }
  99184. //enable VR
  99185. var engine = _this.getEngine();
  99186. _this._onVREnabled = function (success) { if (success) {
  99187. _this.initControllers();
  99188. } };
  99189. engine.onVRRequestPresentComplete.add(_this._onVREnabled);
  99190. engine.initWebVR().add(function (event) {
  99191. if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) {
  99192. return;
  99193. }
  99194. _this._vrDevice = event.vrDisplay;
  99195. //reset the rig parameters.
  99196. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  99197. if (_this._attached) {
  99198. _this.getEngine().enableVR();
  99199. }
  99200. });
  99201. if (typeof (VRFrameData) !== "undefined")
  99202. _this._frameData = new VRFrameData();
  99203. /**
  99204. * The idea behind the following lines:
  99205. * objects that have the camera as parent should actually have the rig cameras as a parent.
  99206. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  99207. * the second will not show it correctly.
  99208. *
  99209. * To solve this - each object that has the camera as parent will be added to a protected array.
  99210. * When the rig camera renders, it will take this array and set all of those to be its children.
  99211. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  99212. * Amazing!
  99213. */
  99214. scene.onBeforeCameraRenderObservable.add(function (camera) {
  99215. if (camera.parent === _this && _this.rigParenting) {
  99216. _this._descendants = _this.getDescendants(true, function (n) {
  99217. // don't take the cameras or the controllers!
  99218. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  99219. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  99220. return !isController && !isRigCamera;
  99221. });
  99222. _this._descendants.forEach(function (node) {
  99223. node.parent = camera;
  99224. });
  99225. }
  99226. });
  99227. scene.onAfterCameraRenderObservable.add(function (camera) {
  99228. if (camera.parent === _this && _this.rigParenting) {
  99229. _this._descendants.forEach(function (node) {
  99230. node.parent = _this;
  99231. });
  99232. }
  99233. });
  99234. return _this;
  99235. }
  99236. /**
  99237. * Gets the device distance from the ground in meters.
  99238. * @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.
  99239. */
  99240. WebVRFreeCamera.prototype.deviceDistanceToRoomGround = function () {
  99241. if (this._standingMatrix) {
  99242. // Add standing matrix offset to get real offset from ground in room
  99243. this._standingMatrix.getTranslationToRef(this._workingVector);
  99244. return this._deviceRoomPosition.y + this._workingVector.y;
  99245. }
  99246. //If VRDisplay does not inform stage parameters and no default height is set we fallback to zero.
  99247. return this._defaultHeight || 0;
  99248. };
  99249. /**
  99250. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  99251. * @param callback will be called when the standing matrix is set. Callback parameter is if the standing matrix is supported.
  99252. */
  99253. WebVRFreeCamera.prototype.useStandingMatrix = function (callback) {
  99254. var _this = this;
  99255. if (callback === void 0) { callback = function (bool) { }; }
  99256. // Use standing matrix if available
  99257. this.getEngine().initWebVRAsync().then(function (result) {
  99258. if (!result.vrDisplay || !result.vrDisplay.stageParameters || !result.vrDisplay.stageParameters.sittingToStandingTransform || !_this.webVROptions.trackPosition) {
  99259. callback(false);
  99260. }
  99261. else {
  99262. _this._standingMatrix = new BABYLON.Matrix();
  99263. BABYLON.Matrix.FromFloat32ArrayToRefScaled(result.vrDisplay.stageParameters.sittingToStandingTransform, 0, 1, _this._standingMatrix);
  99264. if (!_this.getScene().useRightHandedSystem) {
  99265. [2, 6, 8, 9, 14].forEach(function (num) {
  99266. if (_this._standingMatrix) {
  99267. _this._standingMatrix.m[num] *= -1;
  99268. }
  99269. });
  99270. }
  99271. callback(true);
  99272. }
  99273. });
  99274. };
  99275. /**
  99276. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  99277. * @returns A promise with a boolean set to if the standing matrix is supported.
  99278. */
  99279. WebVRFreeCamera.prototype.useStandingMatrixAsync = function () {
  99280. var _this = this;
  99281. return new Promise(function (res, rej) {
  99282. _this.useStandingMatrix(function (supported) {
  99283. res(supported);
  99284. });
  99285. });
  99286. };
  99287. /**
  99288. * Disposes the camera
  99289. */
  99290. WebVRFreeCamera.prototype.dispose = function () {
  99291. this._detachIfAttached();
  99292. this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);
  99293. if (this._updateCacheWhenTrackingDisabledObserver) {
  99294. this._scene.onBeforeRenderObservable.remove(this._updateCacheWhenTrackingDisabledObserver);
  99295. }
  99296. _super.prototype.dispose.call(this);
  99297. };
  99298. /**
  99299. * Gets a vrController by name.
  99300. * @param name The name of the controller to retreive
  99301. * @returns the controller matching the name specified or null if not found
  99302. */
  99303. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  99304. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  99305. var gp = _a[_i];
  99306. if (gp.hand === name) {
  99307. return gp;
  99308. }
  99309. }
  99310. return null;
  99311. };
  99312. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  99313. /**
  99314. * The controller corrisponding to the users left hand.
  99315. */
  99316. get: function () {
  99317. if (!this._leftController) {
  99318. this._leftController = this.getControllerByName("left");
  99319. }
  99320. return this._leftController;
  99321. },
  99322. enumerable: true,
  99323. configurable: true
  99324. });
  99325. ;
  99326. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  99327. /**
  99328. * The controller corrisponding to the users right hand.
  99329. */
  99330. get: function () {
  99331. if (!this._rightController) {
  99332. this._rightController = this.getControllerByName("right");
  99333. }
  99334. return this._rightController;
  99335. },
  99336. enumerable: true,
  99337. configurable: true
  99338. });
  99339. ;
  99340. /**
  99341. * Casts a ray forward from the vrCamera's gaze.
  99342. * @param length Length of the ray (default: 100)
  99343. * @returns the ray corrisponding to the gaze
  99344. */
  99345. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  99346. if (length === void 0) { length = 100; }
  99347. if (this.leftCamera) {
  99348. // Use left eye to avoid computation to compute center on every call
  99349. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.leftCamera.globalPosition); // Need the actual rendered camera
  99350. }
  99351. else {
  99352. return _super.prototype.getForwardRay.call(this, length);
  99353. }
  99354. };
  99355. /**
  99356. * @hidden
  99357. * Updates the camera based on device's frame data
  99358. */
  99359. WebVRFreeCamera.prototype._checkInputs = function () {
  99360. if (this._vrDevice && this._vrDevice.isPresenting) {
  99361. this._vrDevice.getFrameData(this._frameData);
  99362. this.updateFromDevice(this._frameData.pose);
  99363. }
  99364. _super.prototype._checkInputs.call(this);
  99365. };
  99366. /**
  99367. * Updates the poseControlled values based on the input device pose.
  99368. * @param poseData Pose coming from the device
  99369. */
  99370. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  99371. if (poseData && poseData.orientation) {
  99372. this.rawPose = poseData;
  99373. this._deviceRoomRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]);
  99374. if (this.getScene().useRightHandedSystem) {
  99375. this._deviceRoomRotationQuaternion.z *= -1;
  99376. this._deviceRoomRotationQuaternion.w *= -1;
  99377. }
  99378. if (this.webVROptions.trackPosition && this.rawPose.position) {
  99379. this._deviceRoomPosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  99380. if (this.getScene().useRightHandedSystem) {
  99381. this._deviceRoomPosition.z *= -1;
  99382. }
  99383. }
  99384. this._poseSet = true;
  99385. }
  99386. };
  99387. /**
  99388. * WebVR's attach control will start broadcasting frames to the device.
  99389. * Note that in certain browsers (chrome for example) this function must be called
  99390. * within a user-interaction callback. Example:
  99391. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  99392. *
  99393. * @param element html element to attach the vrDevice to
  99394. * @param noPreventDefault prevent the default html element operation when attaching the vrDevice
  99395. */
  99396. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  99397. _super.prototype.attachControl.call(this, element, noPreventDefault);
  99398. this._attached = true;
  99399. this._htmlElementAttached = element;
  99400. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  99401. if (this._vrDevice) {
  99402. this.getEngine().enableVR();
  99403. }
  99404. window.addEventListener('vrdisplaypresentchange', this._detachIfAttached);
  99405. };
  99406. /**
  99407. * Detaches the camera from the html element and disables VR
  99408. *
  99409. * @param element html element to detach from
  99410. */
  99411. WebVRFreeCamera.prototype.detachControl = function (element) {
  99412. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  99413. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  99414. _super.prototype.detachControl.call(this, element);
  99415. this._attached = false;
  99416. this.getEngine().disableVR();
  99417. window.removeEventListener('vrdisplaypresentchange', this._detachIfAttached);
  99418. };
  99419. /**
  99420. * @returns the name of this class
  99421. */
  99422. WebVRFreeCamera.prototype.getClassName = function () {
  99423. return "WebVRFreeCamera";
  99424. };
  99425. /**
  99426. * Calls resetPose on the vrDisplay
  99427. * See: https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay/resetPose
  99428. */
  99429. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  99430. //uses the vrDisplay's "resetPose()".
  99431. //pitch and roll won't be affected.
  99432. this._vrDevice.resetPose();
  99433. };
  99434. /**
  99435. * @hidden
  99436. * Updates the rig cameras (left and right eye)
  99437. */
  99438. WebVRFreeCamera.prototype._updateRigCameras = function () {
  99439. var camLeft = this._rigCameras[0];
  99440. var camRight = this._rigCameras[1];
  99441. camLeft.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  99442. camRight.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  99443. camLeft.position.copyFrom(this._deviceRoomPosition);
  99444. camRight.position.copyFrom(this._deviceRoomPosition);
  99445. };
  99446. // Remove translation from 6dof headset if trackposition is set to false
  99447. WebVRFreeCamera.prototype._correctPositionIfNotTrackPosition = function (matrix, isViewMatrix) {
  99448. if (isViewMatrix === void 0) { isViewMatrix = false; }
  99449. if (this.rawPose && this.rawPose.position && !this.webVROptions.trackPosition) {
  99450. BABYLON.Matrix.TranslationToRef(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2], this._tmpMatrix);
  99451. if (!isViewMatrix) {
  99452. this._tmpMatrix.invert();
  99453. }
  99454. this._tmpMatrix.multiplyToRef(matrix, matrix);
  99455. }
  99456. };
  99457. /**
  99458. * @hidden
  99459. * Updates the cached values of the camera
  99460. * @param ignoreParentClass ignores updating the parent class's cache (default: false)
  99461. */
  99462. WebVRFreeCamera.prototype._updateCache = function (ignoreParentClass) {
  99463. var _this = this;
  99464. if (!this.rotationQuaternion.equals(this._cache.rotationQuaternion) || !this.position.equals(this._cache.position)) {
  99465. // Update to ensure devicePosition is up to date with most recent _deviceRoomPosition
  99466. if (!this.updateCacheCalled) {
  99467. // make sure it is only called once per loop. this.update() might cause an infinite loop.
  99468. this.updateCacheCalled = true;
  99469. this.update();
  99470. }
  99471. // Set working vector to the device position in room space rotated by the new rotation
  99472. this.rotationQuaternion.toRotationMatrix(this._workingMatrix);
  99473. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._workingMatrix, this._workingVector);
  99474. // Subtract this vector from the current device position in world to get the translation for the device world matrix
  99475. this.devicePosition.subtractToRef(this._workingVector, this._workingVector);
  99476. BABYLON.Matrix.ComposeToRef(this._oneVector, this.rotationQuaternion, this._workingVector, this._deviceToWorld);
  99477. // Add translation from anchor position
  99478. this._deviceToWorld.getTranslationToRef(this._workingVector);
  99479. this._workingVector.addInPlace(this.position);
  99480. this._workingVector.subtractInPlace(this._cache.position);
  99481. this._deviceToWorld.setTranslation(this._workingVector);
  99482. // Set an inverted matrix to be used when updating the camera
  99483. this._deviceToWorld.invertToRef(this._worldToDevice);
  99484. // Update the gamepad to ensure the mesh is updated on the same frame as camera
  99485. this.controllers.forEach(function (controller) {
  99486. controller._deviceToWorld.copyFrom(_this._deviceToWorld);
  99487. _this._correctPositionIfNotTrackPosition(controller._deviceToWorld);
  99488. controller.update();
  99489. });
  99490. }
  99491. if (!ignoreParentClass) {
  99492. _super.prototype._updateCache.call(this);
  99493. }
  99494. this.updateCacheCalled = false;
  99495. };
  99496. /**
  99497. * @hidden
  99498. * Get current device position in babylon world
  99499. */
  99500. WebVRFreeCamera.prototype._computeDevicePosition = function () {
  99501. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._deviceToWorld, this.devicePosition);
  99502. };
  99503. /**
  99504. * Updates the current device position and rotation in the babylon world
  99505. */
  99506. WebVRFreeCamera.prototype.update = function () {
  99507. this._computeDevicePosition();
  99508. // Get current device rotation in babylon world
  99509. BABYLON.Matrix.FromQuaternionToRef(this._deviceRoomRotationQuaternion, this._workingMatrix);
  99510. this._workingMatrix.multiplyToRef(this._deviceToWorld, this._workingMatrix);
  99511. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  99512. if (this._poseSet) {
  99513. this.onPoseUpdatedFromDeviceObservable.notifyObservers(null);
  99514. }
  99515. _super.prototype.update.call(this);
  99516. };
  99517. /**
  99518. * @hidden
  99519. * Gets the view matrix of this camera (Always set to identity as left and right eye cameras contain the actual view matrix)
  99520. * @returns an identity matrix
  99521. */
  99522. WebVRFreeCamera.prototype._getViewMatrix = function () {
  99523. return BABYLON.Matrix.Identity();
  99524. };
  99525. /**
  99526. * This function is called by the two RIG cameras.
  99527. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  99528. */
  99529. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  99530. var _this = this;
  99531. // Update the parent camera prior to using a child camera to avoid desynchronization
  99532. var parentCamera = this._cameraRigParams["parentCamera"];
  99533. parentCamera._updateCache();
  99534. //WebVR 1.1
  99535. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  99536. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  99537. if (!this.getScene().useRightHandedSystem) {
  99538. [2, 6, 8, 9, 14].forEach(function (num) {
  99539. _this._webvrViewMatrix.m[num] *= -1;
  99540. });
  99541. }
  99542. // update the camera rotation matrix
  99543. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  99544. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  99545. // Computing target and final matrix
  99546. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  99547. // should the view matrix be updated with scale and position offset?
  99548. if (parentCamera.deviceScaleFactor !== 1) {
  99549. this._webvrViewMatrix.invert();
  99550. // scale the position, if set
  99551. if (parentCamera.deviceScaleFactor) {
  99552. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  99553. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  99554. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  99555. }
  99556. this._webvrViewMatrix.invert();
  99557. }
  99558. // Remove translation from 6dof headset if trackposition is set to false
  99559. parentCamera._correctPositionIfNotTrackPosition(this._webvrViewMatrix, true);
  99560. parentCamera._worldToDevice.multiplyToRef(this._webvrViewMatrix, this._webvrViewMatrix);
  99561. // Compute global position
  99562. this._workingMatrix = this._workingMatrix || BABYLON.Matrix.Identity();
  99563. this._webvrViewMatrix.invertToRef(this._workingMatrix);
  99564. this._workingMatrix.multiplyToRef(parentCamera.getWorldMatrix(), this._workingMatrix);
  99565. this._workingMatrix.getTranslationToRef(this._globalPosition);
  99566. this._markSyncedWithParent();
  99567. return this._webvrViewMatrix;
  99568. };
  99569. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  99570. var _this = this;
  99571. var parentCamera = this.parent;
  99572. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  99573. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  99574. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  99575. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  99576. //babylon compatible matrix
  99577. if (!this.getScene().useRightHandedSystem) {
  99578. [8, 9, 10, 11].forEach(function (num) {
  99579. _this._projectionMatrix.m[num] *= -1;
  99580. });
  99581. }
  99582. return this._projectionMatrix;
  99583. };
  99584. /**
  99585. * Initializes the controllers and their meshes
  99586. */
  99587. WebVRFreeCamera.prototype.initControllers = function () {
  99588. var _this = this;
  99589. this.controllers = [];
  99590. var manager = this.getScene().gamepadManager;
  99591. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  99592. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  99593. var webVrController = gamepad;
  99594. if (webVrController.defaultModel) {
  99595. webVrController.defaultModel.setEnabled(false);
  99596. }
  99597. if (webVrController.hand === "right") {
  99598. _this._rightController = null;
  99599. }
  99600. if (webVrController.hand === "left") {
  99601. _this._leftController = null;
  99602. }
  99603. var controllerIndex = _this.controllers.indexOf(webVrController);
  99604. if (controllerIndex !== -1) {
  99605. _this.controllers.splice(controllerIndex, 1);
  99606. }
  99607. }
  99608. });
  99609. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  99610. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  99611. var webVrController_1 = gamepad;
  99612. if (!_this.webVROptions.trackPosition) {
  99613. webVrController_1._disableTrackPosition(new BABYLON.Vector3(webVrController_1.hand == "left" ? -0.15 : 0.15, -0.5, 0.25));
  99614. // Cache must be updated before rendering controllers to avoid them being one frame behind
  99615. if (!_this._updateCacheWhenTrackingDisabledObserver) {
  99616. _this._updateCacheWhenTrackingDisabledObserver = _this._scene.onBeforeRenderObservable.add(function () {
  99617. _this._updateCache();
  99618. });
  99619. }
  99620. }
  99621. webVrController_1.deviceScaleFactor = _this.deviceScaleFactor;
  99622. webVrController_1._deviceToWorld.copyFrom(_this._deviceToWorld);
  99623. _this._correctPositionIfNotTrackPosition(webVrController_1._deviceToWorld);
  99624. if (_this.webVROptions.controllerMeshes) {
  99625. if (webVrController_1.defaultModel) {
  99626. webVrController_1.defaultModel.setEnabled(true);
  99627. }
  99628. else {
  99629. // Load the meshes
  99630. webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) {
  99631. loadedMesh.scaling.scaleInPlace(_this.deviceScaleFactor);
  99632. _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1);
  99633. if (_this.webVROptions.defaultLightingOnControllers) {
  99634. if (!_this._lightOnControllers) {
  99635. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  99636. }
  99637. var activateLightOnSubMeshes_1 = function (mesh, light) {
  99638. var children = mesh.getChildren();
  99639. if (children && children.length !== 0) {
  99640. children.forEach(function (mesh) {
  99641. light.includedOnlyMeshes.push(mesh);
  99642. activateLightOnSubMeshes_1(mesh, light);
  99643. });
  99644. }
  99645. };
  99646. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  99647. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  99648. }
  99649. });
  99650. }
  99651. }
  99652. webVrController_1.attachToPoseControlledCamera(_this);
  99653. // since this is async - sanity check. Is the controller already stored?
  99654. if (_this.controllers.indexOf(webVrController_1) === -1) {
  99655. //add to the controllers array
  99656. _this.controllers.push(webVrController_1);
  99657. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  99658. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  99659. // So we're overriding setting left & right manually to be sure
  99660. var firstViveWandDetected = false;
  99661. for (var i = 0; i < _this.controllers.length; i++) {
  99662. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  99663. if (!firstViveWandDetected) {
  99664. firstViveWandDetected = true;
  99665. _this.controllers[i].hand = "left";
  99666. }
  99667. else {
  99668. _this.controllers[i].hand = "right";
  99669. }
  99670. }
  99671. }
  99672. //did we find enough controllers? Great! let the developer know.
  99673. if (_this.controllers.length >= 2) {
  99674. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  99675. }
  99676. }
  99677. }
  99678. });
  99679. };
  99680. return WebVRFreeCamera;
  99681. }(BABYLON.FreeCamera));
  99682. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  99683. })(BABYLON || (BABYLON = {}));
  99684. //# sourceMappingURL=babylon.webVRCamera.js.map
  99685. var BABYLON;
  99686. (function (BABYLON) {
  99687. BABYLON.Node.AddNodeConstructor("DeviceOrientationCamera", function (name, scene) {
  99688. return function () { return new DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  99689. });
  99690. // We're mainly based on the logic defined into the FreeCamera code
  99691. /**
  99692. * This is a camera specifically designed to react to device orientation events such as a modern mobile device
  99693. * being tilted forward or back and left or right.
  99694. */
  99695. var DeviceOrientationCamera = /** @class */ (function (_super) {
  99696. __extends(DeviceOrientationCamera, _super);
  99697. /**
  99698. * Creates a new device orientation camera
  99699. * @param name The name of the camera
  99700. * @param position The start position camera
  99701. * @param scene The scene the camera belongs to
  99702. */
  99703. function DeviceOrientationCamera(name, position, scene) {
  99704. var _this = _super.call(this, name, position, scene) || this;
  99705. _this._quaternionCache = new BABYLON.Quaternion();
  99706. _this.inputs.addDeviceOrientation();
  99707. return _this;
  99708. }
  99709. /**
  99710. * Gets the current instance class name ("DeviceOrientationCamera").
  99711. * This helps avoiding instanceof at run time.
  99712. * @returns the class name
  99713. */
  99714. DeviceOrientationCamera.prototype.getClassName = function () {
  99715. return "DeviceOrientationCamera";
  99716. };
  99717. /**
  99718. * @hidden
  99719. * Checks and applies the current values of the inputs to the camera. (Internal use only)
  99720. */
  99721. DeviceOrientationCamera.prototype._checkInputs = function () {
  99722. _super.prototype._checkInputs.call(this);
  99723. this._quaternionCache.copyFrom(this.rotationQuaternion);
  99724. if (this._initialQuaternion) {
  99725. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  99726. }
  99727. };
  99728. /**
  99729. * Reset the camera to its default orientation on the specified axis only.
  99730. * @param axis The axis to reset
  99731. */
  99732. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  99733. var _this = this;
  99734. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  99735. //can only work if this camera has a rotation quaternion already.
  99736. if (!this.rotationQuaternion)
  99737. return;
  99738. if (!this._initialQuaternion) {
  99739. this._initialQuaternion = new BABYLON.Quaternion();
  99740. }
  99741. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  99742. ['x', 'y', 'z'].forEach(function (axisName) {
  99743. if (!axis[axisName]) {
  99744. _this._initialQuaternion[axisName] = 0;
  99745. }
  99746. else {
  99747. _this._initialQuaternion[axisName] *= -1;
  99748. }
  99749. });
  99750. this._initialQuaternion.normalize();
  99751. //force rotation update
  99752. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  99753. };
  99754. return DeviceOrientationCamera;
  99755. }(BABYLON.FreeCamera));
  99756. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  99757. })(BABYLON || (BABYLON = {}));
  99758. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  99759. var BABYLON;
  99760. (function (BABYLON) {
  99761. BABYLON.Node.AddNodeConstructor("VRDeviceOrientationFreeCamera", function (name, scene) {
  99762. return function () { return new VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  99763. });
  99764. /**
  99765. * Camera used to simulate VR rendering (based on FreeCamera)
  99766. * @see http://doc.babylonjs.com/babylon101/cameras#vr-device-orientation-cameras
  99767. */
  99768. var VRDeviceOrientationFreeCamera = /** @class */ (function (_super) {
  99769. __extends(VRDeviceOrientationFreeCamera, _super);
  99770. /**
  99771. * Creates a new VRDeviceOrientationFreeCamera
  99772. * @param name defines camera name
  99773. * @param position defines the start position of the camera
  99774. * @param scene defines the scene the camera belongs to
  99775. * @param compensateDistortion defines if the camera needs to compensate the lens distorsion
  99776. * @param vrCameraMetrics defines the vr metrics associated to the camera
  99777. */
  99778. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  99779. if (compensateDistortion === void 0) { compensateDistortion = true; }
  99780. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  99781. var _this = _super.call(this, name, position, scene) || this;
  99782. vrCameraMetrics.compensateDistortion = compensateDistortion;
  99783. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  99784. return _this;
  99785. }
  99786. /**
  99787. * Gets camera class name
  99788. * @returns VRDeviceOrientationFreeCamera
  99789. */
  99790. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  99791. return "VRDeviceOrientationFreeCamera";
  99792. };
  99793. return VRDeviceOrientationFreeCamera;
  99794. }(BABYLON.DeviceOrientationCamera));
  99795. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  99796. })(BABYLON || (BABYLON = {}));
  99797. //# sourceMappingURL=babylon.vrDeviceOrientationFreeCamera.js.map
  99798. var BABYLON;
  99799. (function (BABYLON) {
  99800. BABYLON.Node.AddNodeConstructor("VRDeviceOrientationFreeCamera", function (name, scene) {
  99801. return function () { return new VRDeviceOrientationArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  99802. });
  99803. /**
  99804. * Camera used to simulate VR rendering (based on ArcRotateCamera)
  99805. * @see http://doc.babylonjs.com/babylon101/cameras#vr-device-orientation-cameras
  99806. */
  99807. var VRDeviceOrientationArcRotateCamera = /** @class */ (function (_super) {
  99808. __extends(VRDeviceOrientationArcRotateCamera, _super);
  99809. /**
  99810. * Creates a new VRDeviceOrientationArcRotateCamera
  99811. * @param name defines camera name
  99812. * @param alpha defines the camera rotation along the logitudinal axis
  99813. * @param beta defines the camera rotation along the latitudinal axis
  99814. * @param radius defines the camera distance from its target
  99815. * @param target defines the camera target
  99816. * @param scene defines the scene the camera belongs to
  99817. * @param compensateDistortion defines if the camera needs to compensate the lens distorsion
  99818. * @param vrCameraMetrics defines the vr metrics associated to the camera
  99819. */
  99820. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  99821. if (compensateDistortion === void 0) { compensateDistortion = true; }
  99822. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  99823. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  99824. vrCameraMetrics.compensateDistortion = compensateDistortion;
  99825. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  99826. _this.inputs.addVRDeviceOrientation();
  99827. return _this;
  99828. }
  99829. /**
  99830. * Gets camera class name
  99831. * @returns VRDeviceOrientationArcRotateCamera
  99832. */
  99833. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  99834. return "VRDeviceOrientationArcRotateCamera";
  99835. };
  99836. return VRDeviceOrientationArcRotateCamera;
  99837. }(BABYLON.ArcRotateCamera));
  99838. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  99839. })(BABYLON || (BABYLON = {}));
  99840. //# sourceMappingURL=babylon.vrDeviceOrientationArcRotateCamera.js.map
  99841. var BABYLON;
  99842. (function (BABYLON) {
  99843. BABYLON.Node.AddNodeConstructor("VRDeviceOrientationGamepadCamera", function (name, scene) {
  99844. return function () { return new VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  99845. });
  99846. /**
  99847. * Camera used to simulate VR rendering (based on VRDeviceOrientationFreeCamera)
  99848. * @see http://doc.babylonjs.com/babylon101/cameras#vr-device-orientation-cameras
  99849. */
  99850. var VRDeviceOrientationGamepadCamera = /** @class */ (function (_super) {
  99851. __extends(VRDeviceOrientationGamepadCamera, _super);
  99852. /**
  99853. * Creates a new VRDeviceOrientationGamepadCamera
  99854. * @param name defines camera name
  99855. * @param position defines the start position of the camera
  99856. * @param scene defines the scene the camera belongs to
  99857. * @param compensateDistortion defines if the camera needs to compensate the lens distorsion
  99858. * @param vrCameraMetrics defines the vr metrics associated to the camera
  99859. */
  99860. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  99861. if (compensateDistortion === void 0) { compensateDistortion = true; }
  99862. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  99863. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  99864. _this.inputs.addGamepad();
  99865. return _this;
  99866. }
  99867. /**
  99868. * Gets camera class name
  99869. * @returns VRDeviceOrientationGamepadCamera
  99870. */
  99871. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  99872. return "VRDeviceOrientationGamepadCamera";
  99873. };
  99874. return VRDeviceOrientationGamepadCamera;
  99875. }(BABYLON.VRDeviceOrientationFreeCamera));
  99876. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  99877. })(BABYLON || (BABYLON = {}));
  99878. //# sourceMappingURL=babylon.vrDeviceOrientationGamepadCamera.js.map
  99879. var BABYLON;
  99880. (function (BABYLON) {
  99881. var VRExperienceHelperGazer = /** @class */ (function () {
  99882. function VRExperienceHelperGazer(scene, gazeTrackerToClone) {
  99883. if (gazeTrackerToClone === void 0) { gazeTrackerToClone = null; }
  99884. this.scene = scene;
  99885. /** @hidden */
  99886. this._pointerDownOnMeshAsked = false;
  99887. /** @hidden */
  99888. this._isActionableMesh = false;
  99889. /** @hidden */
  99890. this._teleportationRequestInitiated = false;
  99891. /** @hidden */
  99892. this._teleportationBackRequestInitiated = false;
  99893. /** @hidden */
  99894. this._rotationRightAsked = false;
  99895. /** @hidden */
  99896. this._rotationLeftAsked = false;
  99897. /** @hidden */
  99898. this._dpadPressed = true;
  99899. /** @hidden */
  99900. this._activePointer = false;
  99901. this._id = VRExperienceHelperGazer._idCounter++;
  99902. // Gaze tracker
  99903. if (!gazeTrackerToClone) {
  99904. this._gazeTracker = BABYLON.Mesh.CreateTorus("gazeTracker", 0.0035, 0.0025, 20, scene, false);
  99905. this._gazeTracker.bakeCurrentTransformIntoVertices();
  99906. this._gazeTracker.isPickable = false;
  99907. this._gazeTracker.isVisible = false;
  99908. var targetMat = new BABYLON.StandardMaterial("targetMat", scene);
  99909. targetMat.specularColor = BABYLON.Color3.Black();
  99910. targetMat.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  99911. targetMat.backFaceCulling = false;
  99912. this._gazeTracker.material = targetMat;
  99913. }
  99914. else {
  99915. this._gazeTracker = gazeTrackerToClone.clone("gazeTracker");
  99916. }
  99917. }
  99918. /** @hidden */
  99919. VRExperienceHelperGazer.prototype._getForwardRay = function (length) {
  99920. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, length));
  99921. };
  99922. /** @hidden */
  99923. VRExperienceHelperGazer.prototype._selectionPointerDown = function () {
  99924. this._pointerDownOnMeshAsked = true;
  99925. if (this._currentHit) {
  99926. this.scene.simulatePointerDown(this._currentHit, { pointerId: this._id });
  99927. }
  99928. };
  99929. /** @hidden */
  99930. VRExperienceHelperGazer.prototype._selectionPointerUp = function () {
  99931. if (this._currentHit) {
  99932. this.scene.simulatePointerUp(this._currentHit, { pointerId: this._id });
  99933. }
  99934. this._pointerDownOnMeshAsked = false;
  99935. };
  99936. /** @hidden */
  99937. VRExperienceHelperGazer.prototype._activatePointer = function () {
  99938. this._activePointer = true;
  99939. };
  99940. /** @hidden */
  99941. VRExperienceHelperGazer.prototype._deactivatePointer = function () {
  99942. this._activePointer = false;
  99943. };
  99944. /** @hidden */
  99945. VRExperienceHelperGazer.prototype._updatePointerDistance = function (distance) {
  99946. if (distance === void 0) { distance = 100; }
  99947. };
  99948. VRExperienceHelperGazer.prototype.dispose = function () {
  99949. this._interactionsEnabled = false;
  99950. this._teleportationEnabled = false;
  99951. if (this._gazeTracker) {
  99952. this._gazeTracker.dispose();
  99953. }
  99954. };
  99955. VRExperienceHelperGazer._idCounter = 0;
  99956. return VRExperienceHelperGazer;
  99957. }());
  99958. var VRExperienceHelperControllerGazer = /** @class */ (function (_super) {
  99959. __extends(VRExperienceHelperControllerGazer, _super);
  99960. function VRExperienceHelperControllerGazer(webVRController, scene, gazeTrackerToClone) {
  99961. var _this = _super.call(this, scene, gazeTrackerToClone) || this;
  99962. _this.webVRController = webVRController;
  99963. // Laser pointer
  99964. _this._laserPointer = BABYLON.Mesh.CreateCylinder("laserPointer", 1, 0.004, 0.0002, 20, 1, scene, false);
  99965. var laserPointerMaterial = new BABYLON.StandardMaterial("laserPointerMat", scene);
  99966. laserPointerMaterial.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  99967. laserPointerMaterial.alpha = 0.6;
  99968. _this._laserPointer.material = laserPointerMaterial;
  99969. _this._laserPointer.rotation.x = Math.PI / 2;
  99970. _this._laserPointer.position.z = -0.5;
  99971. _this._laserPointer.isVisible = false;
  99972. _this._laserPointer.isPickable = false;
  99973. if (!webVRController.mesh) {
  99974. // Create an empty mesh that is used prior to loading the high quality model
  99975. var preloadMesh = new BABYLON.Mesh("preloadControllerMesh", scene);
  99976. var preloadPointerPose = new BABYLON.Mesh(BABYLON.PoseEnabledController.POINTING_POSE, scene);
  99977. preloadPointerPose.rotation.x = -0.7;
  99978. preloadMesh.addChild(preloadPointerPose);
  99979. webVRController.attachToMesh(preloadMesh);
  99980. }
  99981. _this._setLaserPointerParent(webVRController.mesh);
  99982. _this._meshAttachedObserver = webVRController._meshAttachedObservable.add(function (mesh) {
  99983. _this._setLaserPointerParent(mesh);
  99984. });
  99985. return _this;
  99986. }
  99987. VRExperienceHelperControllerGazer.prototype._getForwardRay = function (length) {
  99988. return this.webVRController.getForwardRay(length);
  99989. };
  99990. /** @hidden */
  99991. VRExperienceHelperControllerGazer.prototype._activatePointer = function () {
  99992. _super.prototype._activatePointer.call(this);
  99993. this._laserPointer.isVisible = true;
  99994. };
  99995. /** @hidden */
  99996. VRExperienceHelperControllerGazer.prototype._deactivatePointer = function () {
  99997. _super.prototype._deactivatePointer.call(this);
  99998. this._laserPointer.isVisible = false;
  99999. };
  100000. /** @hidden */
  100001. VRExperienceHelperControllerGazer.prototype._setLaserPointerColor = function (color) {
  100002. this._laserPointer.material.emissiveColor = color;
  100003. };
  100004. /** @hidden */
  100005. VRExperienceHelperControllerGazer.prototype._setLaserPointerParent = function (mesh) {
  100006. var makeNotPick = function (root) {
  100007. root.isPickable = false;
  100008. root.getChildMeshes().forEach(function (c) {
  100009. makeNotPick(c);
  100010. });
  100011. };
  100012. makeNotPick(mesh);
  100013. var childMeshes = mesh.getChildMeshes();
  100014. this.webVRController._pointingPoseNode = null;
  100015. for (var i = 0; i < childMeshes.length; i++) {
  100016. if (childMeshes[i].name && childMeshes[i].name.indexOf(BABYLON.PoseEnabledController.POINTING_POSE) >= 0) {
  100017. mesh = childMeshes[i];
  100018. this.webVRController._pointingPoseNode = mesh;
  100019. break;
  100020. }
  100021. }
  100022. this._laserPointer.parent = mesh;
  100023. };
  100024. VRExperienceHelperControllerGazer.prototype._updatePointerDistance = function (distance) {
  100025. if (distance === void 0) { distance = 100; }
  100026. this._laserPointer.scaling.y = distance;
  100027. this._laserPointer.position.z = -distance / 2;
  100028. };
  100029. VRExperienceHelperControllerGazer.prototype.dispose = function () {
  100030. _super.prototype.dispose.call(this);
  100031. this._laserPointer.dispose();
  100032. if (this._meshAttachedObserver) {
  100033. this.webVRController._meshAttachedObservable.remove(this._meshAttachedObserver);
  100034. }
  100035. };
  100036. return VRExperienceHelperControllerGazer;
  100037. }(VRExperienceHelperGazer));
  100038. var VRExperienceHelperCameraGazer = /** @class */ (function (_super) {
  100039. __extends(VRExperienceHelperCameraGazer, _super);
  100040. function VRExperienceHelperCameraGazer(getCamera, scene) {
  100041. var _this = _super.call(this, scene) || this;
  100042. _this.getCamera = getCamera;
  100043. return _this;
  100044. }
  100045. VRExperienceHelperCameraGazer.prototype._getForwardRay = function (length) {
  100046. var camera = this.getCamera();
  100047. if (camera) {
  100048. return camera.getForwardRay(length);
  100049. }
  100050. else {
  100051. return new BABYLON.Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward());
  100052. }
  100053. };
  100054. return VRExperienceHelperCameraGazer;
  100055. }(VRExperienceHelperGazer));
  100056. /**
  100057. * Helps to quickly add VR support to an existing scene.
  100058. * See http://doc.babylonjs.com/how_to/webvr_helper
  100059. */
  100060. var VRExperienceHelper = /** @class */ (function () {
  100061. /**
  100062. * Instantiates a VRExperienceHelper.
  100063. * Helps to quickly add VR support to an existing scene.
  100064. * @param scene The scene the VRExperienceHelper belongs to.
  100065. * @param webVROptions Options to modify the vr experience helper's behavior.
  100066. */
  100067. function VRExperienceHelper(scene,
  100068. /** Options to modify the vr experience helper's behavior. */
  100069. webVROptions) {
  100070. if (webVROptions === void 0) { webVROptions = {}; }
  100071. var _this = this;
  100072. this.webVROptions = webVROptions;
  100073. // Can the system support WebVR, even if a headset isn't plugged in?
  100074. this._webVRsupported = false;
  100075. // If WebVR is supported, is a headset plugged in and are we ready to present?
  100076. this._webVRready = false;
  100077. // Are we waiting for the requestPresent callback to complete?
  100078. this._webVRrequesting = false;
  100079. // Are we presenting to the headset right now? (this is the vrDevice state)
  100080. this._webVRpresenting = false;
  100081. // Are we presenting in the fullscreen fallback?
  100082. this._fullscreenVRpresenting = false;
  100083. /**
  100084. * Observable raised when entering VR.
  100085. */
  100086. this.onEnteringVRObservable = new BABYLON.Observable();
  100087. /**
  100088. * Observable raised when exiting VR.
  100089. */
  100090. this.onExitingVRObservable = new BABYLON.Observable();
  100091. /**
  100092. * Observable raised when controller mesh is loaded.
  100093. */
  100094. this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  100095. this._useCustomVRButton = false;
  100096. this._teleportationRequested = false;
  100097. this._teleportActive = false;
  100098. this._floorMeshesCollection = [];
  100099. this._rotationAllowed = true;
  100100. this._teleportBackwardsVector = new BABYLON.Vector3(0, -1, -1);
  100101. this._isDefaultTeleportationTarget = true;
  100102. this._teleportationFillColor = "#444444";
  100103. this._teleportationBorderColor = "#FFFFFF";
  100104. this._rotationAngle = 0;
  100105. this._haloCenter = new BABYLON.Vector3(0, 0, 0);
  100106. this._padSensibilityUp = 0.65;
  100107. this._padSensibilityDown = 0.35;
  100108. this._leftController = null;
  100109. this._rightController = null;
  100110. /**
  100111. * Observable raised when a new mesh is selected based on meshSelectionPredicate
  100112. */
  100113. this.onNewMeshSelected = new BABYLON.Observable();
  100114. /**
  100115. * Observable raised when a new mesh is picked based on meshSelectionPredicate
  100116. */
  100117. this.onNewMeshPicked = new BABYLON.Observable();
  100118. /**
  100119. * Observable raised before camera teleportation
  100120. */
  100121. this.onBeforeCameraTeleport = new BABYLON.Observable();
  100122. /**
  100123. * Observable raised after camera teleportation
  100124. */
  100125. this.onAfterCameraTeleport = new BABYLON.Observable();
  100126. /**
  100127. * Observable raised when current selected mesh gets unselected
  100128. */
  100129. this.onSelectedMeshUnselected = new BABYLON.Observable();
  100130. /**
  100131. * Set teleportation enabled. If set to false camera teleportation will be disabled but camera rotation will be kept.
  100132. */
  100133. this.teleportationEnabled = true;
  100134. this._teleportationInitialized = false;
  100135. this._interactionsEnabled = false;
  100136. this._interactionsRequested = false;
  100137. this._displayGaze = true;
  100138. this._displayLaserPointer = true;
  100139. /**
  100140. * If the gaze trackers scale should be updated to be constant size when pointing at near/far meshes
  100141. */
  100142. this.updateGazeTrackerScale = true;
  100143. this._onResize = function () {
  100144. _this.moveButtonToBottomRight();
  100145. if (_this._fullscreenVRpresenting && _this._webVRready) {
  100146. _this.exitVR();
  100147. }
  100148. };
  100149. this._onFullscreenChange = function () {
  100150. if (document.fullscreen !== undefined) {
  100151. _this._fullscreenVRpresenting = document.fullscreen;
  100152. }
  100153. else if (document.mozFullScreen !== undefined) {
  100154. _this._fullscreenVRpresenting = document.mozFullScreen;
  100155. }
  100156. else if (document.webkitIsFullScreen !== undefined) {
  100157. _this._fullscreenVRpresenting = document.webkitIsFullScreen;
  100158. }
  100159. else if (document.msIsFullScreen !== undefined) {
  100160. _this._fullscreenVRpresenting = document.msIsFullScreen;
  100161. }
  100162. else if (document.msFullscreenElement !== undefined) {
  100163. _this._fullscreenVRpresenting = document.msFullscreenElement;
  100164. }
  100165. if (!_this._fullscreenVRpresenting && _this._canvas) {
  100166. _this.exitVR();
  100167. if (!_this._useCustomVRButton) {
  100168. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  100169. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  100170. }
  100171. }
  100172. };
  100173. this.beforeRender = function () {
  100174. if (_this._leftController && _this._leftController._activePointer) {
  100175. _this._castRayAndSelectObject(_this._leftController);
  100176. }
  100177. if (_this._rightController && _this._rightController._activePointer) {
  100178. _this._castRayAndSelectObject(_this._rightController);
  100179. }
  100180. if (_this._noControllerIsActive) {
  100181. _this._castRayAndSelectObject(_this._cameraGazer);
  100182. }
  100183. else {
  100184. _this._cameraGazer._gazeTracker.isVisible = false;
  100185. }
  100186. };
  100187. this._onNewGamepadConnected = function (gamepad) {
  100188. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  100189. if (gamepad.leftStick) {
  100190. gamepad.onleftstickchanged(function (stickValues) {
  100191. if (_this._teleportationInitialized && _this.teleportationEnabled) {
  100192. // Listening to classic/xbox gamepad only if no VR controller is active
  100193. if ((!_this._leftController && !_this._rightController) ||
  100194. ((_this._leftController && !_this._leftController._activePointer) &&
  100195. (_this._rightController && !_this._rightController._activePointer))) {
  100196. _this._checkTeleportWithRay(stickValues, _this._cameraGazer);
  100197. _this._checkTeleportBackwards(stickValues, _this._cameraGazer);
  100198. }
  100199. }
  100200. });
  100201. }
  100202. if (gamepad.rightStick) {
  100203. gamepad.onrightstickchanged(function (stickValues) {
  100204. if (_this._teleportationInitialized) {
  100205. _this._checkRotate(stickValues, _this._cameraGazer);
  100206. }
  100207. });
  100208. }
  100209. if (gamepad.type === BABYLON.Gamepad.XBOX) {
  100210. gamepad.onbuttondown(function (buttonPressed) {
  100211. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  100212. _this._cameraGazer._selectionPointerDown();
  100213. }
  100214. });
  100215. gamepad.onbuttonup(function (buttonPressed) {
  100216. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  100217. _this._cameraGazer._selectionPointerUp();
  100218. }
  100219. });
  100220. }
  100221. }
  100222. else {
  100223. var webVRController = gamepad;
  100224. var controller = new VRExperienceHelperControllerGazer(webVRController, _this._scene, _this._cameraGazer._gazeTracker);
  100225. if (webVRController.hand === "right" || (_this._leftController && _this._leftController.webVRController != webVRController)) {
  100226. _this._rightController = controller;
  100227. }
  100228. else {
  100229. _this._leftController = controller;
  100230. }
  100231. _this._tryEnableInteractionOnController(controller);
  100232. }
  100233. };
  100234. // 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
  100235. this._tryEnableInteractionOnController = function (controller) {
  100236. if (_this._interactionsRequested && !controller._interactionsEnabled) {
  100237. _this._enableInteractionOnController(controller);
  100238. }
  100239. if (_this._teleportationRequested && !controller._teleportationEnabled) {
  100240. _this._enableTeleportationOnController(controller);
  100241. }
  100242. };
  100243. this._onNewGamepadDisconnected = function (gamepad) {
  100244. if (gamepad instanceof BABYLON.WebVRController) {
  100245. if (gamepad.hand === "left" && _this._leftController != null) {
  100246. _this._leftController.dispose();
  100247. _this._leftController = null;
  100248. }
  100249. if (gamepad.hand === "right" && _this._rightController != null) {
  100250. _this._rightController.dispose();
  100251. _this._rightController = null;
  100252. }
  100253. }
  100254. };
  100255. this._workingVector = BABYLON.Vector3.Zero();
  100256. this._workingQuaternion = BABYLON.Quaternion.Identity();
  100257. this._workingMatrix = BABYLON.Matrix.Identity();
  100258. this._scene = scene;
  100259. this._canvas = scene.getEngine().getRenderingCanvas();
  100260. // Parse options
  100261. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera === undefined) {
  100262. webVROptions.createFallbackVRDeviceOrientationFreeCamera = true;
  100263. }
  100264. if (webVROptions.createDeviceOrientationCamera === undefined) {
  100265. webVROptions.createDeviceOrientationCamera = true;
  100266. }
  100267. if (webVROptions.laserToggle === undefined) {
  100268. webVROptions.laserToggle = true;
  100269. }
  100270. if (webVROptions.defaultHeight === undefined) {
  100271. webVROptions.defaultHeight = 1.7;
  100272. }
  100273. if (webVROptions.useCustomVRButton) {
  100274. this._useCustomVRButton = true;
  100275. if (webVROptions.customVRButton) {
  100276. this._btnVR = webVROptions.customVRButton;
  100277. }
  100278. }
  100279. if (webVROptions.rayLength) {
  100280. this._rayLength = webVROptions.rayLength;
  100281. }
  100282. this._defaultHeight = webVROptions.defaultHeight;
  100283. if (webVROptions.positionScale) {
  100284. this._rayLength *= webVROptions.positionScale;
  100285. this._defaultHeight *= webVROptions.positionScale;
  100286. }
  100287. this._hasEnteredVR = false;
  100288. // Set position
  100289. if (this._scene.activeCamera) {
  100290. this._position = this._scene.activeCamera.position.clone();
  100291. }
  100292. else {
  100293. this._position = new BABYLON.Vector3(0, this._defaultHeight, 0);
  100294. }
  100295. // Set non-vr camera
  100296. if (webVROptions.createDeviceOrientationCamera || !this._scene.activeCamera) {
  100297. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._position.clone(), scene);
  100298. // Copy data from existing camera
  100299. if (this._scene.activeCamera) {
  100300. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  100301. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  100302. // Set rotation from previous camera
  100303. if (this._scene.activeCamera instanceof BABYLON.TargetCamera && this._scene.activeCamera.rotation) {
  100304. var targetCamera = this._scene.activeCamera;
  100305. if (targetCamera.rotationQuaternion) {
  100306. this._deviceOrientationCamera.rotationQuaternion.copyFrom(targetCamera.rotationQuaternion);
  100307. }
  100308. else {
  100309. this._deviceOrientationCamera.rotationQuaternion.copyFrom(BABYLON.Quaternion.RotationYawPitchRoll(targetCamera.rotation.y, targetCamera.rotation.x, targetCamera.rotation.z));
  100310. }
  100311. this._deviceOrientationCamera.rotation = targetCamera.rotation.clone();
  100312. }
  100313. }
  100314. this._scene.activeCamera = this._deviceOrientationCamera;
  100315. if (this._canvas) {
  100316. this._scene.activeCamera.attachControl(this._canvas);
  100317. }
  100318. }
  100319. else {
  100320. this._existingCamera = this._scene.activeCamera;
  100321. }
  100322. // Create VR cameras
  100323. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  100324. this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  100325. }
  100326. this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene, webVROptions);
  100327. this._webVRCamera.useStandingMatrix();
  100328. this._cameraGazer = new VRExperienceHelperCameraGazer(function () { return _this.currentVRCamera; }, scene);
  100329. // Create default button
  100330. if (!this._useCustomVRButton) {
  100331. this._btnVR = document.createElement("BUTTON");
  100332. this._btnVR.className = "babylonVRicon";
  100333. this._btnVR.id = "babylonVRiconbtn";
  100334. this._btnVR.title = "Click to switch to VR";
  100335. 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) }";
  100336. css += ".babylonVRicon.vrdisplaypresenting { display: none; }";
  100337. // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)
  100338. // css += ".babylonVRicon.vrdisplaysupported { }";
  100339. // css += ".babylonVRicon.vrdisplayready { }";
  100340. // css += ".babylonVRicon.vrdisplayrequesting { }";
  100341. var style = document.createElement('style');
  100342. style.appendChild(document.createTextNode(css));
  100343. document.getElementsByTagName('head')[0].appendChild(style);
  100344. this.moveButtonToBottomRight();
  100345. }
  100346. // VR button click event
  100347. if (this._btnVR) {
  100348. this._btnVR.addEventListener("click", function () {
  100349. if (!_this.isInVRMode) {
  100350. _this.enterVR();
  100351. }
  100352. else {
  100353. _this.exitVR();
  100354. }
  100355. });
  100356. }
  100357. // Window events
  100358. window.addEventListener("resize", this._onResize);
  100359. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  100360. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  100361. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  100362. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  100363. document.onmsfullscreenchange = this._onFullscreenChange;
  100364. // Display vr button when headset is connected
  100365. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  100366. this.displayVRButton();
  100367. }
  100368. else {
  100369. this._scene.getEngine().onVRDisplayChangedObservable.add(function (e) {
  100370. if (e.vrDisplay) {
  100371. _this.displayVRButton();
  100372. }
  100373. });
  100374. }
  100375. // Exiting VR mode using 'ESC' key on desktop
  100376. this._onKeyDown = function (event) {
  100377. if (event.keyCode === 27 && _this.isInVRMode) {
  100378. _this.exitVR();
  100379. }
  100380. };
  100381. document.addEventListener("keydown", this._onKeyDown);
  100382. // Exiting VR mode double tapping the touch screen
  100383. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  100384. if (_this.isInVRMode) {
  100385. _this.exitVR();
  100386. if (_this._fullscreenVRpresenting) {
  100387. _this._scene.getEngine().switchFullscreen(true);
  100388. }
  100389. }
  100390. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  100391. // Listen for WebVR display changes
  100392. this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); };
  100393. this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); };
  100394. this._onVRRequestPresentStart = function () {
  100395. _this._webVRrequesting = true;
  100396. _this.updateButtonVisibility();
  100397. };
  100398. this._onVRRequestPresentComplete = function (success) {
  100399. _this._webVRrequesting = false;
  100400. _this.updateButtonVisibility();
  100401. };
  100402. scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);
  100403. scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);
  100404. scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);
  100405. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  100406. scene.onDisposeObservable.add(function () {
  100407. _this.dispose();
  100408. });
  100409. // Gamepad connection events
  100410. this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); });
  100411. this._scene.gamepadManager.onGamepadConnectedObservable.add(this._onNewGamepadConnected);
  100412. this._scene.gamepadManager.onGamepadDisconnectedObservable.add(this._onNewGamepadDisconnected);
  100413. this.updateButtonVisibility();
  100414. //create easing functions
  100415. this._circleEase = new BABYLON.CircleEase();
  100416. this._circleEase.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  100417. if (this.webVROptions.floorMeshes) {
  100418. this.enableTeleportation({ floorMeshes: this.webVROptions.floorMeshes });
  100419. }
  100420. }
  100421. Object.defineProperty(VRExperienceHelper.prototype, "onEnteringVR", {
  100422. /** Return this.onEnteringVRObservable
  100423. * Note: This one is for backward compatibility. Please use onEnteringVRObservable directly
  100424. */
  100425. get: function () {
  100426. return this.onEnteringVRObservable;
  100427. },
  100428. enumerable: true,
  100429. configurable: true
  100430. });
  100431. Object.defineProperty(VRExperienceHelper.prototype, "onExitingVR", {
  100432. /** Return this.onExitingVRObservable
  100433. * Note: This one is for backward compatibility. Please use onExitingVRObservable directly
  100434. */
  100435. get: function () {
  100436. return this.onExitingVRObservable;
  100437. },
  100438. enumerable: true,
  100439. configurable: true
  100440. });
  100441. Object.defineProperty(VRExperienceHelper.prototype, "onControllerMeshLoaded", {
  100442. /** Return this.onControllerMeshLoadedObservable
  100443. * Note: This one is for backward compatibility. Please use onControllerMeshLoadedObservable directly
  100444. */
  100445. get: function () {
  100446. return this.onControllerMeshLoadedObservable;
  100447. },
  100448. enumerable: true,
  100449. configurable: true
  100450. });
  100451. Object.defineProperty(VRExperienceHelper.prototype, "teleportationTarget", {
  100452. /**
  100453. * The mesh used to display where the user is going to teleport.
  100454. */
  100455. get: function () {
  100456. return this._teleportationTarget;
  100457. },
  100458. /**
  100459. * Sets the mesh to be used to display where the user is going to teleport.
  100460. */
  100461. set: function (value) {
  100462. if (value) {
  100463. value.name = "teleportationTarget";
  100464. this._isDefaultTeleportationTarget = false;
  100465. this._teleportationTarget = value;
  100466. }
  100467. },
  100468. enumerable: true,
  100469. configurable: true
  100470. });
  100471. Object.defineProperty(VRExperienceHelper.prototype, "gazeTrackerMesh", {
  100472. /**
  100473. * The mesh used to display where the user is selecting, this mesh will be cloned and set as the gazeTracker for the left and right controller
  100474. * when set bakeCurrentTransformIntoVertices will be called on the mesh.
  100475. * See http://doc.babylonjs.com/resources/baking_transformations
  100476. */
  100477. get: function () {
  100478. return this._cameraGazer._gazeTracker;
  100479. },
  100480. set: function (value) {
  100481. if (value) {
  100482. // Dispose of existing meshes
  100483. if (this._cameraGazer._gazeTracker) {
  100484. this._cameraGazer._gazeTracker.dispose();
  100485. }
  100486. if (this._leftController && this._leftController._gazeTracker) {
  100487. this._leftController._gazeTracker.dispose();
  100488. }
  100489. if (this._rightController && this._rightController._gazeTracker) {
  100490. this._rightController._gazeTracker.dispose();
  100491. }
  100492. // Set and create gaze trackers on head and controllers
  100493. this._cameraGazer._gazeTracker = value;
  100494. this._cameraGazer._gazeTracker.bakeCurrentTransformIntoVertices();
  100495. this._cameraGazer._gazeTracker.isPickable = false;
  100496. this._cameraGazer._gazeTracker.isVisible = false;
  100497. this._cameraGazer._gazeTracker.name = "gazeTracker";
  100498. if (this._leftController) {
  100499. this._leftController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  100500. }
  100501. if (this._rightController) {
  100502. this._rightController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  100503. }
  100504. }
  100505. },
  100506. enumerable: true,
  100507. configurable: true
  100508. });
  100509. Object.defineProperty(VRExperienceHelper.prototype, "leftControllerGazeTrackerMesh", {
  100510. /**
  100511. * The gaze tracking mesh corresponding to the left controller
  100512. */
  100513. get: function () {
  100514. if (this._leftController) {
  100515. return this._leftController._gazeTracker;
  100516. }
  100517. return null;
  100518. },
  100519. enumerable: true,
  100520. configurable: true
  100521. });
  100522. Object.defineProperty(VRExperienceHelper.prototype, "rightControllerGazeTrackerMesh", {
  100523. /**
  100524. * The gaze tracking mesh corresponding to the right controller
  100525. */
  100526. get: function () {
  100527. if (this._rightController) {
  100528. return this._rightController._gazeTracker;
  100529. }
  100530. return null;
  100531. },
  100532. enumerable: true,
  100533. configurable: true
  100534. });
  100535. Object.defineProperty(VRExperienceHelper.prototype, "displayGaze", {
  100536. /**
  100537. * If the ray of the gaze should be displayed.
  100538. */
  100539. get: function () {
  100540. return this._displayGaze;
  100541. },
  100542. /**
  100543. * Sets if the ray of the gaze should be displayed.
  100544. */
  100545. set: function (value) {
  100546. this._displayGaze = value;
  100547. if (!value) {
  100548. this._cameraGazer._gazeTracker.isVisible = false;
  100549. if (this._leftController) {
  100550. this._leftController._gazeTracker.isVisible = false;
  100551. }
  100552. if (this._rightController) {
  100553. this._rightController._gazeTracker.isVisible = false;
  100554. }
  100555. }
  100556. },
  100557. enumerable: true,
  100558. configurable: true
  100559. });
  100560. Object.defineProperty(VRExperienceHelper.prototype, "displayLaserPointer", {
  100561. /**
  100562. * If the ray of the LaserPointer should be displayed.
  100563. */
  100564. get: function () {
  100565. return this._displayLaserPointer;
  100566. },
  100567. /**
  100568. * Sets if the ray of the LaserPointer should be displayed.
  100569. */
  100570. set: function (value) {
  100571. this._displayLaserPointer = value;
  100572. if (!value) {
  100573. if (this._rightController) {
  100574. this._rightController._deactivatePointer();
  100575. this._rightController._gazeTracker.isVisible = false;
  100576. }
  100577. if (this._leftController) {
  100578. this._leftController._deactivatePointer();
  100579. this._leftController._gazeTracker.isVisible = false;
  100580. }
  100581. }
  100582. else {
  100583. if (this._rightController) {
  100584. this._rightController._activatePointer();
  100585. }
  100586. if (this._leftController) {
  100587. this._leftController._activatePointer();
  100588. }
  100589. }
  100590. },
  100591. enumerable: true,
  100592. configurable: true
  100593. });
  100594. Object.defineProperty(VRExperienceHelper.prototype, "deviceOrientationCamera", {
  100595. /**
  100596. * The deviceOrientationCamera used as the camera when not in VR.
  100597. */
  100598. get: function () {
  100599. return this._deviceOrientationCamera;
  100600. },
  100601. enumerable: true,
  100602. configurable: true
  100603. });
  100604. Object.defineProperty(VRExperienceHelper.prototype, "currentVRCamera", {
  100605. /**
  100606. * Based on the current WebVR support, returns the current VR camera used.
  100607. */
  100608. get: function () {
  100609. if (this._webVRready) {
  100610. return this._webVRCamera;
  100611. }
  100612. else {
  100613. return this._scene.activeCamera;
  100614. }
  100615. },
  100616. enumerable: true,
  100617. configurable: true
  100618. });
  100619. Object.defineProperty(VRExperienceHelper.prototype, "webVRCamera", {
  100620. /**
  100621. * The webVRCamera which is used when in VR.
  100622. */
  100623. get: function () {
  100624. return this._webVRCamera;
  100625. },
  100626. enumerable: true,
  100627. configurable: true
  100628. });
  100629. Object.defineProperty(VRExperienceHelper.prototype, "vrDeviceOrientationCamera", {
  100630. /**
  100631. * The deviceOrientationCamera that is used as a fallback when vr device is not connected.
  100632. */
  100633. get: function () {
  100634. return this._vrDeviceOrientationCamera;
  100635. },
  100636. enumerable: true,
  100637. configurable: true
  100638. });
  100639. Object.defineProperty(VRExperienceHelper.prototype, "_teleportationRequestInitiated", {
  100640. get: function () {
  100641. var result = this._cameraGazer._teleportationRequestInitiated
  100642. || (this._leftController !== null && this._leftController._teleportationRequestInitiated)
  100643. || (this._rightController !== null && this._rightController._teleportationRequestInitiated);
  100644. return result;
  100645. },
  100646. enumerable: true,
  100647. configurable: true
  100648. });
  100649. // Raised when one of the controller has loaded successfully its associated default mesh
  100650. VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) {
  100651. if (this._leftController && this._leftController.webVRController == webVRController) {
  100652. if (webVRController.mesh) {
  100653. this._leftController._setLaserPointerParent(webVRController.mesh);
  100654. }
  100655. }
  100656. if (this._rightController && this._rightController.webVRController == webVRController) {
  100657. if (webVRController.mesh) {
  100658. this._rightController._setLaserPointerParent(webVRController.mesh);
  100659. }
  100660. }
  100661. try {
  100662. this.onControllerMeshLoadedObservable.notifyObservers(webVRController);
  100663. }
  100664. catch (err) {
  100665. BABYLON.Tools.Warn("Error in your custom logic onControllerMeshLoaded: " + err);
  100666. }
  100667. };
  100668. Object.defineProperty(VRExperienceHelper.prototype, "isInVRMode", {
  100669. /**
  100670. * Gets a value indicating if we are currently in VR mode.
  100671. */
  100672. get: function () {
  100673. return this._webVRpresenting || this._fullscreenVRpresenting;
  100674. },
  100675. enumerable: true,
  100676. configurable: true
  100677. });
  100678. VRExperienceHelper.prototype.onVrDisplayPresentChange = function () {
  100679. var vrDisplay = this._scene.getEngine().getVRDevice();
  100680. if (vrDisplay) {
  100681. var wasPresenting = this._webVRpresenting;
  100682. this._webVRpresenting = vrDisplay.isPresenting;
  100683. if (wasPresenting && !this._webVRpresenting)
  100684. this.exitVR();
  100685. }
  100686. else {
  100687. BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');
  100688. }
  100689. this.updateButtonVisibility();
  100690. };
  100691. VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) {
  100692. this._webVRsupported = eventArgs.vrSupported;
  100693. this._webVRready = !!eventArgs.vrDisplay;
  100694. this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;
  100695. this.updateButtonVisibility();
  100696. };
  100697. VRExperienceHelper.prototype.moveButtonToBottomRight = function () {
  100698. if (this._canvas && !this._useCustomVRButton) {
  100699. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  100700. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  100701. }
  100702. };
  100703. VRExperienceHelper.prototype.displayVRButton = function () {
  100704. if (!this._useCustomVRButton && !this._btnVRDisplayed) {
  100705. document.body.appendChild(this._btnVR);
  100706. this._btnVRDisplayed = true;
  100707. }
  100708. };
  100709. VRExperienceHelper.prototype.updateButtonVisibility = function () {
  100710. if (!this._btnVR || this._useCustomVRButton) {
  100711. return;
  100712. }
  100713. this._btnVR.className = "babylonVRicon";
  100714. if (this.isInVRMode) {
  100715. this._btnVR.className += " vrdisplaypresenting";
  100716. }
  100717. else {
  100718. if (this._webVRready)
  100719. this._btnVR.className += " vrdisplayready";
  100720. if (this._webVRsupported)
  100721. this._btnVR.className += " vrdisplaysupported";
  100722. if (this._webVRrequesting)
  100723. this._btnVR.className += " vrdisplayrequesting";
  100724. }
  100725. };
  100726. /**
  100727. * Attempt to enter VR. If a headset is connected and ready, will request present on that.
  100728. * Otherwise, will use the fullscreen API.
  100729. */
  100730. VRExperienceHelper.prototype.enterVR = function () {
  100731. if (this.onEnteringVRObservable) {
  100732. try {
  100733. this.onEnteringVRObservable.notifyObservers(this);
  100734. }
  100735. catch (err) {
  100736. BABYLON.Tools.Warn("Error in your custom logic onEnteringVR: " + err);
  100737. }
  100738. }
  100739. if (this._scene.activeCamera) {
  100740. this._position = this._scene.activeCamera.position.clone();
  100741. // make sure that we return to the last active camera
  100742. this._existingCamera = this._scene.activeCamera;
  100743. }
  100744. if (this._webVRrequesting)
  100745. return;
  100746. // If WebVR is supported and a headset is connected
  100747. if (this._webVRready) {
  100748. if (!this._webVRpresenting) {
  100749. this._webVRCamera.position = this._position;
  100750. this._scene.activeCamera = this._webVRCamera;
  100751. }
  100752. }
  100753. else if (this._vrDeviceOrientationCamera) {
  100754. this._vrDeviceOrientationCamera.position = this._position;
  100755. if (this._scene.activeCamera) {
  100756. this._vrDeviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  100757. }
  100758. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  100759. this._scene.getEngine().switchFullscreen(true);
  100760. this.updateButtonVisibility();
  100761. }
  100762. if (this._scene.activeCamera && this._canvas) {
  100763. this._scene.activeCamera.attachControl(this._canvas);
  100764. }
  100765. if (this._interactionsEnabled) {
  100766. this._scene.registerBeforeRender(this.beforeRender);
  100767. }
  100768. this._hasEnteredVR = true;
  100769. };
  100770. /**
  100771. * Attempt to exit VR, or fullscreen.
  100772. */
  100773. VRExperienceHelper.prototype.exitVR = function () {
  100774. if (this._hasEnteredVR) {
  100775. if (this.onExitingVRObservable) {
  100776. try {
  100777. this.onExitingVRObservable.notifyObservers(this);
  100778. }
  100779. catch (err) {
  100780. BABYLON.Tools.Warn("Error in your custom logic onExitingVR: " + err);
  100781. }
  100782. }
  100783. if (this._webVRpresenting) {
  100784. this._scene.getEngine().disableVR();
  100785. }
  100786. if (this._scene.activeCamera) {
  100787. this._position = this._scene.activeCamera.position.clone();
  100788. }
  100789. if (this._deviceOrientationCamera) {
  100790. this._deviceOrientationCamera.position = this._position;
  100791. this._scene.activeCamera = this._deviceOrientationCamera;
  100792. if (this._canvas) {
  100793. this._scene.activeCamera.attachControl(this._canvas);
  100794. }
  100795. }
  100796. else if (this._existingCamera) {
  100797. this._existingCamera.position = this._position;
  100798. this._scene.activeCamera = this._existingCamera;
  100799. }
  100800. this.updateButtonVisibility();
  100801. if (this._interactionsEnabled) {
  100802. this._scene.unregisterBeforeRender(this.beforeRender);
  100803. this._cameraGazer._gazeTracker.isVisible = false;
  100804. if (this._leftController) {
  100805. this._leftController._gazeTracker.isVisible = false;
  100806. }
  100807. if (this._rightController) {
  100808. this._rightController._gazeTracker.isVisible = false;
  100809. }
  100810. }
  100811. // resize to update width and height when exiting vr exits fullscreen
  100812. this._scene.getEngine().resize();
  100813. this._hasEnteredVR = false;
  100814. }
  100815. };
  100816. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  100817. /**
  100818. * The position of the vr experience helper.
  100819. */
  100820. get: function () {
  100821. return this._position;
  100822. },
  100823. /**
  100824. * Sets the position of the vr experience helper.
  100825. */
  100826. set: function (value) {
  100827. this._position = value;
  100828. if (this._scene.activeCamera) {
  100829. this._scene.activeCamera.position = value;
  100830. }
  100831. },
  100832. enumerable: true,
  100833. configurable: true
  100834. });
  100835. /**
  100836. * Enables controllers and user interactions such as selecting and object or clicking on an object.
  100837. */
  100838. VRExperienceHelper.prototype.enableInteractions = function () {
  100839. var _this = this;
  100840. if (!this._interactionsEnabled) {
  100841. this._interactionsRequested = true;
  100842. if (this._leftController) {
  100843. this._enableInteractionOnController(this._leftController);
  100844. }
  100845. if (this._rightController) {
  100846. this._enableInteractionOnController(this._rightController);
  100847. }
  100848. this.raySelectionPredicate = function (mesh) {
  100849. return mesh.isVisible && (mesh.isPickable || mesh.name === _this._floorMeshName);
  100850. };
  100851. this.meshSelectionPredicate = function (mesh) {
  100852. return true;
  100853. };
  100854. this._raySelectionPredicate = function (mesh) {
  100855. if (_this._isTeleportationFloor(mesh) || (mesh.name.indexOf("gazeTracker") === -1
  100856. && mesh.name.indexOf("teleportationTarget") === -1
  100857. && mesh.name.indexOf("torusTeleportation") === -1)) {
  100858. return _this.raySelectionPredicate(mesh);
  100859. }
  100860. return false;
  100861. };
  100862. this._interactionsEnabled = true;
  100863. }
  100864. };
  100865. Object.defineProperty(VRExperienceHelper.prototype, "_noControllerIsActive", {
  100866. get: function () {
  100867. return !(this._leftController && this._leftController._activePointer) && !(this._rightController && this._rightController._activePointer);
  100868. },
  100869. enumerable: true,
  100870. configurable: true
  100871. });
  100872. VRExperienceHelper.prototype._isTeleportationFloor = function (mesh) {
  100873. for (var i = 0; i < this._floorMeshesCollection.length; i++) {
  100874. if (this._floorMeshesCollection[i].id === mesh.id) {
  100875. return true;
  100876. }
  100877. }
  100878. if (this._floorMeshName && mesh.name === this._floorMeshName) {
  100879. return true;
  100880. }
  100881. return false;
  100882. };
  100883. /**
  100884. * Adds a floor mesh to be used for teleportation.
  100885. * @param floorMesh the mesh to be used for teleportation.
  100886. */
  100887. VRExperienceHelper.prototype.addFloorMesh = function (floorMesh) {
  100888. if (!this._floorMeshesCollection) {
  100889. return;
  100890. }
  100891. if (this._floorMeshesCollection.indexOf(floorMesh) > -1) {
  100892. return;
  100893. }
  100894. this._floorMeshesCollection.push(floorMesh);
  100895. };
  100896. /**
  100897. * Removes a floor mesh from being used for teleportation.
  100898. * @param floorMesh the mesh to be removed.
  100899. */
  100900. VRExperienceHelper.prototype.removeFloorMesh = function (floorMesh) {
  100901. if (!this._floorMeshesCollection) {
  100902. return;
  100903. }
  100904. var meshIndex = this._floorMeshesCollection.indexOf(floorMesh);
  100905. if (meshIndex !== -1) {
  100906. this._floorMeshesCollection.splice(meshIndex, 1);
  100907. }
  100908. };
  100909. /**
  100910. * Enables interactions and teleportation using the VR controllers and gaze.
  100911. * @param vrTeleportationOptions options to modify teleportation behavior.
  100912. */
  100913. VRExperienceHelper.prototype.enableTeleportation = function (vrTeleportationOptions) {
  100914. if (vrTeleportationOptions === void 0) { vrTeleportationOptions = {}; }
  100915. if (!this._teleportationInitialized) {
  100916. this._teleportationRequested = true;
  100917. this.enableInteractions();
  100918. if (vrTeleportationOptions.floorMeshName) {
  100919. this._floorMeshName = vrTeleportationOptions.floorMeshName;
  100920. }
  100921. if (vrTeleportationOptions.floorMeshes) {
  100922. this._floorMeshesCollection = vrTeleportationOptions.floorMeshes;
  100923. }
  100924. if (this._leftController != null) {
  100925. this._enableTeleportationOnController(this._leftController);
  100926. }
  100927. if (this._rightController != null) {
  100928. this._enableTeleportationOnController(this._rightController);
  100929. }
  100930. // Creates an image processing post process for the vignette not relying
  100931. // on the main scene configuration for image processing to reduce setup and spaces
  100932. // (gamma/linear) conflicts.
  100933. var imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  100934. imageProcessingConfiguration.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  100935. imageProcessingConfiguration.vignetteEnabled = true;
  100936. this._postProcessMove = new BABYLON.ImageProcessingPostProcess("postProcessMove", 1.0, this._webVRCamera, undefined, undefined, undefined, undefined, imageProcessingConfiguration);
  100937. this._webVRCamera.detachPostProcess(this._postProcessMove);
  100938. this._teleportationInitialized = true;
  100939. if (this._isDefaultTeleportationTarget) {
  100940. this._createTeleportationCircles();
  100941. this._teleportationTarget.scaling.scaleInPlace(this._webVRCamera.deviceScaleFactor);
  100942. }
  100943. }
  100944. };
  100945. VRExperienceHelper.prototype._enableInteractionOnController = function (controller) {
  100946. var _this = this;
  100947. var controllerMesh = controller.webVRController.mesh;
  100948. if (controllerMesh) {
  100949. controller._interactionsEnabled = true;
  100950. controller._activatePointer();
  100951. if (this.webVROptions.laserToggle) {
  100952. controller.webVRController.onMainButtonStateChangedObservable.add(function (stateObject) {
  100953. // Enabling / disabling laserPointer
  100954. if (_this._displayLaserPointer && stateObject.value === 1) {
  100955. if (controller._activePointer) {
  100956. controller._deactivatePointer();
  100957. }
  100958. else {
  100959. controller._activatePointer();
  100960. }
  100961. if (_this.displayGaze) {
  100962. controller._gazeTracker.isVisible = controller._activePointer;
  100963. }
  100964. }
  100965. });
  100966. }
  100967. controller.webVRController.onTriggerStateChangedObservable.add(function (stateObject) {
  100968. var gazer = controller;
  100969. if (_this._noControllerIsActive) {
  100970. gazer = _this._cameraGazer;
  100971. }
  100972. if (!gazer._pointerDownOnMeshAsked) {
  100973. if (stateObject.value > _this._padSensibilityUp) {
  100974. gazer._selectionPointerDown();
  100975. }
  100976. }
  100977. else if (stateObject.value < _this._padSensibilityDown) {
  100978. gazer._selectionPointerUp();
  100979. }
  100980. });
  100981. }
  100982. };
  100983. VRExperienceHelper.prototype._checkTeleportWithRay = function (stateObject, gazer) {
  100984. // Dont teleport if another gaze already requested teleportation
  100985. if (this._teleportationRequestInitiated && !gazer._teleportationRequestInitiated) {
  100986. return;
  100987. }
  100988. if (!gazer._teleportationRequestInitiated) {
  100989. if (stateObject.y < -this._padSensibilityUp && gazer._dpadPressed) {
  100990. gazer._activatePointer();
  100991. gazer._teleportationRequestInitiated = true;
  100992. }
  100993. }
  100994. else {
  100995. // Listening to the proper controller values changes to confirm teleportation
  100996. if (Math.sqrt(stateObject.y * stateObject.y + stateObject.x * stateObject.x) < this._padSensibilityDown) {
  100997. if (this._teleportActive) {
  100998. this.teleportCamera(this._haloCenter);
  100999. }
  101000. gazer._teleportationRequestInitiated = false;
  101001. }
  101002. }
  101003. };
  101004. VRExperienceHelper.prototype._checkRotate = function (stateObject, gazer) {
  101005. // Only rotate when user is not currently selecting a teleportation location
  101006. if (gazer._teleportationRequestInitiated) {
  101007. return;
  101008. }
  101009. if (!gazer._rotationLeftAsked) {
  101010. if (stateObject.x < -this._padSensibilityUp && gazer._dpadPressed) {
  101011. gazer._rotationLeftAsked = true;
  101012. if (this._rotationAllowed) {
  101013. this._rotateCamera(false);
  101014. }
  101015. }
  101016. }
  101017. else {
  101018. if (stateObject.x > -this._padSensibilityDown) {
  101019. gazer._rotationLeftAsked = false;
  101020. }
  101021. }
  101022. if (!gazer._rotationRightAsked) {
  101023. if (stateObject.x > this._padSensibilityUp && gazer._dpadPressed) {
  101024. gazer._rotationRightAsked = true;
  101025. if (this._rotationAllowed) {
  101026. this._rotateCamera(true);
  101027. }
  101028. }
  101029. }
  101030. else {
  101031. if (stateObject.x < this._padSensibilityDown) {
  101032. gazer._rotationRightAsked = false;
  101033. }
  101034. }
  101035. };
  101036. VRExperienceHelper.prototype._checkTeleportBackwards = function (stateObject, gazer) {
  101037. // Only teleport backwards when user is not currently selecting a teleportation location
  101038. if (gazer._teleportationRequestInitiated) {
  101039. return;
  101040. }
  101041. // Teleport backwards
  101042. if (stateObject.y > this._padSensibilityUp && gazer._dpadPressed) {
  101043. if (!gazer._teleportationBackRequestInitiated) {
  101044. if (!this.currentVRCamera) {
  101045. return;
  101046. }
  101047. // Get rotation and position of the current camera
  101048. var rotation = BABYLON.Quaternion.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix());
  101049. var position = this.currentVRCamera.position;
  101050. // If the camera has device position, use that instead
  101051. if (this.currentVRCamera.devicePosition && this.currentVRCamera.deviceRotationQuaternion) {
  101052. rotation = this.currentVRCamera.deviceRotationQuaternion;
  101053. position = this.currentVRCamera.devicePosition;
  101054. }
  101055. // Get matrix with only the y rotation of the device rotation
  101056. rotation.toEulerAnglesToRef(this._workingVector);
  101057. this._workingVector.z = 0;
  101058. this._workingVector.x = 0;
  101059. BABYLON.Quaternion.RotationYawPitchRollToRef(this._workingVector.y, this._workingVector.x, this._workingVector.z, this._workingQuaternion);
  101060. this._workingQuaternion.toRotationMatrix(this._workingMatrix);
  101061. // Rotate backwards ray by device rotation to cast at the ground behind the user
  101062. BABYLON.Vector3.TransformCoordinatesToRef(this._teleportBackwardsVector, this._workingMatrix, this._workingVector);
  101063. // Teleport if ray hit the ground and is not to far away eg. backwards off a cliff
  101064. var ray = new BABYLON.Ray(position, this._workingVector);
  101065. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  101066. if (hit && hit.pickedPoint && hit.pickedMesh && this._isTeleportationFloor(hit.pickedMesh) && hit.distance < 5) {
  101067. this.teleportCamera(hit.pickedPoint);
  101068. }
  101069. gazer._teleportationBackRequestInitiated = true;
  101070. }
  101071. }
  101072. else {
  101073. gazer._teleportationBackRequestInitiated = false;
  101074. }
  101075. };
  101076. VRExperienceHelper.prototype._enableTeleportationOnController = function (controller) {
  101077. var _this = this;
  101078. var controllerMesh = controller.webVRController.mesh;
  101079. if (controllerMesh) {
  101080. if (!controller._interactionsEnabled) {
  101081. this._enableInteractionOnController(controller);
  101082. }
  101083. controller._interactionsEnabled = true;
  101084. controller._teleportationEnabled = true;
  101085. if (controller.webVRController.controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  101086. controller._dpadPressed = false;
  101087. controller.webVRController.onPadStateChangedObservable.add(function (stateObject) {
  101088. controller._dpadPressed = stateObject.pressed;
  101089. if (!controller._dpadPressed) {
  101090. controller._rotationLeftAsked = false;
  101091. controller._rotationRightAsked = false;
  101092. controller._teleportationBackRequestInitiated = false;
  101093. }
  101094. });
  101095. }
  101096. controller.webVRController.onPadValuesChangedObservable.add(function (stateObject) {
  101097. if (_this.teleportationEnabled) {
  101098. _this._checkTeleportBackwards(stateObject, controller);
  101099. _this._checkTeleportWithRay(stateObject, controller);
  101100. }
  101101. _this._checkRotate(stateObject, controller);
  101102. });
  101103. }
  101104. };
  101105. VRExperienceHelper.prototype._createTeleportationCircles = function () {
  101106. this._teleportationTarget = BABYLON.Mesh.CreateGround("teleportationTarget", 2, 2, 2, this._scene);
  101107. this._teleportationTarget.isPickable = false;
  101108. var length = 512;
  101109. var dynamicTexture = new BABYLON.DynamicTexture("DynamicTexture", length, this._scene, true);
  101110. dynamicTexture.hasAlpha = true;
  101111. var context = dynamicTexture.getContext();
  101112. var centerX = length / 2;
  101113. var centerY = length / 2;
  101114. var radius = 200;
  101115. context.beginPath();
  101116. context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
  101117. context.fillStyle = this._teleportationFillColor;
  101118. context.fill();
  101119. context.lineWidth = 10;
  101120. context.strokeStyle = this._teleportationBorderColor;
  101121. context.stroke();
  101122. context.closePath();
  101123. dynamicTexture.update();
  101124. var teleportationCircleMaterial = new BABYLON.StandardMaterial("TextPlaneMaterial", this._scene);
  101125. teleportationCircleMaterial.diffuseTexture = dynamicTexture;
  101126. this._teleportationTarget.material = teleportationCircleMaterial;
  101127. var torus = BABYLON.Mesh.CreateTorus("torusTeleportation", 0.75, 0.1, 25, this._scene, false);
  101128. torus.isPickable = false;
  101129. torus.parent = this._teleportationTarget;
  101130. var animationInnerCircle = new BABYLON.Animation("animationInnerCircle", "position.y", 30, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  101131. var keys = [];
  101132. keys.push({
  101133. frame: 0,
  101134. value: 0
  101135. });
  101136. keys.push({
  101137. frame: 30,
  101138. value: 0.4
  101139. });
  101140. keys.push({
  101141. frame: 60,
  101142. value: 0
  101143. });
  101144. animationInnerCircle.setKeys(keys);
  101145. var easingFunction = new BABYLON.SineEase();
  101146. easingFunction.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  101147. animationInnerCircle.setEasingFunction(easingFunction);
  101148. torus.animations = [];
  101149. torus.animations.push(animationInnerCircle);
  101150. this._scene.beginAnimation(torus, 0, 60, true);
  101151. this._hideTeleportationTarget();
  101152. };
  101153. VRExperienceHelper.prototype._displayTeleportationTarget = function () {
  101154. this._teleportActive = true;
  101155. if (this._teleportationInitialized) {
  101156. this._teleportationTarget.isVisible = true;
  101157. if (this._isDefaultTeleportationTarget) {
  101158. this._teleportationTarget.getChildren()[0].isVisible = true;
  101159. }
  101160. }
  101161. };
  101162. VRExperienceHelper.prototype._hideTeleportationTarget = function () {
  101163. this._teleportActive = false;
  101164. if (this._teleportationInitialized) {
  101165. this._teleportationTarget.isVisible = false;
  101166. if (this._isDefaultTeleportationTarget) {
  101167. this._teleportationTarget.getChildren()[0].isVisible = false;
  101168. }
  101169. }
  101170. };
  101171. VRExperienceHelper.prototype._rotateCamera = function (right) {
  101172. var _this = this;
  101173. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  101174. return;
  101175. }
  101176. if (right) {
  101177. this._rotationAngle++;
  101178. }
  101179. else {
  101180. this._rotationAngle--;
  101181. }
  101182. this.currentVRCamera.animations = [];
  101183. var target = BABYLON.Quaternion.FromRotationMatrix(BABYLON.Matrix.RotationY(Math.PI / 4 * this._rotationAngle));
  101184. var animationRotation = new BABYLON.Animation("animationRotation", "rotationQuaternion", 90, BABYLON.Animation.ANIMATIONTYPE_QUATERNION, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  101185. var animationRotationKeys = [];
  101186. animationRotationKeys.push({
  101187. frame: 0,
  101188. value: this.currentVRCamera.rotationQuaternion
  101189. });
  101190. animationRotationKeys.push({
  101191. frame: 6,
  101192. value: target
  101193. });
  101194. animationRotation.setKeys(animationRotationKeys);
  101195. animationRotation.setEasingFunction(this._circleEase);
  101196. this.currentVRCamera.animations.push(animationRotation);
  101197. this._postProcessMove.animations = [];
  101198. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  101199. var vignetteWeightKeys = [];
  101200. vignetteWeightKeys.push({
  101201. frame: 0,
  101202. value: 0
  101203. });
  101204. vignetteWeightKeys.push({
  101205. frame: 3,
  101206. value: 4
  101207. });
  101208. vignetteWeightKeys.push({
  101209. frame: 6,
  101210. value: 0
  101211. });
  101212. animationPP.setKeys(vignetteWeightKeys);
  101213. animationPP.setEasingFunction(this._circleEase);
  101214. this._postProcessMove.animations.push(animationPP);
  101215. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  101216. var vignetteStretchKeys = [];
  101217. vignetteStretchKeys.push({
  101218. frame: 0,
  101219. value: 0
  101220. });
  101221. vignetteStretchKeys.push({
  101222. frame: 3,
  101223. value: 10
  101224. });
  101225. vignetteStretchKeys.push({
  101226. frame: 6,
  101227. value: 0
  101228. });
  101229. animationPP2.setKeys(vignetteStretchKeys);
  101230. animationPP2.setEasingFunction(this._circleEase);
  101231. this._postProcessMove.animations.push(animationPP2);
  101232. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  101233. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  101234. this._postProcessMove.samples = 4;
  101235. this._webVRCamera.attachPostProcess(this._postProcessMove);
  101236. this._scene.beginAnimation(this._postProcessMove, 0, 6, false, 1, function () {
  101237. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  101238. });
  101239. this._scene.beginAnimation(this.currentVRCamera, 0, 6, false, 1);
  101240. };
  101241. VRExperienceHelper.prototype._moveTeleportationSelectorTo = function (hit, gazer, ray) {
  101242. if (hit.pickedPoint) {
  101243. if (gazer._teleportationRequestInitiated) {
  101244. this._displayTeleportationTarget();
  101245. this._haloCenter.copyFrom(hit.pickedPoint);
  101246. this._teleportationTarget.position.copyFrom(hit.pickedPoint);
  101247. }
  101248. var pickNormal = this._convertNormalToDirectionOfRay(hit.getNormal(true, false), ray);
  101249. if (pickNormal) {
  101250. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  101251. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  101252. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._teleportationTarget.rotation);
  101253. }
  101254. this._teleportationTarget.position.y += 0.1;
  101255. }
  101256. };
  101257. /**
  101258. * Teleports the users feet to the desired location
  101259. * @param location The location where the user's feet should be placed
  101260. */
  101261. VRExperienceHelper.prototype.teleportCamera = function (location) {
  101262. var _this = this;
  101263. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  101264. return;
  101265. }
  101266. // Teleport the hmd to where the user is looking by moving the anchor to where they are looking minus the
  101267. // offset of the headset from the anchor.
  101268. if (this.webVRCamera.leftCamera) {
  101269. this._workingVector.copyFrom(this.webVRCamera.leftCamera.globalPosition);
  101270. this._workingVector.subtractInPlace(this.webVRCamera.position);
  101271. location.subtractToRef(this._workingVector, this._workingVector);
  101272. }
  101273. else {
  101274. this._workingVector.copyFrom(location);
  101275. }
  101276. // Add height to account for user's height offset
  101277. if (this.isInVRMode) {
  101278. this._workingVector.y += this.webVRCamera.deviceDistanceToRoomGround() * this._webVRCamera.deviceScaleFactor;
  101279. }
  101280. else {
  101281. this._workingVector.y += this._defaultHeight;
  101282. }
  101283. this.onBeforeCameraTeleport.notifyObservers(this._workingVector);
  101284. // Create animation from the camera's position to the new location
  101285. this.currentVRCamera.animations = [];
  101286. var animationCameraTeleportation = new BABYLON.Animation("animationCameraTeleportation", "position", 90, BABYLON.Animation.ANIMATIONTYPE_VECTOR3, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  101287. var animationCameraTeleportationKeys = [{
  101288. frame: 0,
  101289. value: this.currentVRCamera.position
  101290. },
  101291. {
  101292. frame: 11,
  101293. value: this._workingVector
  101294. }
  101295. ];
  101296. animationCameraTeleportation.setKeys(animationCameraTeleportationKeys);
  101297. animationCameraTeleportation.setEasingFunction(this._circleEase);
  101298. this.currentVRCamera.animations.push(animationCameraTeleportation);
  101299. this._postProcessMove.animations = [];
  101300. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  101301. var vignetteWeightKeys = [];
  101302. vignetteWeightKeys.push({
  101303. frame: 0,
  101304. value: 0
  101305. });
  101306. vignetteWeightKeys.push({
  101307. frame: 5,
  101308. value: 8
  101309. });
  101310. vignetteWeightKeys.push({
  101311. frame: 11,
  101312. value: 0
  101313. });
  101314. animationPP.setKeys(vignetteWeightKeys);
  101315. this._postProcessMove.animations.push(animationPP);
  101316. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  101317. var vignetteStretchKeys = [];
  101318. vignetteStretchKeys.push({
  101319. frame: 0,
  101320. value: 0
  101321. });
  101322. vignetteStretchKeys.push({
  101323. frame: 5,
  101324. value: 10
  101325. });
  101326. vignetteStretchKeys.push({
  101327. frame: 11,
  101328. value: 0
  101329. });
  101330. animationPP2.setKeys(vignetteStretchKeys);
  101331. this._postProcessMove.animations.push(animationPP2);
  101332. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  101333. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  101334. this._webVRCamera.attachPostProcess(this._postProcessMove);
  101335. this._scene.beginAnimation(this._postProcessMove, 0, 11, false, 1, function () {
  101336. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  101337. });
  101338. this._scene.beginAnimation(this.currentVRCamera, 0, 11, false, 1, function () {
  101339. _this.onAfterCameraTeleport.notifyObservers(_this._workingVector);
  101340. });
  101341. this._hideTeleportationTarget();
  101342. };
  101343. VRExperienceHelper.prototype._convertNormalToDirectionOfRay = function (normal, ray) {
  101344. if (normal) {
  101345. var angle = Math.acos(BABYLON.Vector3.Dot(normal, ray.direction));
  101346. if (angle < Math.PI / 2) {
  101347. normal.scaleInPlace(-1);
  101348. }
  101349. }
  101350. return normal;
  101351. };
  101352. VRExperienceHelper.prototype._castRayAndSelectObject = function (gazer) {
  101353. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  101354. return;
  101355. }
  101356. var ray = gazer._getForwardRay(this._rayLength);
  101357. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  101358. if (hit) {
  101359. // Populate the contrllers mesh that can be used for drag/drop
  101360. if (gazer._laserPointer) {
  101361. hit.originMesh = gazer._laserPointer.parent;
  101362. }
  101363. this._scene.simulatePointerMove(hit, { pointerId: gazer._id });
  101364. }
  101365. gazer._currentHit = hit;
  101366. // Moving the gazeTracker on the mesh face targetted
  101367. if (hit && hit.pickedPoint) {
  101368. if (this._displayGaze) {
  101369. var multiplier = 1;
  101370. gazer._gazeTracker.isVisible = true;
  101371. if (gazer._isActionableMesh) {
  101372. multiplier = 3;
  101373. }
  101374. if (this.updateGazeTrackerScale) {
  101375. gazer._gazeTracker.scaling.x = hit.distance * multiplier;
  101376. gazer._gazeTracker.scaling.y = hit.distance * multiplier;
  101377. gazer._gazeTracker.scaling.z = hit.distance * multiplier;
  101378. }
  101379. var pickNormal = this._convertNormalToDirectionOfRay(hit.getNormal(), ray);
  101380. // To avoid z-fighting
  101381. var deltaFighting = 0.002;
  101382. if (pickNormal) {
  101383. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  101384. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  101385. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, gazer._gazeTracker.rotation);
  101386. }
  101387. gazer._gazeTracker.position.copyFrom(hit.pickedPoint);
  101388. if (gazer._gazeTracker.position.x < 0) {
  101389. gazer._gazeTracker.position.x += deltaFighting;
  101390. }
  101391. else {
  101392. gazer._gazeTracker.position.x -= deltaFighting;
  101393. }
  101394. if (gazer._gazeTracker.position.y < 0) {
  101395. gazer._gazeTracker.position.y += deltaFighting;
  101396. }
  101397. else {
  101398. gazer._gazeTracker.position.y -= deltaFighting;
  101399. }
  101400. if (gazer._gazeTracker.position.z < 0) {
  101401. gazer._gazeTracker.position.z += deltaFighting;
  101402. }
  101403. else {
  101404. gazer._gazeTracker.position.z -= deltaFighting;
  101405. }
  101406. }
  101407. // Changing the size of the laser pointer based on the distance from the targetted point
  101408. gazer._updatePointerDistance(hit.distance);
  101409. }
  101410. else {
  101411. gazer._updatePointerDistance();
  101412. gazer._gazeTracker.isVisible = false;
  101413. }
  101414. if (hit && hit.pickedMesh) {
  101415. // The object selected is the floor, we're in a teleportation scenario
  101416. if (this._teleportationInitialized && this._isTeleportationFloor(hit.pickedMesh) && hit.pickedPoint) {
  101417. // Moving the teleportation area to this targetted point
  101418. //Raise onSelectedMeshUnselected observable if ray collided floor mesh/meshes and a non floor mesh was previously selected
  101419. if (gazer._currentMeshSelected && !this._isTeleportationFloor(gazer._currentMeshSelected)) {
  101420. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  101421. }
  101422. gazer._currentMeshSelected = null;
  101423. if (gazer._teleportationRequestInitiated) {
  101424. this._moveTeleportationSelectorTo(hit, gazer, ray);
  101425. }
  101426. return;
  101427. }
  101428. // If not, we're in a selection scenario
  101429. //this._teleportationAllowed = false;
  101430. if (hit.pickedMesh !== gazer._currentMeshSelected) {
  101431. if (this.meshSelectionPredicate(hit.pickedMesh)) {
  101432. this.onNewMeshPicked.notifyObservers(hit);
  101433. gazer._currentMeshSelected = hit.pickedMesh;
  101434. if (hit.pickedMesh.isPickable && hit.pickedMesh.actionManager) {
  101435. this.changeGazeColor(new BABYLON.Color3(0, 0, 1));
  101436. this.changeLaserColor(new BABYLON.Color3(0.2, 0.2, 1));
  101437. gazer._isActionableMesh = true;
  101438. }
  101439. else {
  101440. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  101441. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  101442. gazer._isActionableMesh = false;
  101443. }
  101444. try {
  101445. this.onNewMeshSelected.notifyObservers(hit.pickedMesh);
  101446. }
  101447. catch (err) {
  101448. BABYLON.Tools.Warn("Error in your custom logic onNewMeshSelected: " + err);
  101449. }
  101450. }
  101451. else {
  101452. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  101453. gazer._currentMeshSelected = null;
  101454. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  101455. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  101456. }
  101457. }
  101458. }
  101459. else {
  101460. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  101461. gazer._currentMeshSelected = null;
  101462. //this._teleportationAllowed = false;
  101463. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  101464. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  101465. }
  101466. };
  101467. VRExperienceHelper.prototype._notifySelectedMeshUnselected = function (mesh) {
  101468. if (mesh) {
  101469. this.onSelectedMeshUnselected.notifyObservers(mesh);
  101470. }
  101471. };
  101472. /**
  101473. * Sets the color of the laser ray from the vr controllers.
  101474. * @param color new color for the ray.
  101475. */
  101476. VRExperienceHelper.prototype.changeLaserColor = function (color) {
  101477. if (this._leftController) {
  101478. this._leftController._setLaserPointerColor(color);
  101479. }
  101480. if (this._rightController) {
  101481. this._rightController._setLaserPointerColor(color);
  101482. }
  101483. };
  101484. /**
  101485. * Sets the color of the ray from the vr headsets gaze.
  101486. * @param color new color for the ray.
  101487. */
  101488. VRExperienceHelper.prototype.changeGazeColor = function (color) {
  101489. if (!this._cameraGazer._gazeTracker.material) {
  101490. return;
  101491. }
  101492. this._cameraGazer._gazeTracker.material.emissiveColor = color;
  101493. if (this._leftController) {
  101494. this._leftController._gazeTracker.material.emissiveColor = color;
  101495. }
  101496. if (this._rightController) {
  101497. this._rightController._gazeTracker.material.emissiveColor = color;
  101498. }
  101499. };
  101500. /**
  101501. * Exits VR and disposes of the vr experience helper
  101502. */
  101503. VRExperienceHelper.prototype.dispose = function () {
  101504. if (this.isInVRMode) {
  101505. this.exitVR();
  101506. }
  101507. if (this._postProcessMove) {
  101508. this._postProcessMove.dispose();
  101509. }
  101510. if (this._webVRCamera) {
  101511. this._webVRCamera.dispose();
  101512. }
  101513. if (this._vrDeviceOrientationCamera) {
  101514. this._vrDeviceOrientationCamera.dispose();
  101515. }
  101516. if (!this._useCustomVRButton && this._btnVR.parentNode) {
  101517. document.body.removeChild(this._btnVR);
  101518. }
  101519. if (this._deviceOrientationCamera && (this._scene.activeCamera != this._deviceOrientationCamera)) {
  101520. this._deviceOrientationCamera.dispose();
  101521. }
  101522. if (this._cameraGazer) {
  101523. this._cameraGazer.dispose();
  101524. }
  101525. if (this._leftController) {
  101526. this._leftController.dispose();
  101527. }
  101528. if (this._rightController) {
  101529. this._rightController.dispose();
  101530. }
  101531. if (this._teleportationTarget) {
  101532. this._teleportationTarget.dispose();
  101533. }
  101534. this._floorMeshesCollection = [];
  101535. document.removeEventListener("keydown", this._onKeyDown);
  101536. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  101537. window.removeEventListener("resize", this._onResize);
  101538. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  101539. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  101540. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  101541. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  101542. document.onmsfullscreenchange = null;
  101543. this._scene.getEngine().onVRDisplayChangedObservable.removeCallback(this._onVRDisplayChanged);
  101544. this._scene.getEngine().onVRRequestPresentStart.removeCallback(this._onVRRequestPresentStart);
  101545. this._scene.getEngine().onVRRequestPresentComplete.removeCallback(this._onVRRequestPresentComplete);
  101546. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  101547. this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected);
  101548. this._scene.gamepadManager.onGamepadDisconnectedObservable.removeCallback(this._onNewGamepadDisconnected);
  101549. this._scene.unregisterBeforeRender(this.beforeRender);
  101550. };
  101551. /**
  101552. * Gets the name of the VRExperienceHelper class
  101553. * @returns "VRExperienceHelper"
  101554. */
  101555. VRExperienceHelper.prototype.getClassName = function () {
  101556. return "VRExperienceHelper";
  101557. };
  101558. return VRExperienceHelper;
  101559. }());
  101560. BABYLON.VRExperienceHelper = VRExperienceHelper;
  101561. })(BABYLON || (BABYLON = {}));
  101562. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  101563. // Mainly based on these 2 articles :
  101564. // 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
  101565. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  101566. var BABYLON;
  101567. (function (BABYLON) {
  101568. /**
  101569. * Defines the potential axis of a Joystick
  101570. */
  101571. var JoystickAxis;
  101572. (function (JoystickAxis) {
  101573. /** X axis */
  101574. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  101575. /** Y axis */
  101576. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  101577. /** Z axis */
  101578. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  101579. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  101580. /**
  101581. * Class used to define virtual joystick (used in touch mode)
  101582. */
  101583. var VirtualJoystick = /** @class */ (function () {
  101584. /**
  101585. * Creates a new virtual joystick
  101586. * @param leftJoystick defines that the joystick is for left hand (false by default)
  101587. */
  101588. function VirtualJoystick(leftJoystick) {
  101589. var _this = this;
  101590. if (leftJoystick) {
  101591. this._leftJoystick = true;
  101592. }
  101593. else {
  101594. this._leftJoystick = false;
  101595. }
  101596. VirtualJoystick._globalJoystickIndex++;
  101597. // By default left & right arrow keys are moving the X
  101598. // and up & down keys are moving the Y
  101599. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  101600. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  101601. this.reverseLeftRight = false;
  101602. this.reverseUpDown = false;
  101603. // collections of pointers
  101604. this._touches = new BABYLON.StringDictionary();
  101605. this.deltaPosition = BABYLON.Vector3.Zero();
  101606. this._joystickSensibility = 25;
  101607. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  101608. this._onResize = function (evt) {
  101609. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  101610. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  101611. if (VirtualJoystick.vjCanvas) {
  101612. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  101613. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  101614. }
  101615. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  101616. };
  101617. // injecting a canvas element on top of the canvas 3D game
  101618. if (!VirtualJoystick.vjCanvas) {
  101619. window.addEventListener("resize", this._onResize, false);
  101620. VirtualJoystick.vjCanvas = document.createElement("canvas");
  101621. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  101622. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  101623. VirtualJoystick.vjCanvas.width = window.innerWidth;
  101624. VirtualJoystick.vjCanvas.height = window.innerHeight;
  101625. VirtualJoystick.vjCanvas.style.width = "100%";
  101626. VirtualJoystick.vjCanvas.style.height = "100%";
  101627. VirtualJoystick.vjCanvas.style.position = "absolute";
  101628. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  101629. VirtualJoystick.vjCanvas.style.top = "0px";
  101630. VirtualJoystick.vjCanvas.style.left = "0px";
  101631. VirtualJoystick.vjCanvas.style.zIndex = "5";
  101632. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  101633. // Support for jQuery PEP polyfill
  101634. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  101635. var context = VirtualJoystick.vjCanvas.getContext('2d');
  101636. if (!context) {
  101637. throw new Error("Unable to create canvas for virtual joystick");
  101638. }
  101639. VirtualJoystick.vjCanvasContext = context;
  101640. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  101641. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  101642. document.body.appendChild(VirtualJoystick.vjCanvas);
  101643. }
  101644. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  101645. this.pressed = false;
  101646. // default joystick color
  101647. this._joystickColor = "cyan";
  101648. this._joystickPointerID = -1;
  101649. // current joystick position
  101650. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  101651. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  101652. // origin joystick position
  101653. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  101654. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  101655. this._onPointerDownHandlerRef = function (evt) {
  101656. _this._onPointerDown(evt);
  101657. };
  101658. this._onPointerMoveHandlerRef = function (evt) {
  101659. _this._onPointerMove(evt);
  101660. };
  101661. this._onPointerUpHandlerRef = function (evt) {
  101662. _this._onPointerUp(evt);
  101663. };
  101664. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  101665. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  101666. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  101667. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  101668. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  101669. evt.preventDefault(); // Disables system menu
  101670. }, false);
  101671. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  101672. }
  101673. /**
  101674. * Defines joystick sensibility (ie. the ratio beteen a physical move and virtual joystick position change)
  101675. * @param newJoystickSensibility defines the new sensibility
  101676. */
  101677. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  101678. this._joystickSensibility = newJoystickSensibility;
  101679. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  101680. };
  101681. VirtualJoystick.prototype._onPointerDown = function (e) {
  101682. var positionOnScreenCondition;
  101683. e.preventDefault();
  101684. if (this._leftJoystick === true) {
  101685. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  101686. }
  101687. else {
  101688. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  101689. }
  101690. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  101691. // First contact will be dedicated to the virtual joystick
  101692. this._joystickPointerID = e.pointerId;
  101693. this._joystickPointerStartPos.x = e.clientX;
  101694. this._joystickPointerStartPos.y = e.clientY;
  101695. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  101696. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  101697. this._deltaJoystickVector.x = 0;
  101698. this._deltaJoystickVector.y = 0;
  101699. this.pressed = true;
  101700. this._touches.add(e.pointerId.toString(), e);
  101701. }
  101702. else {
  101703. // You can only trigger the action buttons with a joystick declared
  101704. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  101705. this._action();
  101706. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  101707. }
  101708. }
  101709. };
  101710. VirtualJoystick.prototype._onPointerMove = function (e) {
  101711. // If the current pointer is the one associated to the joystick (first touch contact)
  101712. if (this._joystickPointerID == e.pointerId) {
  101713. this._joystickPointerPos.x = e.clientX;
  101714. this._joystickPointerPos.y = e.clientY;
  101715. this._deltaJoystickVector = this._joystickPointerPos.clone();
  101716. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  101717. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  101718. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  101719. switch (this._axisTargetedByLeftAndRight) {
  101720. case JoystickAxis.X:
  101721. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  101722. break;
  101723. case JoystickAxis.Y:
  101724. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  101725. break;
  101726. case JoystickAxis.Z:
  101727. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  101728. break;
  101729. }
  101730. var directionUpDown = this.reverseUpDown ? 1 : -1;
  101731. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  101732. switch (this._axisTargetedByUpAndDown) {
  101733. case JoystickAxis.X:
  101734. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  101735. break;
  101736. case JoystickAxis.Y:
  101737. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  101738. break;
  101739. case JoystickAxis.Z:
  101740. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  101741. break;
  101742. }
  101743. }
  101744. else {
  101745. var data = this._touches.get(e.pointerId.toString());
  101746. if (data) {
  101747. data.x = e.clientX;
  101748. data.y = e.clientY;
  101749. }
  101750. }
  101751. };
  101752. VirtualJoystick.prototype._onPointerUp = function (e) {
  101753. if (this._joystickPointerID == e.pointerId) {
  101754. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  101755. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  101756. this._joystickPointerID = -1;
  101757. this.pressed = false;
  101758. }
  101759. else {
  101760. var touch = this._touches.get(e.pointerId.toString());
  101761. if (touch) {
  101762. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  101763. }
  101764. }
  101765. this._deltaJoystickVector.x = 0;
  101766. this._deltaJoystickVector.y = 0;
  101767. this._touches.remove(e.pointerId.toString());
  101768. };
  101769. /**
  101770. * Change the color of the virtual joystick
  101771. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  101772. */
  101773. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  101774. this._joystickColor = newColor;
  101775. };
  101776. /**
  101777. * Defines a callback to call when the joystick is touched
  101778. * @param action defines the callback
  101779. */
  101780. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  101781. this._action = action;
  101782. };
  101783. /**
  101784. * Defines which axis you'd like to control for left & right
  101785. * @param axis defines the axis to use
  101786. */
  101787. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  101788. switch (axis) {
  101789. case JoystickAxis.X:
  101790. case JoystickAxis.Y:
  101791. case JoystickAxis.Z:
  101792. this._axisTargetedByLeftAndRight = axis;
  101793. break;
  101794. default:
  101795. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  101796. break;
  101797. }
  101798. };
  101799. /**
  101800. * Defines which axis you'd like to control for up & down
  101801. * @param axis defines the axis to use
  101802. */
  101803. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  101804. switch (axis) {
  101805. case JoystickAxis.X:
  101806. case JoystickAxis.Y:
  101807. case JoystickAxis.Z:
  101808. this._axisTargetedByUpAndDown = axis;
  101809. break;
  101810. default:
  101811. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  101812. break;
  101813. }
  101814. };
  101815. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  101816. var _this = this;
  101817. if (this.pressed) {
  101818. this._touches.forEach(function (key, touch) {
  101819. if (touch.pointerId === _this._joystickPointerID) {
  101820. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  101821. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  101822. VirtualJoystick.vjCanvasContext.beginPath();
  101823. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  101824. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  101825. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  101826. VirtualJoystick.vjCanvasContext.stroke();
  101827. VirtualJoystick.vjCanvasContext.closePath();
  101828. VirtualJoystick.vjCanvasContext.beginPath();
  101829. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  101830. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  101831. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  101832. VirtualJoystick.vjCanvasContext.stroke();
  101833. VirtualJoystick.vjCanvasContext.closePath();
  101834. VirtualJoystick.vjCanvasContext.beginPath();
  101835. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  101836. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  101837. VirtualJoystick.vjCanvasContext.stroke();
  101838. VirtualJoystick.vjCanvasContext.closePath();
  101839. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  101840. }
  101841. else {
  101842. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  101843. VirtualJoystick.vjCanvasContext.beginPath();
  101844. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  101845. VirtualJoystick.vjCanvasContext.beginPath();
  101846. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  101847. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  101848. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  101849. VirtualJoystick.vjCanvasContext.stroke();
  101850. VirtualJoystick.vjCanvasContext.closePath();
  101851. touch.prevX = touch.x;
  101852. touch.prevY = touch.y;
  101853. }
  101854. ;
  101855. });
  101856. }
  101857. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  101858. };
  101859. /**
  101860. * Release internal HTML canvas
  101861. */
  101862. VirtualJoystick.prototype.releaseCanvas = function () {
  101863. if (VirtualJoystick.vjCanvas) {
  101864. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  101865. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  101866. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  101867. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  101868. window.removeEventListener("resize", this._onResize);
  101869. document.body.removeChild(VirtualJoystick.vjCanvas);
  101870. VirtualJoystick.vjCanvas = null;
  101871. }
  101872. };
  101873. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  101874. VirtualJoystick._globalJoystickIndex = 0;
  101875. return VirtualJoystick;
  101876. }());
  101877. BABYLON.VirtualJoystick = VirtualJoystick;
  101878. })(BABYLON || (BABYLON = {}));
  101879. //# sourceMappingURL=babylon.virtualJoystick.js.map
  101880. var BABYLON;
  101881. (function (BABYLON) {
  101882. BABYLON.Node.AddNodeConstructor("VirtualJoysticksCamera", function (name, scene) {
  101883. return function () { return new VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  101884. });
  101885. /**
  101886. * This represents a free type of camera. It can be usefull in First Person Shooter game for instance.
  101887. * It is identical to the Free Camera and simply adds by default a virtual joystick.
  101888. * Virtual Joysticks are on-screen 2D graphics that are used to control the camera or other scene items.
  101889. * @see http://doc.babylonjs.com/features/cameras#virtual-joysticks-camera
  101890. */
  101891. var VirtualJoysticksCamera = /** @class */ (function (_super) {
  101892. __extends(VirtualJoysticksCamera, _super);
  101893. /**
  101894. * Intantiates a VirtualJoysticksCamera. It can be usefull in First Person Shooter game for instance.
  101895. * It is identical to the Free Camera and simply adds by default a virtual joystick.
  101896. * Virtual Joysticks are on-screen 2D graphics that are used to control the camera or other scene items.
  101897. * @see http://doc.babylonjs.com/features/cameras#virtual-joysticks-camera
  101898. * @param name Define the name of the camera in the scene
  101899. * @param position Define the start position of the camera in the scene
  101900. * @param scene Define the scene the camera belongs to
  101901. */
  101902. function VirtualJoysticksCamera(name, position, scene) {
  101903. var _this = _super.call(this, name, position, scene) || this;
  101904. _this.inputs.addVirtualJoystick();
  101905. return _this;
  101906. }
  101907. /**
  101908. * Gets the current object class name.
  101909. * @return the class name
  101910. */
  101911. VirtualJoysticksCamera.prototype.getClassName = function () {
  101912. return "VirtualJoysticksCamera";
  101913. };
  101914. return VirtualJoysticksCamera;
  101915. }(BABYLON.FreeCamera));
  101916. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  101917. })(BABYLON || (BABYLON = {}));
  101918. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  101919. var BABYLON;
  101920. (function (BABYLON) {
  101921. /**
  101922. * Manage the Virtual Joystick inputs to control the movement of a free camera.
  101923. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  101924. */
  101925. var FreeCameraVirtualJoystickInput = /** @class */ (function () {
  101926. function FreeCameraVirtualJoystickInput() {
  101927. }
  101928. /**
  101929. * Gets the left stick of the virtual joystick.
  101930. * @returns The virtual Joystick
  101931. */
  101932. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  101933. return this._leftjoystick;
  101934. };
  101935. /**
  101936. * Gets the right stick of the virtual joystick.
  101937. * @returns The virtual Joystick
  101938. */
  101939. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  101940. return this._rightjoystick;
  101941. };
  101942. /**
  101943. * Update the current camera state depending on the inputs that have been used this frame.
  101944. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
  101945. */
  101946. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  101947. if (this._leftjoystick) {
  101948. var camera = this.camera;
  101949. var speed = camera._computeLocalCameraSpeed() * 50;
  101950. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  101951. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  101952. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  101953. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  101954. if (!this._leftjoystick.pressed) {
  101955. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  101956. }
  101957. if (!this._rightjoystick.pressed) {
  101958. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  101959. }
  101960. }
  101961. };
  101962. /**
  101963. * Attach the input controls to a specific dom element to get the input from.
  101964. * @param element Defines the element the controls should be listened from
  101965. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  101966. */
  101967. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  101968. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  101969. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  101970. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  101971. this._leftjoystick.setJoystickSensibility(0.15);
  101972. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  101973. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  101974. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  101975. this._rightjoystick.reverseUpDown = true;
  101976. this._rightjoystick.setJoystickSensibility(0.05);
  101977. this._rightjoystick.setJoystickColor("yellow");
  101978. };
  101979. /**
  101980. * Detach the current controls from the specified dom element.
  101981. * @param element Defines the element to stop listening the inputs from
  101982. */
  101983. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  101984. this._leftjoystick.releaseCanvas();
  101985. this._rightjoystick.releaseCanvas();
  101986. };
  101987. /**
  101988. * Gets the class name of the current intput.
  101989. * @returns the class name
  101990. */
  101991. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  101992. return "FreeCameraVirtualJoystickInput";
  101993. };
  101994. /**
  101995. * Get the friendly name associated with the input class.
  101996. * @returns the input friendly name
  101997. */
  101998. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  101999. return "virtualJoystick";
  102000. };
  102001. return FreeCameraVirtualJoystickInput;
  102002. }());
  102003. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  102004. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  102005. })(BABYLON || (BABYLON = {}));
  102006. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  102007. var BABYLON;
  102008. (function (BABYLON) {
  102009. var SimplificationSettings = /** @class */ (function () {
  102010. function SimplificationSettings(quality, distance, optimizeMesh) {
  102011. this.quality = quality;
  102012. this.distance = distance;
  102013. this.optimizeMesh = optimizeMesh;
  102014. }
  102015. return SimplificationSettings;
  102016. }());
  102017. BABYLON.SimplificationSettings = SimplificationSettings;
  102018. var SimplificationQueue = /** @class */ (function () {
  102019. function SimplificationQueue() {
  102020. this.running = false;
  102021. this._simplificationArray = [];
  102022. }
  102023. SimplificationQueue.prototype.addTask = function (task) {
  102024. this._simplificationArray.push(task);
  102025. };
  102026. SimplificationQueue.prototype.executeNext = function () {
  102027. var task = this._simplificationArray.pop();
  102028. if (task) {
  102029. this.running = true;
  102030. this.runSimplification(task);
  102031. }
  102032. else {
  102033. this.running = false;
  102034. }
  102035. };
  102036. SimplificationQueue.prototype.runSimplification = function (task) {
  102037. var _this = this;
  102038. if (task.parallelProcessing) {
  102039. //parallel simplifier
  102040. task.settings.forEach(function (setting) {
  102041. var simplifier = _this.getSimplifier(task);
  102042. simplifier.simplify(setting, function (newMesh) {
  102043. task.mesh.addLODLevel(setting.distance, newMesh);
  102044. newMesh.isVisible = true;
  102045. //check if it is the last
  102046. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  102047. //all done, run the success callback.
  102048. task.successCallback();
  102049. }
  102050. _this.executeNext();
  102051. });
  102052. });
  102053. }
  102054. else {
  102055. //single simplifier.
  102056. var simplifier = this.getSimplifier(task);
  102057. var runDecimation = function (setting, callback) {
  102058. simplifier.simplify(setting, function (newMesh) {
  102059. task.mesh.addLODLevel(setting.distance, newMesh);
  102060. newMesh.isVisible = true;
  102061. //run the next quality level
  102062. callback();
  102063. });
  102064. };
  102065. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  102066. runDecimation(task.settings[loop.index], function () {
  102067. loop.executeNext();
  102068. });
  102069. }, function () {
  102070. //execution ended, run the success callback.
  102071. if (task.successCallback) {
  102072. task.successCallback();
  102073. }
  102074. _this.executeNext();
  102075. });
  102076. }
  102077. };
  102078. SimplificationQueue.prototype.getSimplifier = function (task) {
  102079. switch (task.simplificationType) {
  102080. case SimplificationType.QUADRATIC:
  102081. default:
  102082. return new QuadraticErrorSimplification(task.mesh);
  102083. }
  102084. };
  102085. return SimplificationQueue;
  102086. }());
  102087. BABYLON.SimplificationQueue = SimplificationQueue;
  102088. /**
  102089. * The implemented types of simplification
  102090. * At the moment only Quadratic Error Decimation is implemented
  102091. */
  102092. var SimplificationType;
  102093. (function (SimplificationType) {
  102094. /** Quadratic error decimation */
  102095. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  102096. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  102097. var DecimationTriangle = /** @class */ (function () {
  102098. function DecimationTriangle(vertices) {
  102099. this.vertices = vertices;
  102100. this.error = new Array(4);
  102101. this.deleted = false;
  102102. this.isDirty = false;
  102103. this.deletePending = false;
  102104. this.borderFactor = 0;
  102105. }
  102106. return DecimationTriangle;
  102107. }());
  102108. BABYLON.DecimationTriangle = DecimationTriangle;
  102109. var DecimationVertex = /** @class */ (function () {
  102110. function DecimationVertex(position, id) {
  102111. this.position = position;
  102112. this.id = id;
  102113. this.isBorder = true;
  102114. this.q = new QuadraticMatrix();
  102115. this.triangleCount = 0;
  102116. this.triangleStart = 0;
  102117. this.originalOffsets = [];
  102118. }
  102119. DecimationVertex.prototype.updatePosition = function (newPosition) {
  102120. this.position.copyFrom(newPosition);
  102121. };
  102122. return DecimationVertex;
  102123. }());
  102124. BABYLON.DecimationVertex = DecimationVertex;
  102125. var QuadraticMatrix = /** @class */ (function () {
  102126. function QuadraticMatrix(data) {
  102127. this.data = new Array(10);
  102128. for (var i = 0; i < 10; ++i) {
  102129. if (data && data[i]) {
  102130. this.data[i] = data[i];
  102131. }
  102132. else {
  102133. this.data[i] = 0;
  102134. }
  102135. }
  102136. }
  102137. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  102138. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  102139. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  102140. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  102141. return det;
  102142. };
  102143. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  102144. for (var i = 0; i < 10; ++i) {
  102145. this.data[i] += matrix.data[i];
  102146. }
  102147. };
  102148. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  102149. for (var i = 0; i < 10; ++i) {
  102150. this.data[i] += data[i];
  102151. }
  102152. };
  102153. QuadraticMatrix.prototype.add = function (matrix) {
  102154. var m = new QuadraticMatrix();
  102155. for (var i = 0; i < 10; ++i) {
  102156. m.data[i] = this.data[i] + matrix.data[i];
  102157. }
  102158. return m;
  102159. };
  102160. QuadraticMatrix.FromData = function (a, b, c, d) {
  102161. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  102162. };
  102163. //returning an array to avoid garbage collection
  102164. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  102165. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  102166. };
  102167. return QuadraticMatrix;
  102168. }());
  102169. BABYLON.QuadraticMatrix = QuadraticMatrix;
  102170. var Reference = /** @class */ (function () {
  102171. function Reference(vertexId, triangleId) {
  102172. this.vertexId = vertexId;
  102173. this.triangleId = triangleId;
  102174. }
  102175. return Reference;
  102176. }());
  102177. BABYLON.Reference = Reference;
  102178. /**
  102179. * An implementation of the Quadratic Error simplification algorithm.
  102180. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  102181. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  102182. * @author RaananW
  102183. */
  102184. var QuadraticErrorSimplification = /** @class */ (function () {
  102185. function QuadraticErrorSimplification(_mesh) {
  102186. this._mesh = _mesh;
  102187. this.syncIterations = 5000;
  102188. this.aggressiveness = 7;
  102189. this.decimationIterations = 100;
  102190. this.boundingBoxEpsilon = BABYLON.Epsilon;
  102191. }
  102192. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  102193. var _this = this;
  102194. this.initDecimatedMesh();
  102195. //iterating through the submeshes array, one after the other.
  102196. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  102197. _this.initWithMesh(loop.index, function () {
  102198. _this.runDecimation(settings, loop.index, function () {
  102199. loop.executeNext();
  102200. });
  102201. }, settings.optimizeMesh);
  102202. }, function () {
  102203. setTimeout(function () {
  102204. successCallback(_this._reconstructedMesh);
  102205. }, 0);
  102206. });
  102207. };
  102208. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  102209. var _this = this;
  102210. var targetCount = ~~(this.triangles.length * settings.quality);
  102211. var deletedTriangles = 0;
  102212. var triangleCount = this.triangles.length;
  102213. var iterationFunction = function (iteration, callback) {
  102214. setTimeout(function () {
  102215. if (iteration % 5 === 0) {
  102216. _this.updateMesh(iteration === 0);
  102217. }
  102218. for (var i = 0; i < _this.triangles.length; ++i) {
  102219. _this.triangles[i].isDirty = false;
  102220. }
  102221. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  102222. var trianglesIterator = function (i) {
  102223. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  102224. var t = _this.triangles[tIdx];
  102225. if (!t)
  102226. return;
  102227. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  102228. return;
  102229. }
  102230. for (var j = 0; j < 3; ++j) {
  102231. if (t.error[j] < threshold) {
  102232. var deleted0 = [];
  102233. var deleted1 = [];
  102234. var v0 = t.vertices[j];
  102235. var v1 = t.vertices[(j + 1) % 3];
  102236. if (v0.isBorder || v1.isBorder)
  102237. continue;
  102238. var p = BABYLON.Vector3.Zero();
  102239. var n = BABYLON.Vector3.Zero();
  102240. var uv = BABYLON.Vector2.Zero();
  102241. var color = new BABYLON.Color4(0, 0, 0, 1);
  102242. _this.calculateError(v0, v1, p, n, uv, color);
  102243. var delTr = new Array();
  102244. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  102245. continue;
  102246. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  102247. continue;
  102248. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  102249. continue;
  102250. var uniqueArray = new Array();
  102251. delTr.forEach(function (deletedT) {
  102252. if (uniqueArray.indexOf(deletedT) === -1) {
  102253. deletedT.deletePending = true;
  102254. uniqueArray.push(deletedT);
  102255. }
  102256. });
  102257. if (uniqueArray.length % 2 !== 0) {
  102258. continue;
  102259. }
  102260. v0.q = v1.q.add(v0.q);
  102261. v0.updatePosition(p);
  102262. var tStart = _this.references.length;
  102263. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  102264. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  102265. var tCount = _this.references.length - tStart;
  102266. if (tCount <= v0.triangleCount) {
  102267. if (tCount) {
  102268. for (var c = 0; c < tCount; c++) {
  102269. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  102270. }
  102271. }
  102272. }
  102273. else {
  102274. v0.triangleStart = tStart;
  102275. }
  102276. v0.triangleCount = tCount;
  102277. break;
  102278. }
  102279. }
  102280. };
  102281. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  102282. }, 0);
  102283. };
  102284. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  102285. if (triangleCount - deletedTriangles <= targetCount)
  102286. loop.breakLoop();
  102287. else {
  102288. iterationFunction(loop.index, function () {
  102289. loop.executeNext();
  102290. });
  102291. }
  102292. }, function () {
  102293. setTimeout(function () {
  102294. //reconstruct this part of the mesh
  102295. _this.reconstructMesh(submeshIndex);
  102296. successCallback();
  102297. }, 0);
  102298. });
  102299. };
  102300. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  102301. var _this = this;
  102302. this.vertices = [];
  102303. this.triangles = [];
  102304. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  102305. var indices = this._mesh.getIndices();
  102306. var submesh = this._mesh.subMeshes[submeshIndex];
  102307. var findInVertices = function (positionToSearch) {
  102308. if (optimizeMesh) {
  102309. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  102310. if (_this.vertices[ii].position.equals(positionToSearch)) {
  102311. return _this.vertices[ii];
  102312. }
  102313. }
  102314. }
  102315. return null;
  102316. };
  102317. var vertexReferences = [];
  102318. var vertexInit = function (i) {
  102319. if (!positionData) {
  102320. return;
  102321. }
  102322. var offset = i + submesh.verticesStart;
  102323. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  102324. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  102325. vertex.originalOffsets.push(offset);
  102326. if (vertex.id === _this.vertices.length) {
  102327. _this.vertices.push(vertex);
  102328. }
  102329. vertexReferences.push(vertex.id);
  102330. };
  102331. //var totalVertices = mesh.getTotalVertices();
  102332. var totalVertices = submesh.verticesCount;
  102333. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  102334. var indicesInit = function (i) {
  102335. if (!indices) {
  102336. return;
  102337. }
  102338. var offset = (submesh.indexStart / 3) + i;
  102339. var pos = (offset * 3);
  102340. var i0 = indices[pos + 0];
  102341. var i1 = indices[pos + 1];
  102342. var i2 = indices[pos + 2];
  102343. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  102344. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  102345. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  102346. var triangle = new DecimationTriangle([v0, v1, v2]);
  102347. triangle.originalOffset = pos;
  102348. _this.triangles.push(triangle);
  102349. };
  102350. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  102351. _this.init(callback);
  102352. });
  102353. });
  102354. };
  102355. QuadraticErrorSimplification.prototype.init = function (callback) {
  102356. var _this = this;
  102357. var triangleInit1 = function (i) {
  102358. var t = _this.triangles[i];
  102359. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  102360. for (var j = 0; j < 3; j++) {
  102361. 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))));
  102362. }
  102363. };
  102364. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  102365. var triangleInit2 = function (i) {
  102366. var t = _this.triangles[i];
  102367. for (var j = 0; j < 3; ++j) {
  102368. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  102369. }
  102370. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  102371. };
  102372. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  102373. callback();
  102374. });
  102375. });
  102376. };
  102377. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  102378. var newTriangles = [];
  102379. var i;
  102380. for (i = 0; i < this.vertices.length; ++i) {
  102381. this.vertices[i].triangleCount = 0;
  102382. }
  102383. var t;
  102384. var j;
  102385. for (i = 0; i < this.triangles.length; ++i) {
  102386. if (!this.triangles[i].deleted) {
  102387. t = this.triangles[i];
  102388. for (j = 0; j < 3; ++j) {
  102389. t.vertices[j].triangleCount = 1;
  102390. }
  102391. newTriangles.push(t);
  102392. }
  102393. }
  102394. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  102395. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  102396. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  102397. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  102398. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  102399. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  102400. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  102401. var vertexCount = 0;
  102402. for (i = 0; i < this.vertices.length; ++i) {
  102403. var vertex = this.vertices[i];
  102404. vertex.id = vertexCount;
  102405. if (vertex.triangleCount) {
  102406. vertex.originalOffsets.forEach(function (originalOffset) {
  102407. if (!normalData) {
  102408. return;
  102409. }
  102410. newPositionData.push(vertex.position.x);
  102411. newPositionData.push(vertex.position.y);
  102412. newPositionData.push(vertex.position.z);
  102413. newNormalData.push(normalData[originalOffset * 3]);
  102414. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  102415. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  102416. if (uvs && uvs.length) {
  102417. newUVsData.push(uvs[(originalOffset * 2)]);
  102418. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  102419. }
  102420. else if (colorsData && colorsData.length) {
  102421. newColorsData.push(colorsData[(originalOffset * 4)]);
  102422. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  102423. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  102424. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  102425. }
  102426. ++vertexCount;
  102427. });
  102428. }
  102429. }
  102430. var startingIndex = this._reconstructedMesh.getTotalIndices();
  102431. var startingVertex = this._reconstructedMesh.getTotalVertices();
  102432. var submeshesArray = this._reconstructedMesh.subMeshes;
  102433. this._reconstructedMesh.subMeshes = [];
  102434. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  102435. var originalIndices = this._mesh.getIndices();
  102436. for (i = 0; i < newTriangles.length; ++i) {
  102437. t = newTriangles[i]; //now get the new referencing point for each vertex
  102438. [0, 1, 2].forEach(function (idx) {
  102439. var id = originalIndices[t.originalOffset + idx];
  102440. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  102441. if (offset < 0)
  102442. offset = 0;
  102443. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  102444. });
  102445. }
  102446. //overwriting the old vertex buffers and indices.
  102447. this._reconstructedMesh.setIndices(newIndicesArray);
  102448. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  102449. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  102450. if (newUVsData.length > 0)
  102451. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  102452. if (newColorsData.length > 0)
  102453. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  102454. //create submesh
  102455. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  102456. if (submeshIndex > 0) {
  102457. this._reconstructedMesh.subMeshes = [];
  102458. submeshesArray.forEach(function (submesh) {
  102459. BABYLON.SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  102460. });
  102461. BABYLON.SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  102462. }
  102463. };
  102464. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  102465. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  102466. this._reconstructedMesh.material = this._mesh.material;
  102467. this._reconstructedMesh.parent = this._mesh.parent;
  102468. this._reconstructedMesh.isVisible = false;
  102469. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  102470. };
  102471. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  102472. for (var i = 0; i < vertex1.triangleCount; ++i) {
  102473. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  102474. if (t.deleted)
  102475. continue;
  102476. var s = this.references[vertex1.triangleStart + i].vertexId;
  102477. var v1 = t.vertices[(s + 1) % 3];
  102478. var v2 = t.vertices[(s + 2) % 3];
  102479. if ((v1 === vertex2 || v2 === vertex2)) {
  102480. deletedArray[i] = true;
  102481. delTr.push(t);
  102482. continue;
  102483. }
  102484. var d1 = v1.position.subtract(point);
  102485. d1 = d1.normalize();
  102486. var d2 = v2.position.subtract(point);
  102487. d2 = d2.normalize();
  102488. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  102489. return true;
  102490. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  102491. deletedArray[i] = false;
  102492. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  102493. return true;
  102494. }
  102495. return false;
  102496. };
  102497. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  102498. var newDeleted = deletedTriangles;
  102499. for (var i = 0; i < vertex.triangleCount; ++i) {
  102500. var ref = this.references[vertex.triangleStart + i];
  102501. var t = this.triangles[ref.triangleId];
  102502. if (t.deleted)
  102503. continue;
  102504. if (deletedArray[i] && t.deletePending) {
  102505. t.deleted = true;
  102506. newDeleted++;
  102507. continue;
  102508. }
  102509. t.vertices[ref.vertexId] = origVertex;
  102510. t.isDirty = true;
  102511. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  102512. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  102513. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  102514. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  102515. this.references.push(ref);
  102516. }
  102517. return newDeleted;
  102518. };
  102519. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  102520. for (var i = 0; i < this.vertices.length; ++i) {
  102521. var vCount = [];
  102522. var vId = [];
  102523. var v = this.vertices[i];
  102524. var j;
  102525. for (j = 0; j < v.triangleCount; ++j) {
  102526. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  102527. for (var ii = 0; ii < 3; ii++) {
  102528. var ofs = 0;
  102529. var vv = triangle.vertices[ii];
  102530. while (ofs < vCount.length) {
  102531. if (vId[ofs] === vv.id)
  102532. break;
  102533. ++ofs;
  102534. }
  102535. if (ofs === vCount.length) {
  102536. vCount.push(1);
  102537. vId.push(vv.id);
  102538. }
  102539. else {
  102540. vCount[ofs]++;
  102541. }
  102542. }
  102543. }
  102544. for (j = 0; j < vCount.length; ++j) {
  102545. if (vCount[j] === 1) {
  102546. this.vertices[vId[j]].isBorder = true;
  102547. }
  102548. else {
  102549. this.vertices[vId[j]].isBorder = false;
  102550. }
  102551. }
  102552. }
  102553. };
  102554. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  102555. if (identifyBorders === void 0) { identifyBorders = false; }
  102556. var i;
  102557. if (!identifyBorders) {
  102558. var newTrianglesVector = [];
  102559. for (i = 0; i < this.triangles.length; ++i) {
  102560. if (!this.triangles[i].deleted) {
  102561. newTrianglesVector.push(this.triangles[i]);
  102562. }
  102563. }
  102564. this.triangles = newTrianglesVector;
  102565. }
  102566. for (i = 0; i < this.vertices.length; ++i) {
  102567. this.vertices[i].triangleCount = 0;
  102568. this.vertices[i].triangleStart = 0;
  102569. }
  102570. var t;
  102571. var j;
  102572. var v;
  102573. for (i = 0; i < this.triangles.length; ++i) {
  102574. t = this.triangles[i];
  102575. for (j = 0; j < 3; ++j) {
  102576. v = t.vertices[j];
  102577. v.triangleCount++;
  102578. }
  102579. }
  102580. var tStart = 0;
  102581. for (i = 0; i < this.vertices.length; ++i) {
  102582. this.vertices[i].triangleStart = tStart;
  102583. tStart += this.vertices[i].triangleCount;
  102584. this.vertices[i].triangleCount = 0;
  102585. }
  102586. var newReferences = new Array(this.triangles.length * 3);
  102587. for (i = 0; i < this.triangles.length; ++i) {
  102588. t = this.triangles[i];
  102589. for (j = 0; j < 3; ++j) {
  102590. v = t.vertices[j];
  102591. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  102592. v.triangleCount++;
  102593. }
  102594. }
  102595. this.references = newReferences;
  102596. if (identifyBorders) {
  102597. this.identifyBorder();
  102598. }
  102599. };
  102600. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  102601. var x = point.x;
  102602. var y = point.y;
  102603. var z = point.z;
  102604. 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
  102605. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  102606. };
  102607. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  102608. var q = vertex1.q.add(vertex2.q);
  102609. var border = vertex1.isBorder && vertex2.isBorder;
  102610. var error = 0;
  102611. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  102612. if (qDet !== 0 && !border) {
  102613. if (!pointResult) {
  102614. pointResult = BABYLON.Vector3.Zero();
  102615. }
  102616. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  102617. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  102618. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  102619. error = this.vertexError(q, pointResult);
  102620. }
  102621. else {
  102622. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  102623. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  102624. var error1 = this.vertexError(q, vertex1.position);
  102625. var error2 = this.vertexError(q, vertex2.position);
  102626. var error3 = this.vertexError(q, p3);
  102627. error = Math.min(error1, error2, error3);
  102628. if (error === error1) {
  102629. if (pointResult) {
  102630. pointResult.copyFrom(vertex1.position);
  102631. }
  102632. }
  102633. else if (error === error2) {
  102634. if (pointResult) {
  102635. pointResult.copyFrom(vertex2.position);
  102636. }
  102637. }
  102638. else {
  102639. if (pointResult) {
  102640. pointResult.copyFrom(p3);
  102641. }
  102642. }
  102643. }
  102644. return error;
  102645. };
  102646. return QuadraticErrorSimplification;
  102647. }());
  102648. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  102649. })(BABYLON || (BABYLON = {}));
  102650. //# sourceMappingURL=babylon.meshSimplification.js.map
  102651. var BABYLON;
  102652. (function (BABYLON) {
  102653. Object.defineProperty(BABYLON.Scene.prototype, "simplificationQueue", {
  102654. get: function () {
  102655. if (!this._simplificationQueue) {
  102656. this._simplificationQueue = new BABYLON.SimplificationQueue();
  102657. var component = this._getComponent(BABYLON.SceneComponentConstants.NAME_SIMPLIFICATIONQUEUE);
  102658. if (!component) {
  102659. component = new SimplicationQueueSceneComponent(this);
  102660. this._addComponent(component);
  102661. }
  102662. }
  102663. return this._simplificationQueue;
  102664. },
  102665. set: function (value) {
  102666. this._simplificationQueue = value;
  102667. },
  102668. enumerable: true,
  102669. configurable: true
  102670. });
  102671. BABYLON.Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  102672. if (parallelProcessing === void 0) { parallelProcessing = true; }
  102673. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  102674. this.getScene().simplificationQueue.addTask({
  102675. settings: settings,
  102676. parallelProcessing: parallelProcessing,
  102677. mesh: this,
  102678. simplificationType: simplificationType,
  102679. successCallback: successCallback
  102680. });
  102681. return this;
  102682. };
  102683. /**
  102684. * Defines the simplification queue scene component responsible to help scheduling the various simplification task
  102685. * created in a scene
  102686. */
  102687. var SimplicationQueueSceneComponent = /** @class */ (function () {
  102688. /**
  102689. * Creates a new instance of the component for the given scene
  102690. * @param scene Defines the scene to register the component in
  102691. */
  102692. function SimplicationQueueSceneComponent(scene) {
  102693. /**
  102694. * The component name helpfull to identify the component in the list of scene components.
  102695. */
  102696. this.name = BABYLON.SceneComponentConstants.NAME_SIMPLIFICATIONQUEUE;
  102697. this.scene = scene;
  102698. }
  102699. /**
  102700. * Registers the component in a given scene
  102701. */
  102702. SimplicationQueueSceneComponent.prototype.register = function () {
  102703. this.scene._beforeCameraUpdateStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERAUPDATE_SIMPLIFICATIONQUEUE, this, this._beforeCameraUpdate);
  102704. };
  102705. /**
  102706. * Rebuilds the elements related to this component in case of
  102707. * context lost for instance.
  102708. */
  102709. SimplicationQueueSceneComponent.prototype.rebuild = function () {
  102710. // Nothing to do for this component
  102711. };
  102712. /**
  102713. * Disposes the component and the associated ressources
  102714. */
  102715. SimplicationQueueSceneComponent.prototype.dispose = function () {
  102716. // Nothing to do for this component
  102717. };
  102718. SimplicationQueueSceneComponent.prototype._beforeCameraUpdate = function () {
  102719. if (this.scene._simplificationQueue && !this.scene._simplificationQueue.running) {
  102720. this.scene._simplificationQueue.executeNext();
  102721. }
  102722. };
  102723. return SimplicationQueueSceneComponent;
  102724. }());
  102725. BABYLON.SimplicationQueueSceneComponent = SimplicationQueueSceneComponent;
  102726. })(BABYLON || (BABYLON = {}));
  102727. //# sourceMappingURL=babylon.meshSimplificationSceneComponent.js.map
  102728. var BABYLON;
  102729. (function (BABYLON) {
  102730. /**
  102731. * Class used to represent a specific level of detail of a mesh
  102732. * @see http://doc.babylonjs.com/how_to/how_to_use_lod
  102733. */
  102734. var MeshLODLevel = /** @class */ (function () {
  102735. /**
  102736. * Creates a new LOD level
  102737. * @param distance defines the distance where this level should star being displayed
  102738. * @param mesh defines the mesh to use to render this level
  102739. */
  102740. function MeshLODLevel(
  102741. /** Defines the distance where this level should star being displayed */
  102742. distance,
  102743. /** Defines the mesh to use to render this level */
  102744. mesh) {
  102745. this.distance = distance;
  102746. this.mesh = mesh;
  102747. }
  102748. return MeshLODLevel;
  102749. }());
  102750. BABYLON.MeshLODLevel = MeshLODLevel;
  102751. })(BABYLON || (BABYLON = {}));
  102752. //# sourceMappingURL=babylon.meshLODLevel.js.map
  102753. var BABYLON;
  102754. (function (BABYLON) {
  102755. /**
  102756. * Defines the root class used to create scene optimization to use with SceneOptimizer
  102757. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  102758. */
  102759. var SceneOptimization = /** @class */ (function () {
  102760. /**
  102761. * Creates the SceneOptimization object
  102762. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  102763. * @param desc defines the description associated with the optimization
  102764. */
  102765. function SceneOptimization(
  102766. /**
  102767. * Defines the priority of this optimization (0 by default which means first in the list)
  102768. */
  102769. priority) {
  102770. if (priority === void 0) { priority = 0; }
  102771. this.priority = priority;
  102772. }
  102773. /**
  102774. * Gets a string describing the action executed by the current optimization
  102775. * @returns description string
  102776. */
  102777. SceneOptimization.prototype.getDescription = function () {
  102778. return "";
  102779. };
  102780. /**
  102781. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  102782. * @param scene defines the current scene where to apply this optimization
  102783. * @param optimizer defines the current optimizer
  102784. * @returns true if everything that can be done was applied
  102785. */
  102786. SceneOptimization.prototype.apply = function (scene, optimizer) {
  102787. return true;
  102788. };
  102789. ;
  102790. return SceneOptimization;
  102791. }());
  102792. BABYLON.SceneOptimization = SceneOptimization;
  102793. /**
  102794. * Defines an optimization used to reduce the size of render target textures
  102795. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  102796. */
  102797. var TextureOptimization = /** @class */ (function (_super) {
  102798. __extends(TextureOptimization, _super);
  102799. /**
  102800. * Creates the TextureOptimization object
  102801. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  102802. * @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
  102803. * @param step defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  102804. */
  102805. function TextureOptimization(
  102806. /**
  102807. * Defines the priority of this optimization (0 by default which means first in the list)
  102808. */
  102809. priority,
  102810. /**
  102811. * 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
  102812. */
  102813. maximumSize,
  102814. /**
  102815. * Defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  102816. */
  102817. step) {
  102818. if (priority === void 0) { priority = 0; }
  102819. if (maximumSize === void 0) { maximumSize = 1024; }
  102820. if (step === void 0) { step = 0.5; }
  102821. var _this = _super.call(this, priority) || this;
  102822. _this.priority = priority;
  102823. _this.maximumSize = maximumSize;
  102824. _this.step = step;
  102825. return _this;
  102826. }
  102827. /**
  102828. * Gets a string describing the action executed by the current optimization
  102829. * @returns description string
  102830. */
  102831. TextureOptimization.prototype.getDescription = function () {
  102832. return "Reducing render target texture size to " + this.maximumSize;
  102833. };
  102834. /**
  102835. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  102836. * @param scene defines the current scene where to apply this optimization
  102837. * @param optimizer defines the current optimizer
  102838. * @returns true if everything that can be done was applied
  102839. */
  102840. TextureOptimization.prototype.apply = function (scene, optimizer) {
  102841. var allDone = true;
  102842. for (var index = 0; index < scene.textures.length; index++) {
  102843. var texture = scene.textures[index];
  102844. if (!texture.canRescale || texture.getContext) {
  102845. continue;
  102846. }
  102847. var currentSize = texture.getSize();
  102848. var maxDimension = Math.max(currentSize.width, currentSize.height);
  102849. if (maxDimension > this.maximumSize) {
  102850. texture.scale(this.step);
  102851. allDone = false;
  102852. }
  102853. }
  102854. return allDone;
  102855. };
  102856. return TextureOptimization;
  102857. }(SceneOptimization));
  102858. BABYLON.TextureOptimization = TextureOptimization;
  102859. /**
  102860. * Defines an optimization used to increase or decrease the rendering resolution
  102861. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  102862. */
  102863. var HardwareScalingOptimization = /** @class */ (function (_super) {
  102864. __extends(HardwareScalingOptimization, _super);
  102865. /**
  102866. * Creates the HardwareScalingOptimization object
  102867. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  102868. * @param maximumScale defines the maximum scale to use (2 by default)
  102869. * @param step defines the step to use between two passes (0.5 by default)
  102870. */
  102871. function HardwareScalingOptimization(
  102872. /**
  102873. * Defines the priority of this optimization (0 by default which means first in the list)
  102874. */
  102875. priority,
  102876. /**
  102877. * Defines the maximum scale to use (2 by default)
  102878. */
  102879. maximumScale,
  102880. /**
  102881. * Defines the step to use between two passes (0.5 by default)
  102882. */
  102883. step) {
  102884. if (priority === void 0) { priority = 0; }
  102885. if (maximumScale === void 0) { maximumScale = 2; }
  102886. if (step === void 0) { step = 0.25; }
  102887. var _this = _super.call(this, priority) || this;
  102888. _this.priority = priority;
  102889. _this.maximumScale = maximumScale;
  102890. _this.step = step;
  102891. _this._currentScale = -1;
  102892. _this._directionOffset = 1;
  102893. return _this;
  102894. }
  102895. /**
  102896. * Gets a string describing the action executed by the current optimization
  102897. * @return description string
  102898. */
  102899. HardwareScalingOptimization.prototype.getDescription = function () {
  102900. return "Setting hardware scaling level to " + this._currentScale;
  102901. };
  102902. /**
  102903. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  102904. * @param scene defines the current scene where to apply this optimization
  102905. * @param optimizer defines the current optimizer
  102906. * @returns true if everything that can be done was applied
  102907. */
  102908. HardwareScalingOptimization.prototype.apply = function (scene, optimizer) {
  102909. if (this._currentScale === -1) {
  102910. this._currentScale = scene.getEngine().getHardwareScalingLevel();
  102911. if (this._currentScale > this.maximumScale) {
  102912. this._directionOffset = -1;
  102913. }
  102914. }
  102915. this._currentScale += this._directionOffset * this.step;
  102916. scene.getEngine().setHardwareScalingLevel(this._currentScale);
  102917. return this._directionOffset === 1 ? this._currentScale >= this.maximumScale : this._currentScale <= this.maximumScale;
  102918. };
  102919. ;
  102920. return HardwareScalingOptimization;
  102921. }(SceneOptimization));
  102922. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  102923. /**
  102924. * Defines an optimization used to remove shadows
  102925. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  102926. */
  102927. var ShadowsOptimization = /** @class */ (function (_super) {
  102928. __extends(ShadowsOptimization, _super);
  102929. function ShadowsOptimization() {
  102930. return _super !== null && _super.apply(this, arguments) || this;
  102931. }
  102932. /**
  102933. * Gets a string describing the action executed by the current optimization
  102934. * @return description string
  102935. */
  102936. ShadowsOptimization.prototype.getDescription = function () {
  102937. return "Turning shadows on/off";
  102938. };
  102939. /**
  102940. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  102941. * @param scene defines the current scene where to apply this optimization
  102942. * @param optimizer defines the current optimizer
  102943. * @returns true if everything that can be done was applied
  102944. */
  102945. ShadowsOptimization.prototype.apply = function (scene, optimizer) {
  102946. scene.shadowsEnabled = optimizer.isInImprovementMode;
  102947. return true;
  102948. };
  102949. ;
  102950. return ShadowsOptimization;
  102951. }(SceneOptimization));
  102952. BABYLON.ShadowsOptimization = ShadowsOptimization;
  102953. /**
  102954. * Defines an optimization used to turn post-processes off
  102955. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  102956. */
  102957. var PostProcessesOptimization = /** @class */ (function (_super) {
  102958. __extends(PostProcessesOptimization, _super);
  102959. function PostProcessesOptimization() {
  102960. return _super !== null && _super.apply(this, arguments) || this;
  102961. }
  102962. /**
  102963. * Gets a string describing the action executed by the current optimization
  102964. * @return description string
  102965. */
  102966. PostProcessesOptimization.prototype.getDescription = function () {
  102967. return "Turning post-processes on/off";
  102968. };
  102969. /**
  102970. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  102971. * @param scene defines the current scene where to apply this optimization
  102972. * @param optimizer defines the current optimizer
  102973. * @returns true if everything that can be done was applied
  102974. */
  102975. PostProcessesOptimization.prototype.apply = function (scene, optimizer) {
  102976. scene.postProcessesEnabled = optimizer.isInImprovementMode;
  102977. return true;
  102978. };
  102979. ;
  102980. return PostProcessesOptimization;
  102981. }(SceneOptimization));
  102982. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  102983. /**
  102984. * Defines an optimization used to turn lens flares off
  102985. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  102986. */
  102987. var LensFlaresOptimization = /** @class */ (function (_super) {
  102988. __extends(LensFlaresOptimization, _super);
  102989. function LensFlaresOptimization() {
  102990. return _super !== null && _super.apply(this, arguments) || this;
  102991. }
  102992. /**
  102993. * Gets a string describing the action executed by the current optimization
  102994. * @return description string
  102995. */
  102996. LensFlaresOptimization.prototype.getDescription = function () {
  102997. return "Turning lens flares on/off";
  102998. };
  102999. /**
  103000. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  103001. * @param scene defines the current scene where to apply this optimization
  103002. * @param optimizer defines the current optimizer
  103003. * @returns true if everything that can be done was applied
  103004. */
  103005. LensFlaresOptimization.prototype.apply = function (scene, optimizer) {
  103006. scene.lensFlaresEnabled = optimizer.isInImprovementMode;
  103007. return true;
  103008. };
  103009. ;
  103010. return LensFlaresOptimization;
  103011. }(SceneOptimization));
  103012. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  103013. /**
  103014. * Defines an optimization based on user defined callback.
  103015. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  103016. */
  103017. var CustomOptimization = /** @class */ (function (_super) {
  103018. __extends(CustomOptimization, _super);
  103019. function CustomOptimization() {
  103020. return _super !== null && _super.apply(this, arguments) || this;
  103021. }
  103022. /**
  103023. * Gets a string describing the action executed by the current optimization
  103024. * @returns description string
  103025. */
  103026. CustomOptimization.prototype.getDescription = function () {
  103027. if (this.onGetDescription) {
  103028. return this.onGetDescription();
  103029. }
  103030. return "Running user defined callback";
  103031. };
  103032. /**
  103033. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  103034. * @param scene defines the current scene where to apply this optimization
  103035. * @param optimizer defines the current optimizer
  103036. * @returns true if everything that can be done was applied
  103037. */
  103038. CustomOptimization.prototype.apply = function (scene, optimizer) {
  103039. if (this.onApply) {
  103040. return this.onApply(scene, optimizer);
  103041. }
  103042. return true;
  103043. };
  103044. ;
  103045. return CustomOptimization;
  103046. }(SceneOptimization));
  103047. BABYLON.CustomOptimization = CustomOptimization;
  103048. /**
  103049. * Defines an optimization used to turn particles off
  103050. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  103051. */
  103052. var ParticlesOptimization = /** @class */ (function (_super) {
  103053. __extends(ParticlesOptimization, _super);
  103054. function ParticlesOptimization() {
  103055. return _super !== null && _super.apply(this, arguments) || this;
  103056. }
  103057. /**
  103058. * Gets a string describing the action executed by the current optimization
  103059. * @return description string
  103060. */
  103061. ParticlesOptimization.prototype.getDescription = function () {
  103062. return "Turning particles on/off";
  103063. };
  103064. /**
  103065. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  103066. * @param scene defines the current scene where to apply this optimization
  103067. * @param optimizer defines the current optimizer
  103068. * @returns true if everything that can be done was applied
  103069. */
  103070. ParticlesOptimization.prototype.apply = function (scene, optimizer) {
  103071. scene.particlesEnabled = optimizer.isInImprovementMode;
  103072. return true;
  103073. };
  103074. ;
  103075. return ParticlesOptimization;
  103076. }(SceneOptimization));
  103077. BABYLON.ParticlesOptimization = ParticlesOptimization;
  103078. /**
  103079. * Defines an optimization used to turn render targets off
  103080. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  103081. */
  103082. var RenderTargetsOptimization = /** @class */ (function (_super) {
  103083. __extends(RenderTargetsOptimization, _super);
  103084. function RenderTargetsOptimization() {
  103085. return _super !== null && _super.apply(this, arguments) || this;
  103086. }
  103087. /**
  103088. * Gets a string describing the action executed by the current optimization
  103089. * @return description string
  103090. */
  103091. RenderTargetsOptimization.prototype.getDescription = function () {
  103092. return "Turning render targets off";
  103093. };
  103094. /**
  103095. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  103096. * @param scene defines the current scene where to apply this optimization
  103097. * @param optimizer defines the current optimizer
  103098. * @returns true if everything that can be done was applied
  103099. */
  103100. RenderTargetsOptimization.prototype.apply = function (scene, optimizer) {
  103101. scene.renderTargetsEnabled = optimizer.isInImprovementMode;
  103102. return true;
  103103. };
  103104. ;
  103105. return RenderTargetsOptimization;
  103106. }(SceneOptimization));
  103107. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  103108. /**
  103109. * Defines an optimization used to merge meshes with compatible materials
  103110. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  103111. */
  103112. var MergeMeshesOptimization = /** @class */ (function (_super) {
  103113. __extends(MergeMeshesOptimization, _super);
  103114. function MergeMeshesOptimization() {
  103115. var _this = _super !== null && _super.apply(this, arguments) || this;
  103116. _this._canBeMerged = function (abstractMesh) {
  103117. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  103118. return false;
  103119. }
  103120. var mesh = abstractMesh;
  103121. if (mesh.isDisposed()) {
  103122. return false;
  103123. }
  103124. if (!mesh.isVisible || !mesh.isEnabled()) {
  103125. return false;
  103126. }
  103127. if (mesh.instances.length > 0) {
  103128. return false;
  103129. }
  103130. if (mesh.skeleton || mesh.hasLODLevels) {
  103131. return false;
  103132. }
  103133. return true;
  103134. };
  103135. return _this;
  103136. }
  103137. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  103138. /**
  103139. * Gets or sets a boolean which defines if optimization octree has to be updated
  103140. */
  103141. get: function () {
  103142. return MergeMeshesOptimization._UpdateSelectionTree;
  103143. },
  103144. /**
  103145. * Gets or sets a boolean which defines if optimization octree has to be updated
  103146. */
  103147. set: function (value) {
  103148. MergeMeshesOptimization._UpdateSelectionTree = value;
  103149. },
  103150. enumerable: true,
  103151. configurable: true
  103152. });
  103153. /**
  103154. * Gets a string describing the action executed by the current optimization
  103155. * @return description string
  103156. */
  103157. MergeMeshesOptimization.prototype.getDescription = function () {
  103158. return "Merging similar meshes together";
  103159. };
  103160. /**
  103161. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  103162. * @param scene defines the current scene where to apply this optimization
  103163. * @param optimizer defines the current optimizer
  103164. * @param updateSelectionTree defines that the selection octree has to be updated (false by default)
  103165. * @returns true if everything that can be done was applied
  103166. */
  103167. MergeMeshesOptimization.prototype.apply = function (scene, optimizer, updateSelectionTree) {
  103168. var globalPool = scene.meshes.slice(0);
  103169. var globalLength = globalPool.length;
  103170. for (var index = 0; index < globalLength; index++) {
  103171. var currentPool = new Array();
  103172. var current = globalPool[index];
  103173. // Checks
  103174. if (!this._canBeMerged(current)) {
  103175. continue;
  103176. }
  103177. currentPool.push(current);
  103178. // Find compatible meshes
  103179. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  103180. var otherMesh = globalPool[subIndex];
  103181. if (!this._canBeMerged(otherMesh)) {
  103182. continue;
  103183. }
  103184. if (otherMesh.material !== current.material) {
  103185. continue;
  103186. }
  103187. if (otherMesh.checkCollisions !== current.checkCollisions) {
  103188. continue;
  103189. }
  103190. currentPool.push(otherMesh);
  103191. globalLength--;
  103192. globalPool.splice(subIndex, 1);
  103193. subIndex--;
  103194. }
  103195. if (currentPool.length < 2) {
  103196. continue;
  103197. }
  103198. // Merge meshes
  103199. BABYLON.Mesh.MergeMeshes(currentPool, undefined, true);
  103200. }
  103201. // Call the octree system optimization if it is defined.
  103202. var sceneAsAny = scene;
  103203. if (sceneAsAny.createOrUpdateSelectionOctree) {
  103204. if (updateSelectionTree != undefined) {
  103205. if (updateSelectionTree) {
  103206. sceneAsAny.createOrUpdateSelectionOctree();
  103207. }
  103208. }
  103209. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  103210. sceneAsAny.createOrUpdateSelectionOctree();
  103211. }
  103212. }
  103213. return true;
  103214. };
  103215. ;
  103216. MergeMeshesOptimization._UpdateSelectionTree = false;
  103217. return MergeMeshesOptimization;
  103218. }(SceneOptimization));
  103219. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  103220. /**
  103221. * Defines a list of options used by SceneOptimizer
  103222. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  103223. */
  103224. var SceneOptimizerOptions = /** @class */ (function () {
  103225. /**
  103226. * Creates a new list of options used by SceneOptimizer
  103227. * @param targetFrameRate defines the target frame rate to reach (60 by default)
  103228. * @param trackerDuration defines the interval between two checkes (2000ms by default)
  103229. */
  103230. function SceneOptimizerOptions(
  103231. /**
  103232. * Defines the target frame rate to reach (60 by default)
  103233. */
  103234. targetFrameRate,
  103235. /**
  103236. * Defines the interval between two checkes (2000ms by default)
  103237. */
  103238. trackerDuration) {
  103239. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  103240. if (trackerDuration === void 0) { trackerDuration = 2000; }
  103241. this.targetFrameRate = targetFrameRate;
  103242. this.trackerDuration = trackerDuration;
  103243. /**
  103244. * Gets the list of optimizations to apply
  103245. */
  103246. this.optimizations = new Array();
  103247. }
  103248. /**
  103249. * Add a new optimization
  103250. * @param optimization defines the SceneOptimization to add to the list of active optimizations
  103251. * @returns the current SceneOptimizerOptions
  103252. */
  103253. SceneOptimizerOptions.prototype.addOptimization = function (optimization) {
  103254. this.optimizations.push(optimization);
  103255. return this;
  103256. };
  103257. /**
  103258. * Add a new custom optimization
  103259. * @param onApply defines the callback called to apply the custom optimization (true if everything that can be done was applied)
  103260. * @param onGetDescription defines the callback called to get the description attached with the optimization.
  103261. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  103262. * @returns the current SceneOptimizerOptions
  103263. */
  103264. SceneOptimizerOptions.prototype.addCustomOptimization = function (onApply, onGetDescription, priority) {
  103265. if (priority === void 0) { priority = 0; }
  103266. var optimization = new CustomOptimization(priority);
  103267. optimization.onApply = onApply;
  103268. optimization.onGetDescription = onGetDescription;
  103269. this.optimizations.push(optimization);
  103270. return this;
  103271. };
  103272. /**
  103273. * Creates a list of pre-defined optimizations aimed to reduce the visual impact on the scene
  103274. * @param targetFrameRate defines the target frame rate (60 by default)
  103275. * @returns a SceneOptimizerOptions object
  103276. */
  103277. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  103278. var result = new SceneOptimizerOptions(targetFrameRate);
  103279. var priority = 0;
  103280. result.addOptimization(new MergeMeshesOptimization(priority));
  103281. result.addOptimization(new ShadowsOptimization(priority));
  103282. result.addOptimization(new LensFlaresOptimization(priority));
  103283. // Next priority
  103284. priority++;
  103285. result.addOptimization(new PostProcessesOptimization(priority));
  103286. result.addOptimization(new ParticlesOptimization(priority));
  103287. // Next priority
  103288. priority++;
  103289. result.addOptimization(new TextureOptimization(priority, 1024));
  103290. return result;
  103291. };
  103292. /**
  103293. * Creates a list of pre-defined optimizations aimed to have a moderate impact on the scene visual
  103294. * @param targetFrameRate defines the target frame rate (60 by default)
  103295. * @returns a SceneOptimizerOptions object
  103296. */
  103297. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  103298. var result = new SceneOptimizerOptions(targetFrameRate);
  103299. var priority = 0;
  103300. result.addOptimization(new MergeMeshesOptimization(priority));
  103301. result.addOptimization(new ShadowsOptimization(priority));
  103302. result.addOptimization(new LensFlaresOptimization(priority));
  103303. // Next priority
  103304. priority++;
  103305. result.addOptimization(new PostProcessesOptimization(priority));
  103306. result.addOptimization(new ParticlesOptimization(priority));
  103307. // Next priority
  103308. priority++;
  103309. result.addOptimization(new TextureOptimization(priority, 512));
  103310. // Next priority
  103311. priority++;
  103312. result.addOptimization(new RenderTargetsOptimization(priority));
  103313. // Next priority
  103314. priority++;
  103315. result.addOptimization(new HardwareScalingOptimization(priority, 2));
  103316. return result;
  103317. };
  103318. /**
  103319. * Creates a list of pre-defined optimizations aimed to have a big impact on the scene visual
  103320. * @param targetFrameRate defines the target frame rate (60 by default)
  103321. * @returns a SceneOptimizerOptions object
  103322. */
  103323. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  103324. var result = new SceneOptimizerOptions(targetFrameRate);
  103325. var priority = 0;
  103326. result.addOptimization(new MergeMeshesOptimization(priority));
  103327. result.addOptimization(new ShadowsOptimization(priority));
  103328. result.addOptimization(new LensFlaresOptimization(priority));
  103329. // Next priority
  103330. priority++;
  103331. result.addOptimization(new PostProcessesOptimization(priority));
  103332. result.addOptimization(new ParticlesOptimization(priority));
  103333. // Next priority
  103334. priority++;
  103335. result.addOptimization(new TextureOptimization(priority, 256));
  103336. // Next priority
  103337. priority++;
  103338. result.addOptimization(new RenderTargetsOptimization(priority));
  103339. // Next priority
  103340. priority++;
  103341. result.addOptimization(new HardwareScalingOptimization(priority, 4));
  103342. return result;
  103343. };
  103344. return SceneOptimizerOptions;
  103345. }());
  103346. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  103347. /**
  103348. * Class used to run optimizations in order to reach a target frame rate
  103349. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  103350. */
  103351. var SceneOptimizer = /** @class */ (function () {
  103352. /**
  103353. * Creates a new SceneOptimizer
  103354. * @param scene defines the scene to work on
  103355. * @param options defines the options to use with the SceneOptimizer
  103356. * @param autoGeneratePriorities defines if priorities must be generated and not read from SceneOptimization property (true by default)
  103357. * @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)
  103358. */
  103359. function SceneOptimizer(scene, options, autoGeneratePriorities, improvementMode) {
  103360. if (autoGeneratePriorities === void 0) { autoGeneratePriorities = true; }
  103361. if (improvementMode === void 0) { improvementMode = false; }
  103362. var _this = this;
  103363. this._isRunning = false;
  103364. this._currentPriorityLevel = 0;
  103365. this._targetFrameRate = 60;
  103366. this._trackerDuration = 2000;
  103367. this._currentFrameRate = 0;
  103368. this._improvementMode = false;
  103369. /**
  103370. * Defines an observable called when the optimizer reaches the target frame rate
  103371. */
  103372. this.onSuccessObservable = new BABYLON.Observable();
  103373. /**
  103374. * Defines an observable called when the optimizer enables an optimization
  103375. */
  103376. this.onNewOptimizationAppliedObservable = new BABYLON.Observable();
  103377. /**
  103378. * Defines an observable called when the optimizer is not able to reach the target frame rate
  103379. */
  103380. this.onFailureObservable = new BABYLON.Observable();
  103381. if (!options) {
  103382. this._options = new SceneOptimizerOptions();
  103383. }
  103384. else {
  103385. this._options = options;
  103386. }
  103387. if (this._options.targetFrameRate) {
  103388. this._targetFrameRate = this._options.targetFrameRate;
  103389. }
  103390. if (this._options.trackerDuration) {
  103391. this._trackerDuration = this._options.trackerDuration;
  103392. }
  103393. if (autoGeneratePriorities) {
  103394. var priority = 0;
  103395. for (var _i = 0, _a = this._options.optimizations; _i < _a.length; _i++) {
  103396. var optim = _a[_i];
  103397. optim.priority = priority++;
  103398. }
  103399. }
  103400. this._improvementMode = improvementMode;
  103401. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  103402. this._sceneDisposeObserver = this._scene.onDisposeObservable.add(function () {
  103403. _this._sceneDisposeObserver = null;
  103404. _this.dispose();
  103405. });
  103406. }
  103407. Object.defineProperty(SceneOptimizer.prototype, "isInImprovementMode", {
  103408. /**
  103409. * Gets a boolean indicating if the optimizer is in improvement mode
  103410. */
  103411. get: function () {
  103412. return this._improvementMode;
  103413. },
  103414. enumerable: true,
  103415. configurable: true
  103416. });
  103417. Object.defineProperty(SceneOptimizer.prototype, "currentPriorityLevel", {
  103418. /**
  103419. * Gets the current priority level (0 at start)
  103420. */
  103421. get: function () {
  103422. return this._currentPriorityLevel;
  103423. },
  103424. enumerable: true,
  103425. configurable: true
  103426. });
  103427. Object.defineProperty(SceneOptimizer.prototype, "currentFrameRate", {
  103428. /**
  103429. * Gets the current frame rate checked by the SceneOptimizer
  103430. */
  103431. get: function () {
  103432. return this._currentFrameRate;
  103433. },
  103434. enumerable: true,
  103435. configurable: true
  103436. });
  103437. Object.defineProperty(SceneOptimizer.prototype, "targetFrameRate", {
  103438. /**
  103439. * Gets or sets the current target frame rate (60 by default)
  103440. */
  103441. get: function () {
  103442. return this._targetFrameRate;
  103443. },
  103444. /**
  103445. * Gets or sets the current target frame rate (60 by default)
  103446. */
  103447. set: function (value) {
  103448. this._targetFrameRate = value;
  103449. },
  103450. enumerable: true,
  103451. configurable: true
  103452. });
  103453. Object.defineProperty(SceneOptimizer.prototype, "trackerDuration", {
  103454. /**
  103455. * Gets or sets the current interval between two checks (every 2000ms by default)
  103456. */
  103457. get: function () {
  103458. return this._trackerDuration;
  103459. },
  103460. /**
  103461. * Gets or sets the current interval between two checks (every 2000ms by default)
  103462. */
  103463. set: function (value) {
  103464. this._trackerDuration = value;
  103465. },
  103466. enumerable: true,
  103467. configurable: true
  103468. });
  103469. Object.defineProperty(SceneOptimizer.prototype, "optimizations", {
  103470. /**
  103471. * Gets the list of active optimizations
  103472. */
  103473. get: function () {
  103474. return this._options.optimizations;
  103475. },
  103476. enumerable: true,
  103477. configurable: true
  103478. });
  103479. /**
  103480. * Stops the current optimizer
  103481. */
  103482. SceneOptimizer.prototype.stop = function () {
  103483. this._isRunning = false;
  103484. };
  103485. /**
  103486. * Reset the optimizer to initial step (current priority level = 0)
  103487. */
  103488. SceneOptimizer.prototype.reset = function () {
  103489. this._currentPriorityLevel = 0;
  103490. };
  103491. /**
  103492. * Start the optimizer. By default it will try to reach a specific framerate
  103493. * but if the optimizer is set with improvementMode === true then it will run all optimiatiation while frame rate is above the target frame rate
  103494. */
  103495. SceneOptimizer.prototype.start = function () {
  103496. var _this = this;
  103497. if (this._isRunning) {
  103498. return;
  103499. }
  103500. this._isRunning = true;
  103501. // Let's wait for the scene to be ready before running our check
  103502. this._scene.executeWhenReady(function () {
  103503. setTimeout(function () {
  103504. _this._checkCurrentState();
  103505. }, _this._trackerDuration);
  103506. });
  103507. };
  103508. SceneOptimizer.prototype._checkCurrentState = function () {
  103509. var _this = this;
  103510. if (!this._isRunning) {
  103511. return;
  103512. }
  103513. var scene = this._scene;
  103514. var options = this._options;
  103515. this._currentFrameRate = Math.round(scene.getEngine().getFps());
  103516. if (this._improvementMode && this._currentFrameRate <= this._targetFrameRate ||
  103517. !this._improvementMode && this._currentFrameRate >= this._targetFrameRate) {
  103518. this._isRunning = false;
  103519. this.onSuccessObservable.notifyObservers(this);
  103520. return;
  103521. }
  103522. // Apply current level of optimizations
  103523. var allDone = true;
  103524. var noOptimizationApplied = true;
  103525. for (var index = 0; index < options.optimizations.length; index++) {
  103526. var optimization = options.optimizations[index];
  103527. if (optimization.priority === this._currentPriorityLevel) {
  103528. noOptimizationApplied = false;
  103529. allDone = allDone && optimization.apply(scene, this);
  103530. this.onNewOptimizationAppliedObservable.notifyObservers(optimization);
  103531. }
  103532. }
  103533. // If no optimization was applied, this is a failure :(
  103534. if (noOptimizationApplied) {
  103535. this._isRunning = false;
  103536. this.onFailureObservable.notifyObservers(this);
  103537. return;
  103538. }
  103539. // If all optimizations were done, move to next level
  103540. if (allDone) {
  103541. this._currentPriorityLevel++;
  103542. }
  103543. // Let's the system running for a specific amount of time before checking FPS
  103544. scene.executeWhenReady(function () {
  103545. setTimeout(function () {
  103546. _this._checkCurrentState();
  103547. }, _this._trackerDuration);
  103548. });
  103549. };
  103550. /**
  103551. * Release all resources
  103552. */
  103553. SceneOptimizer.prototype.dispose = function () {
  103554. this.stop();
  103555. this.onSuccessObservable.clear();
  103556. this.onFailureObservable.clear();
  103557. this.onNewOptimizationAppliedObservable.clear();
  103558. if (this._sceneDisposeObserver) {
  103559. this._scene.onDisposeObservable.remove(this._sceneDisposeObserver);
  103560. }
  103561. };
  103562. /**
  103563. * Helper function to create a SceneOptimizer with one single line of code
  103564. * @param scene defines the scene to work on
  103565. * @param options defines the options to use with the SceneOptimizer
  103566. * @param onSuccess defines a callback to call on success
  103567. * @param onFailure defines a callback to call on failure
  103568. * @returns the new SceneOptimizer object
  103569. */
  103570. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  103571. var optimizer = new SceneOptimizer(scene, options || SceneOptimizerOptions.ModerateDegradationAllowed(), false);
  103572. if (onSuccess) {
  103573. optimizer.onSuccessObservable.add(function () {
  103574. onSuccess();
  103575. });
  103576. }
  103577. if (onFailure) {
  103578. optimizer.onFailureObservable.add(function () {
  103579. onFailure();
  103580. });
  103581. }
  103582. optimizer.start();
  103583. return optimizer;
  103584. };
  103585. return SceneOptimizer;
  103586. }());
  103587. BABYLON.SceneOptimizer = SceneOptimizer;
  103588. })(BABYLON || (BABYLON = {}));
  103589. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  103590. var BABYLON;
  103591. (function (BABYLON) {
  103592. /**
  103593. * Gets the outline renderer associated with the scene
  103594. * @returns a OutlineRenderer
  103595. */
  103596. BABYLON.Scene.prototype.getOutlineRenderer = function () {
  103597. if (!this._outlineRenderer) {
  103598. this._outlineRenderer = new OutlineRenderer(this);
  103599. }
  103600. return this._outlineRenderer;
  103601. };
  103602. Object.defineProperty(BABYLON.AbstractMesh.prototype, "renderOutline", {
  103603. get: function () {
  103604. return this._renderOutline;
  103605. },
  103606. set: function (value) {
  103607. if (value) {
  103608. // Lazy Load the component.
  103609. this.getScene().getOutlineRenderer();
  103610. }
  103611. this._renderOutline = value;
  103612. },
  103613. enumerable: true,
  103614. configurable: true
  103615. });
  103616. Object.defineProperty(BABYLON.AbstractMesh.prototype, "renderOverlay", {
  103617. get: function () {
  103618. return this._renderOverlay;
  103619. },
  103620. set: function (value) {
  103621. if (value) {
  103622. // Lazy Load the component.
  103623. this.getScene().getOutlineRenderer();
  103624. }
  103625. this._renderOverlay = value;
  103626. },
  103627. enumerable: true,
  103628. configurable: true
  103629. });
  103630. /**
  103631. * This class is responsible to draw bothe outline/overlay of meshes.
  103632. * It should not be used directly but through the available method on mesh.
  103633. */
  103634. var OutlineRenderer = /** @class */ (function () {
  103635. /**
  103636. * Instantiates a new outline renderer. (There could be only one per scene).
  103637. * @param scene Defines the scene it belongs to
  103638. */
  103639. function OutlineRenderer(scene) {
  103640. /**
  103641. * The name of the component. Each component must have a unique name.
  103642. */
  103643. this.name = BABYLON.SceneComponentConstants.NAME_OUTLINERENDERER;
  103644. /**
  103645. * Defines a zOffset to prevent zFighting between the overlay and the mesh.
  103646. */
  103647. this.zOffset = 1;
  103648. this.scene = scene;
  103649. this._engine = scene.getEngine();
  103650. this.scene._addComponent(this);
  103651. }
  103652. /**
  103653. * Register the component to one instance of a scene.
  103654. */
  103655. OutlineRenderer.prototype.register = function () {
  103656. this.scene._beforeRenderingMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORERENDERINGMESH_OUTLINE, this, this._beforeRenderingMesh);
  103657. this.scene._afterRenderingMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERRENDERINGMESH_OUTLINE, this, this._afterRenderingMesh);
  103658. };
  103659. /**
  103660. * Rebuilds the elements related to this component in case of
  103661. * context lost for instance.
  103662. */
  103663. OutlineRenderer.prototype.rebuild = function () {
  103664. // Nothing to do here.
  103665. };
  103666. /**
  103667. * Disposes the component and the associated ressources.
  103668. */
  103669. OutlineRenderer.prototype.dispose = function () {
  103670. // Nothing to do here.
  103671. };
  103672. /**
  103673. * Renders the outline in the canvas.
  103674. * @param subMesh Defines the sumesh to render
  103675. * @param batch Defines the batch of meshes in case of instances
  103676. * @param useOverlay Defines if the rendering is for the overlay or the outline
  103677. */
  103678. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  103679. var _this = this;
  103680. if (useOverlay === void 0) { useOverlay = false; }
  103681. var scene = this.scene;
  103682. var engine = scene.getEngine();
  103683. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  103684. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  103685. return;
  103686. }
  103687. var mesh = subMesh.getRenderingMesh();
  103688. var material = subMesh.getMaterial();
  103689. if (!material || !scene.activeCamera) {
  103690. return;
  103691. }
  103692. engine.enableEffect(this._effect);
  103693. // Logarithmic depth
  103694. if (material.useLogarithmicDepth) {
  103695. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  103696. }
  103697. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  103698. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  103699. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  103700. // Bones
  103701. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  103702. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  103703. }
  103704. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  103705. // Alpha test
  103706. if (material && material.needAlphaTesting()) {
  103707. var alphaTexture = material.getAlphaTestTexture();
  103708. if (alphaTexture) {
  103709. this._effect.setTexture("diffuseSampler", alphaTexture);
  103710. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  103711. }
  103712. }
  103713. engine.setZOffset(-this.zOffset);
  103714. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  103715. engine.setZOffset(0);
  103716. };
  103717. /**
  103718. * Returns whether or not the outline renderer is ready for a given submesh.
  103719. * All the dependencies e.g. submeshes, texture, effect... mus be ready
  103720. * @param subMesh Defines the submesh to check readyness for
  103721. * @param useInstances Defines wheter wee are trying to render instances or not
  103722. * @returns true if ready otherwise false
  103723. */
  103724. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  103725. var defines = [];
  103726. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  103727. var mesh = subMesh.getMesh();
  103728. var material = subMesh.getMaterial();
  103729. if (material) {
  103730. // Alpha test
  103731. if (material.needAlphaTesting()) {
  103732. defines.push("#define ALPHATEST");
  103733. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  103734. attribs.push(BABYLON.VertexBuffer.UVKind);
  103735. defines.push("#define UV1");
  103736. }
  103737. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  103738. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  103739. defines.push("#define UV2");
  103740. }
  103741. }
  103742. //Logarithmic depth
  103743. if (material.useLogarithmicDepth) {
  103744. defines.push("#define LOGARITHMICDEPTH");
  103745. }
  103746. }
  103747. // Bones
  103748. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  103749. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  103750. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  103751. if (mesh.numBoneInfluencers > 4) {
  103752. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  103753. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  103754. }
  103755. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  103756. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  103757. }
  103758. else {
  103759. defines.push("#define NUM_BONE_INFLUENCERS 0");
  103760. }
  103761. // Instances
  103762. if (useInstances) {
  103763. defines.push("#define INSTANCES");
  103764. attribs.push("world0");
  103765. attribs.push("world1");
  103766. attribs.push("world2");
  103767. attribs.push("world3");
  103768. }
  103769. // Get correct effect
  103770. var join = defines.join("\n");
  103771. if (this._cachedDefines !== join) {
  103772. this._cachedDefines = join;
  103773. this._effect = this.scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  103774. }
  103775. return this._effect.isReady();
  103776. };
  103777. OutlineRenderer.prototype._beforeRenderingMesh = function (mesh, subMesh, batch) {
  103778. // Outline - step 1
  103779. this._savedDepthWrite = this._engine.getDepthWrite();
  103780. if (mesh.renderOutline) {
  103781. this._engine.setDepthWrite(false);
  103782. this.render(subMesh, batch);
  103783. this._engine.setDepthWrite(this._savedDepthWrite);
  103784. }
  103785. };
  103786. OutlineRenderer.prototype._afterRenderingMesh = function (mesh, subMesh, batch) {
  103787. // Outline - step 2
  103788. if (mesh.renderOutline && this._savedDepthWrite) {
  103789. this._engine.setDepthWrite(true);
  103790. this._engine.setColorWrite(false);
  103791. this.render(subMesh, batch);
  103792. this._engine.setColorWrite(true);
  103793. }
  103794. // Overlay
  103795. if (mesh.renderOverlay) {
  103796. var currentMode = this._engine.getAlphaMode();
  103797. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  103798. this.render(subMesh, batch, true);
  103799. this._engine.setAlphaMode(currentMode);
  103800. }
  103801. };
  103802. return OutlineRenderer;
  103803. }());
  103804. BABYLON.OutlineRenderer = OutlineRenderer;
  103805. })(BABYLON || (BABYLON = {}));
  103806. //# sourceMappingURL=babylon.outlineRenderer.js.map
  103807. var BABYLON;
  103808. (function (BABYLON) {
  103809. BABYLON.AbstractMesh.prototype.disableEdgesRendering = function () {
  103810. if (this._edgesRenderer) {
  103811. this._edgesRenderer.dispose();
  103812. this._edgesRenderer = null;
  103813. }
  103814. return this;
  103815. };
  103816. BABYLON.AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  103817. if (epsilon === void 0) { epsilon = 0.95; }
  103818. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  103819. this.disableEdgesRendering();
  103820. this._edgesRenderer = new EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  103821. return this;
  103822. };
  103823. Object.defineProperty(BABYLON.AbstractMesh.prototype, "edgesRenderer", {
  103824. get: function () {
  103825. return this._edgesRenderer;
  103826. },
  103827. enumerable: true,
  103828. configurable: true
  103829. });
  103830. BABYLON.LinesMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  103831. if (epsilon === void 0) { epsilon = 0.95; }
  103832. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  103833. this.disableEdgesRendering();
  103834. this._edgesRenderer = new BABYLON.LineEdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  103835. return this;
  103836. };
  103837. /**
  103838. * FaceAdjacencies Helper class to generate edges
  103839. */
  103840. var FaceAdjacencies = /** @class */ (function () {
  103841. function FaceAdjacencies() {
  103842. this.edges = new Array();
  103843. this.edgesConnectedCount = 0;
  103844. }
  103845. return FaceAdjacencies;
  103846. }());
  103847. /**
  103848. * This class is used to generate edges of the mesh that could then easily be rendered in a scene.
  103849. */
  103850. var EdgesRenderer = /** @class */ (function () {
  103851. /**
  103852. * Creates an instance of the EdgesRenderer. It is primarily use to display edges of a mesh.
  103853. * Beware when you use this class with complex objects as the adjacencies computation can be really long
  103854. * @param source Mesh used to create edges
  103855. * @param epsilon sum of angles in adjacency to check for edge
  103856. * @param checkVerticesInsteadOfIndices
  103857. * @param generateEdgesLines - should generate Lines or only prepare resources.
  103858. */
  103859. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices, generateEdgesLines) {
  103860. if (epsilon === void 0) { epsilon = 0.95; }
  103861. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  103862. if (generateEdgesLines === void 0) { generateEdgesLines = true; }
  103863. var _this = this;
  103864. /**
  103865. * Define the size of the edges with an orthographic camera
  103866. */
  103867. this.edgesWidthScalerForOrthographic = 1000.0;
  103868. /**
  103869. * Define the size of the edges with a perspective camera
  103870. */
  103871. this.edgesWidthScalerForPerspective = 50.0;
  103872. this._linesPositions = new Array();
  103873. this._linesNormals = new Array();
  103874. this._linesIndices = new Array();
  103875. this._buffers = {};
  103876. this._checkVerticesInsteadOfIndices = false;
  103877. /** Gets or sets a boolean indicating if the edgesRenderer is active */
  103878. this.isEnabled = true;
  103879. this._source = source;
  103880. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  103881. this._epsilon = epsilon;
  103882. this._prepareRessources();
  103883. if (generateEdgesLines) {
  103884. this._generateEdgesLines();
  103885. }
  103886. this._meshRebuildObserver = this._source.onRebuildObservable.add(function () {
  103887. _this._rebuild();
  103888. });
  103889. this._meshDisposeObserver = this._source.onDisposeObservable.add(function () {
  103890. _this.dispose();
  103891. });
  103892. }
  103893. EdgesRenderer.prototype._prepareRessources = function () {
  103894. if (this._lineShader) {
  103895. return;
  103896. }
  103897. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  103898. attributes: ["position", "normal"],
  103899. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  103900. });
  103901. this._lineShader.disableDepthWrite = true;
  103902. this._lineShader.backFaceCulling = false;
  103903. };
  103904. /** @hidden */
  103905. EdgesRenderer.prototype._rebuild = function () {
  103906. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  103907. if (buffer) {
  103908. buffer._rebuild();
  103909. }
  103910. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  103911. if (buffer) {
  103912. buffer._rebuild();
  103913. }
  103914. var scene = this._source.getScene();
  103915. var engine = scene.getEngine();
  103916. this._ib = engine.createIndexBuffer(this._linesIndices);
  103917. };
  103918. /**
  103919. * Releases the required resources for the edges renderer
  103920. */
  103921. EdgesRenderer.prototype.dispose = function () {
  103922. this._source.onRebuildObservable.remove(this._meshRebuildObserver);
  103923. this._source.onDisposeObservable.remove(this._meshDisposeObserver);
  103924. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  103925. if (buffer) {
  103926. buffer.dispose();
  103927. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  103928. }
  103929. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  103930. if (buffer) {
  103931. buffer.dispose();
  103932. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  103933. }
  103934. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  103935. this._lineShader.dispose();
  103936. };
  103937. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  103938. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  103939. return 0;
  103940. }
  103941. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  103942. return 1;
  103943. }
  103944. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  103945. return 2;
  103946. }
  103947. return -1;
  103948. };
  103949. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  103950. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  103951. return 0;
  103952. }
  103953. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  103954. return 1;
  103955. }
  103956. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  103957. return 2;
  103958. }
  103959. return -1;
  103960. };
  103961. /**
  103962. * Checks if the pair of p0 and p1 is en edge
  103963. * @param faceIndex
  103964. * @param edge
  103965. * @param faceNormals
  103966. * @param p0
  103967. * @param p1
  103968. * @private
  103969. */
  103970. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  103971. var needToCreateLine;
  103972. if (edge === undefined) {
  103973. needToCreateLine = true;
  103974. }
  103975. else {
  103976. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  103977. needToCreateLine = dotProduct < this._epsilon;
  103978. }
  103979. if (needToCreateLine) {
  103980. var offset = this._linesPositions.length / 3;
  103981. var normal = p0.subtract(p1);
  103982. normal.normalize();
  103983. // Positions
  103984. this._linesPositions.push(p0.x);
  103985. this._linesPositions.push(p0.y);
  103986. this._linesPositions.push(p0.z);
  103987. this._linesPositions.push(p0.x);
  103988. this._linesPositions.push(p0.y);
  103989. this._linesPositions.push(p0.z);
  103990. this._linesPositions.push(p1.x);
  103991. this._linesPositions.push(p1.y);
  103992. this._linesPositions.push(p1.z);
  103993. this._linesPositions.push(p1.x);
  103994. this._linesPositions.push(p1.y);
  103995. this._linesPositions.push(p1.z);
  103996. // Normals
  103997. this._linesNormals.push(p1.x);
  103998. this._linesNormals.push(p1.y);
  103999. this._linesNormals.push(p1.z);
  104000. this._linesNormals.push(-1);
  104001. this._linesNormals.push(p1.x);
  104002. this._linesNormals.push(p1.y);
  104003. this._linesNormals.push(p1.z);
  104004. this._linesNormals.push(1);
  104005. this._linesNormals.push(p0.x);
  104006. this._linesNormals.push(p0.y);
  104007. this._linesNormals.push(p0.z);
  104008. this._linesNormals.push(-1);
  104009. this._linesNormals.push(p0.x);
  104010. this._linesNormals.push(p0.y);
  104011. this._linesNormals.push(p0.z);
  104012. this._linesNormals.push(1);
  104013. // Indices
  104014. this._linesIndices.push(offset);
  104015. this._linesIndices.push(offset + 1);
  104016. this._linesIndices.push(offset + 2);
  104017. this._linesIndices.push(offset);
  104018. this._linesIndices.push(offset + 2);
  104019. this._linesIndices.push(offset + 3);
  104020. }
  104021. };
  104022. /**
  104023. * Generates lines edges from adjacencjes
  104024. * @private
  104025. */
  104026. EdgesRenderer.prototype._generateEdgesLines = function () {
  104027. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  104028. var indices = this._source.getIndices();
  104029. if (!indices || !positions) {
  104030. return;
  104031. }
  104032. // First let's find adjacencies
  104033. var adjacencies = new Array();
  104034. var faceNormals = new Array();
  104035. var index;
  104036. var faceAdjacencies;
  104037. // Prepare faces
  104038. for (index = 0; index < indices.length; index += 3) {
  104039. faceAdjacencies = new FaceAdjacencies();
  104040. var p0Index = indices[index];
  104041. var p1Index = indices[index + 1];
  104042. var p2Index = indices[index + 2];
  104043. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  104044. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  104045. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  104046. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  104047. faceNormal.normalize();
  104048. faceNormals.push(faceNormal);
  104049. adjacencies.push(faceAdjacencies);
  104050. }
  104051. // Scan
  104052. for (index = 0; index < adjacencies.length; index++) {
  104053. faceAdjacencies = adjacencies[index];
  104054. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  104055. var otherFaceAdjacencies = adjacencies[otherIndex];
  104056. if (faceAdjacencies.edgesConnectedCount === 3) { // Full
  104057. break;
  104058. }
  104059. if (otherFaceAdjacencies.edgesConnectedCount === 3) { // Full
  104060. continue;
  104061. }
  104062. var otherP0 = indices[otherIndex * 3];
  104063. var otherP1 = indices[otherIndex * 3 + 1];
  104064. var otherP2 = indices[otherIndex * 3 + 2];
  104065. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  104066. var otherEdgeIndex = 0;
  104067. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  104068. continue;
  104069. }
  104070. switch (edgeIndex) {
  104071. case 0:
  104072. if (this._checkVerticesInsteadOfIndices) {
  104073. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  104074. }
  104075. else {
  104076. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  104077. }
  104078. break;
  104079. case 1:
  104080. if (this._checkVerticesInsteadOfIndices) {
  104081. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  104082. }
  104083. else {
  104084. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  104085. }
  104086. break;
  104087. case 2:
  104088. if (this._checkVerticesInsteadOfIndices) {
  104089. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  104090. }
  104091. else {
  104092. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  104093. }
  104094. break;
  104095. }
  104096. if (otherEdgeIndex === -1) {
  104097. continue;
  104098. }
  104099. faceAdjacencies.edges[edgeIndex] = otherIndex;
  104100. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  104101. faceAdjacencies.edgesConnectedCount++;
  104102. otherFaceAdjacencies.edgesConnectedCount++;
  104103. if (faceAdjacencies.edgesConnectedCount === 3) {
  104104. break;
  104105. }
  104106. }
  104107. }
  104108. }
  104109. // Create lines
  104110. for (index = 0; index < adjacencies.length; index++) {
  104111. // 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
  104112. var current = adjacencies[index];
  104113. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  104114. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  104115. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  104116. }
  104117. // Merge into a single mesh
  104118. var engine = this._source.getScene().getEngine();
  104119. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  104120. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  104121. this._ib = engine.createIndexBuffer(this._linesIndices);
  104122. this._indicesCount = this._linesIndices.length;
  104123. };
  104124. /**
  104125. * Checks wether or not the edges renderer is ready to render.
  104126. * @return true if ready, otherwise false.
  104127. */
  104128. EdgesRenderer.prototype.isReady = function () {
  104129. return this._lineShader.isReady();
  104130. };
  104131. /**
  104132. * Renders the edges of the attached mesh,
  104133. */
  104134. EdgesRenderer.prototype.render = function () {
  104135. var scene = this._source.getScene();
  104136. if (!this.isReady() || !scene.activeCamera) {
  104137. return;
  104138. }
  104139. var engine = scene.getEngine();
  104140. this._lineShader._preBind();
  104141. if (this._source.edgesColor.a !== 1) {
  104142. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  104143. }
  104144. else {
  104145. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  104146. }
  104147. // VBOs
  104148. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  104149. scene.resetCachedMaterial();
  104150. this._lineShader.setColor4("color", this._source.edgesColor);
  104151. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  104152. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  104153. }
  104154. else {
  104155. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  104156. }
  104157. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  104158. this._lineShader.bind(this._source.getWorldMatrix());
  104159. // Draw order
  104160. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._indicesCount);
  104161. this._lineShader.unbind();
  104162. };
  104163. return EdgesRenderer;
  104164. }());
  104165. BABYLON.EdgesRenderer = EdgesRenderer;
  104166. })(BABYLON || (BABYLON = {}));
  104167. //# sourceMappingURL=babylon.edgesRenderer.js.map
  104168. var BABYLON;
  104169. (function (BABYLON) {
  104170. /**
  104171. * FaceAdjacencies Helper class to generate edges
  104172. */
  104173. var FaceAdjacencies = /** @class */ (function () {
  104174. function FaceAdjacencies() {
  104175. this.edges = new Array();
  104176. this.edgesConnectedCount = 0;
  104177. }
  104178. return FaceAdjacencies;
  104179. }());
  104180. /**
  104181. * LineEdgesRenderer for LineMeshes to remove unnecessary triangulation
  104182. */
  104183. var LineEdgesRenderer = /** @class */ (function (_super) {
  104184. __extends(LineEdgesRenderer, _super);
  104185. /**
  104186. * This constructor turns off auto generating edges line in Edges Renderer to make it here.
  104187. * @param source LineMesh used to generate edges
  104188. * @param epsilon not important (specified angle for edge detection)
  104189. * @param checkVerticesInsteadOfIndices not important for LineMesh
  104190. */
  104191. function LineEdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  104192. if (epsilon === void 0) { epsilon = 0.95; }
  104193. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  104194. var _this = _super.call(this, source, epsilon, checkVerticesInsteadOfIndices, false) || this;
  104195. _this._generateEdgesLines();
  104196. return _this;
  104197. }
  104198. /**
  104199. * Always create the edge since its a line so only important things are p0 and p1
  104200. * @param faceIndex not important for LineMesh
  104201. * @param edge not important for LineMesh
  104202. * @param faceNormals not important for LineMesh
  104203. * @param p0 beginnig of line
  104204. * @param p1 end of line
  104205. */
  104206. LineEdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  104207. var offset = this._linesPositions.length / 3;
  104208. var normal = p0.subtract(p1);
  104209. normal.normalize();
  104210. // Positions
  104211. this._linesPositions.push(p0.x);
  104212. this._linesPositions.push(p0.y);
  104213. this._linesPositions.push(p0.z);
  104214. this._linesPositions.push(p0.x);
  104215. this._linesPositions.push(p0.y);
  104216. this._linesPositions.push(p0.z);
  104217. this._linesPositions.push(p1.x);
  104218. this._linesPositions.push(p1.y);
  104219. this._linesPositions.push(p1.z);
  104220. this._linesPositions.push(p1.x);
  104221. this._linesPositions.push(p1.y);
  104222. this._linesPositions.push(p1.z);
  104223. // Normals
  104224. this._linesNormals.push(p1.x);
  104225. this._linesNormals.push(p1.y);
  104226. this._linesNormals.push(p1.z);
  104227. this._linesNormals.push(-1);
  104228. this._linesNormals.push(p1.x);
  104229. this._linesNormals.push(p1.y);
  104230. this._linesNormals.push(p1.z);
  104231. this._linesNormals.push(1);
  104232. this._linesNormals.push(p0.x);
  104233. this._linesNormals.push(p0.y);
  104234. this._linesNormals.push(p0.z);
  104235. this._linesNormals.push(-1);
  104236. this._linesNormals.push(p0.x);
  104237. this._linesNormals.push(p0.y);
  104238. this._linesNormals.push(p0.z);
  104239. this._linesNormals.push(1);
  104240. // Indices
  104241. this._linesIndices.push(offset);
  104242. this._linesIndices.push(offset + 1);
  104243. this._linesIndices.push(offset + 2);
  104244. this._linesIndices.push(offset);
  104245. this._linesIndices.push(offset + 2);
  104246. this._linesIndices.push(offset + 3);
  104247. };
  104248. /**
  104249. * Generate edges for each line in LinesMesh. Every Line should be rendered as edge.
  104250. */
  104251. LineEdgesRenderer.prototype._generateEdgesLines = function () {
  104252. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  104253. var indices = this._source.getIndices();
  104254. if (!indices || !positions) {
  104255. return;
  104256. }
  104257. // First let's find adjacencies
  104258. var adjacencies = new Array();
  104259. var faceNormals = new Array();
  104260. var index;
  104261. for (var i = 0; i < (positions.length / 3) - 1; i++) {
  104262. var currentAdjecancy = new FaceAdjacencies();
  104263. currentAdjecancy.p0 = new BABYLON.Vector3(positions[i * 3], positions[i * 3 + 1], positions[i * 3 + 2]);
  104264. currentAdjecancy.p1 = new BABYLON.Vector3(positions[(i + 1) * 3], positions[(i + 1) * 3 + 1], positions[(i + 1) * 3 + 2]);
  104265. adjacencies.push(currentAdjecancy);
  104266. }
  104267. // Create lines
  104268. for (index = 0; index < adjacencies.length; index++) {
  104269. // 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
  104270. var current = adjacencies[index];
  104271. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  104272. }
  104273. // Merge into a single mesh
  104274. var engine = this._source.getScene().getEngine();
  104275. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  104276. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  104277. this._ib = engine.createIndexBuffer(this._linesIndices);
  104278. this._indicesCount = this._linesIndices.length;
  104279. };
  104280. return LineEdgesRenderer;
  104281. }(BABYLON.EdgesRenderer));
  104282. BABYLON.LineEdgesRenderer = LineEdgesRenderer;
  104283. })(BABYLON || (BABYLON = {}));
  104284. //# sourceMappingURL=babylon.lineEdgesRenderer.js.map
  104285. var BABYLON;
  104286. (function (BABYLON) {
  104287. // Adds the parser to the scene parsers.
  104288. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_EFFECTLAYER, function (parsedData, scene, container, rootUrl) {
  104289. if (parsedData.effectLayers) {
  104290. if (!container.effectLayers) {
  104291. container.effectLayers = new Array();
  104292. }
  104293. for (var index = 0; index < parsedData.effectLayers.length; index++) {
  104294. var effectLayer = BABYLON.EffectLayer.Parse(parsedData.effectLayers[index], scene, rootUrl);
  104295. container.effectLayers.push(effectLayer);
  104296. }
  104297. }
  104298. });
  104299. BABYLON.AbstractScene.prototype.removeEffectLayer = function (toRemove) {
  104300. var index = this.effectLayers.indexOf(toRemove);
  104301. if (index !== -1) {
  104302. this.effectLayers.splice(index, 1);
  104303. }
  104304. return index;
  104305. };
  104306. BABYLON.AbstractScene.prototype.addEffectLayer = function (newEffectLayer) {
  104307. this.effectLayers.push(newEffectLayer);
  104308. };
  104309. /**
  104310. * Defines the layer scene component responsible to manage any effect layers
  104311. * in a given scene.
  104312. */
  104313. var EffectLayerSceneComponent = /** @class */ (function () {
  104314. /**
  104315. * Creates a new instance of the component for the given scene
  104316. * @param scene Defines the scene to register the component in
  104317. */
  104318. function EffectLayerSceneComponent(scene) {
  104319. /**
  104320. * The component name helpfull to identify the component in the list of scene components.
  104321. */
  104322. this.name = BABYLON.SceneComponentConstants.NAME_EFFECTLAYER;
  104323. this._renderEffects = false;
  104324. this._needStencil = false;
  104325. this._previousStencilState = false;
  104326. this.scene = scene;
  104327. this._engine = scene.getEngine();
  104328. scene.effectLayers = new Array();
  104329. }
  104330. /**
  104331. * Registers the component in a given scene
  104332. */
  104333. EffectLayerSceneComponent.prototype.register = function () {
  104334. this.scene._isReadyForMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_ISREADYFORMESH_EFFECTLAYER, this, this._isReadyForMesh);
  104335. this.scene._cameraDrawRenderTargetStage.registerStep(BABYLON.SceneComponentConstants.STEP_CAMERADRAWRENDERTARGET_EFFECTLAYER, this, this._renderMainTexture);
  104336. this.scene._beforeCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERADRAW_EFFECTLAYER, this, this._setStencil);
  104337. this.scene._afterRenderingGroupDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERRENDERINGGROUPDRAW_EFFECTLAYER_DRAW, this, this._drawRenderingGroup);
  104338. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER, this, this._setStencilBack);
  104339. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER_DRAW, this, this._drawCamera);
  104340. };
  104341. /**
  104342. * Rebuilds the elements related to this component in case of
  104343. * context lost for instance.
  104344. */
  104345. EffectLayerSceneComponent.prototype.rebuild = function () {
  104346. var layers = this.scene.effectLayers;
  104347. for (var _i = 0, layers_1 = layers; _i < layers_1.length; _i++) {
  104348. var effectLayer = layers_1[_i];
  104349. effectLayer._rebuild();
  104350. }
  104351. };
  104352. /**
  104353. * Serializes the component data to the specified json object
  104354. * @param serializationObject The object to serialize to
  104355. */
  104356. EffectLayerSceneComponent.prototype.serialize = function (serializationObject) {
  104357. // Effect layers
  104358. serializationObject.effectLayers = [];
  104359. var layers = this.scene.effectLayers;
  104360. for (var _i = 0, layers_2 = layers; _i < layers_2.length; _i++) {
  104361. var effectLayer = layers_2[_i];
  104362. if (effectLayer.serialize) {
  104363. serializationObject.effectLayers.push(effectLayer.serialize());
  104364. }
  104365. }
  104366. };
  104367. /**
  104368. * Adds all the element from the container to the scene
  104369. * @param container the container holding the elements
  104370. */
  104371. EffectLayerSceneComponent.prototype.addFromContainer = function (container) {
  104372. var _this = this;
  104373. if (!container.effectLayers) {
  104374. return;
  104375. }
  104376. container.effectLayers.forEach(function (o) {
  104377. _this.scene.addEffectLayer(o);
  104378. });
  104379. };
  104380. /**
  104381. * Removes all the elements in the container from the scene
  104382. * @param container contains the elements to remove
  104383. */
  104384. EffectLayerSceneComponent.prototype.removeFromContainer = function (container) {
  104385. var _this = this;
  104386. if (!container.effectLayers) {
  104387. return;
  104388. }
  104389. container.effectLayers.forEach(function (o) {
  104390. _this.scene.removeEffectLayer(o);
  104391. });
  104392. };
  104393. /**
  104394. * Disposes the component and the associated ressources.
  104395. */
  104396. EffectLayerSceneComponent.prototype.dispose = function () {
  104397. var layers = this.scene.effectLayers;
  104398. while (layers.length) {
  104399. layers[0].dispose();
  104400. }
  104401. };
  104402. EffectLayerSceneComponent.prototype._isReadyForMesh = function (mesh, hardwareInstancedRendering) {
  104403. var layers = this.scene.effectLayers;
  104404. for (var _i = 0, layers_3 = layers; _i < layers_3.length; _i++) {
  104405. var layer = layers_3[_i];
  104406. if (!layer.hasMesh(mesh)) {
  104407. continue;
  104408. }
  104409. for (var _a = 0, _b = mesh.subMeshes; _a < _b.length; _a++) {
  104410. var subMesh = _b[_a];
  104411. if (!layer.isReady(subMesh, hardwareInstancedRendering)) {
  104412. return false;
  104413. }
  104414. }
  104415. }
  104416. return true;
  104417. };
  104418. EffectLayerSceneComponent.prototype._renderMainTexture = function (camera) {
  104419. this._renderEffects = false;
  104420. this._needStencil = false;
  104421. var layers = this.scene.effectLayers;
  104422. if (layers && layers.length > 0) {
  104423. this._previousStencilState = this._engine.getStencilBuffer();
  104424. for (var _i = 0, layers_4 = layers; _i < layers_4.length; _i++) {
  104425. var effectLayer = layers_4[_i];
  104426. if (effectLayer.shouldRender() &&
  104427. (!effectLayer.camera ||
  104428. (effectLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === effectLayer.camera) ||
  104429. (effectLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && effectLayer.camera._rigCameras.indexOf(camera) > -1))) {
  104430. this._renderEffects = true;
  104431. this._needStencil = this._needStencil || effectLayer.needStencil();
  104432. var renderTarget = effectLayer._mainTexture;
  104433. if (renderTarget._shouldRender()) {
  104434. this.scene.incrementRenderId();
  104435. renderTarget.render(false, false);
  104436. }
  104437. }
  104438. }
  104439. this.scene.incrementRenderId();
  104440. }
  104441. };
  104442. EffectLayerSceneComponent.prototype._setStencil = function (camera) {
  104443. // Activate effect Layer stencil
  104444. if (this._needStencil) {
  104445. this._engine.setStencilBuffer(true);
  104446. }
  104447. };
  104448. EffectLayerSceneComponent.prototype._setStencilBack = function (camera) {
  104449. // Restore effect Layer stencil
  104450. if (this._needStencil) {
  104451. this._engine.setStencilBuffer(this._previousStencilState);
  104452. }
  104453. };
  104454. EffectLayerSceneComponent.prototype._draw = function (renderingGroupId) {
  104455. if (this._renderEffects) {
  104456. this._engine.setDepthBuffer(false);
  104457. var layers = this.scene.effectLayers;
  104458. for (var i = 0; i < layers.length; i++) {
  104459. var effectLayer = layers[i];
  104460. if (effectLayer.renderingGroupId === renderingGroupId) {
  104461. if (effectLayer.shouldRender()) {
  104462. effectLayer.render();
  104463. }
  104464. }
  104465. }
  104466. this._engine.setDepthBuffer(true);
  104467. }
  104468. };
  104469. EffectLayerSceneComponent.prototype._drawCamera = function (camera) {
  104470. if (this._renderEffects) {
  104471. this._draw(-1);
  104472. }
  104473. };
  104474. EffectLayerSceneComponent.prototype._drawRenderingGroup = function (index) {
  104475. if (!this.scene._isInIntermediateRendering() && this._renderEffects) {
  104476. this._draw(index);
  104477. }
  104478. };
  104479. return EffectLayerSceneComponent;
  104480. }());
  104481. BABYLON.EffectLayerSceneComponent = EffectLayerSceneComponent;
  104482. })(BABYLON || (BABYLON = {}));
  104483. //# sourceMappingURL=babylon.effectLayerSceneComponent.js.map
  104484. var __assign = (this && this.__assign) || function () {
  104485. __assign = Object.assign || function(t) {
  104486. for (var s, i = 1, n = arguments.length; i < n; i++) {
  104487. s = arguments[i];
  104488. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  104489. t[p] = s[p];
  104490. }
  104491. return t;
  104492. };
  104493. return __assign.apply(this, arguments);
  104494. };
  104495. var BABYLON;
  104496. (function (BABYLON) {
  104497. /**
  104498. * The effect layer Helps adding post process effect blended with the main pass.
  104499. *
  104500. * This can be for instance use to generate glow or higlight effects on the scene.
  104501. *
  104502. * The effect layer class can not be used directly and is intented to inherited from to be
  104503. * customized per effects.
  104504. */
  104505. var EffectLayer = /** @class */ (function () {
  104506. /**
  104507. * Instantiates a new effect Layer and references it in the scene.
  104508. * @param name The name of the layer
  104509. * @param scene The scene to use the layer in
  104510. */
  104511. function EffectLayer(
  104512. /** The Friendly of the effect in the scene */
  104513. name, scene) {
  104514. this._vertexBuffers = {};
  104515. this._maxSize = 0;
  104516. this._mainTextureDesiredSize = { width: 0, height: 0 };
  104517. this._shouldRender = true;
  104518. this._postProcesses = [];
  104519. this._textures = [];
  104520. this._emissiveTextureAndColor = { texture: null, color: new BABYLON.Color4() };
  104521. /**
  104522. * The clear color of the texture used to generate the glow map.
  104523. */
  104524. this.neutralColor = new BABYLON.Color4();
  104525. /**
  104526. * Specifies wether the highlight layer is enabled or not.
  104527. */
  104528. this.isEnabled = true;
  104529. /**
  104530. * An event triggered when the effect layer has been disposed.
  104531. */
  104532. this.onDisposeObservable = new BABYLON.Observable();
  104533. /**
  104534. * An event triggered when the effect layer is about rendering the main texture with the glowy parts.
  104535. */
  104536. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  104537. /**
  104538. * An event triggered when the generated texture is being merged in the scene.
  104539. */
  104540. this.onBeforeComposeObservable = new BABYLON.Observable();
  104541. /**
  104542. * An event triggered when the generated texture has been merged in the scene.
  104543. */
  104544. this.onAfterComposeObservable = new BABYLON.Observable();
  104545. /**
  104546. * An event triggered when the efffect layer changes its size.
  104547. */
  104548. this.onSizeChangedObservable = new BABYLON.Observable();
  104549. this.name = name;
  104550. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  104551. var component = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_EFFECTLAYER);
  104552. if (!component) {
  104553. component = new BABYLON.EffectLayerSceneComponent(this._scene);
  104554. this._scene._addComponent(component);
  104555. }
  104556. this._engine = this._scene.getEngine();
  104557. this._maxSize = this._engine.getCaps().maxTextureSize;
  104558. this._scene.effectLayers.push(this);
  104559. // Generate Buffers
  104560. this._generateIndexBuffer();
  104561. this._genrateVertexBuffer();
  104562. }
  104563. Object.defineProperty(EffectLayer.prototype, "camera", {
  104564. /**
  104565. * Gets the camera attached to the layer.
  104566. */
  104567. get: function () {
  104568. return this._effectLayerOptions.camera;
  104569. },
  104570. enumerable: true,
  104571. configurable: true
  104572. });
  104573. Object.defineProperty(EffectLayer.prototype, "renderingGroupId", {
  104574. /**
  104575. * Gets the rendering group id the layer should render in.
  104576. */
  104577. get: function () {
  104578. return this._effectLayerOptions.renderingGroupId;
  104579. },
  104580. enumerable: true,
  104581. configurable: true
  104582. });
  104583. /**
  104584. * Initializes the effect layer with the required options.
  104585. * @param options Sets of none mandatory options to use with the layer (see IEffectLayerOptions for more information)
  104586. */
  104587. EffectLayer.prototype._init = function (options) {
  104588. // Adapt options
  104589. this._effectLayerOptions = __assign({ mainTextureRatio: 0.5, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null, renderingGroupId: -1 }, options);
  104590. this._setMainTextureSize();
  104591. this._createMainTexture();
  104592. this._createTextureAndPostProcesses();
  104593. this._mergeEffect = this._createMergeEffect();
  104594. };
  104595. /**
  104596. * Generates the index buffer of the full screen quad blending to the main canvas.
  104597. */
  104598. EffectLayer.prototype._generateIndexBuffer = function () {
  104599. // Indices
  104600. var indices = [];
  104601. indices.push(0);
  104602. indices.push(1);
  104603. indices.push(2);
  104604. indices.push(0);
  104605. indices.push(2);
  104606. indices.push(3);
  104607. this._indexBuffer = this._engine.createIndexBuffer(indices);
  104608. };
  104609. /**
  104610. * Generates the vertex buffer of the full screen quad blending to the main canvas.
  104611. */
  104612. EffectLayer.prototype._genrateVertexBuffer = function () {
  104613. // VBO
  104614. var vertices = [];
  104615. vertices.push(1, 1);
  104616. vertices.push(-1, 1);
  104617. vertices.push(-1, -1);
  104618. vertices.push(1, -1);
  104619. var vertexBuffer = new BABYLON.VertexBuffer(this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  104620. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  104621. };
  104622. /**
  104623. * Sets the main texture desired size which is the closest power of two
  104624. * of the engine canvas size.
  104625. */
  104626. EffectLayer.prototype._setMainTextureSize = function () {
  104627. if (this._effectLayerOptions.mainTextureFixedSize) {
  104628. this._mainTextureDesiredSize.width = this._effectLayerOptions.mainTextureFixedSize;
  104629. this._mainTextureDesiredSize.height = this._effectLayerOptions.mainTextureFixedSize;
  104630. }
  104631. else {
  104632. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._effectLayerOptions.mainTextureRatio;
  104633. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._effectLayerOptions.mainTextureRatio;
  104634. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  104635. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  104636. }
  104637. this._mainTextureDesiredSize.width = Math.floor(this._mainTextureDesiredSize.width);
  104638. this._mainTextureDesiredSize.height = Math.floor(this._mainTextureDesiredSize.height);
  104639. };
  104640. /**
  104641. * Creates the main texture for the effect layer.
  104642. */
  104643. EffectLayer.prototype._createMainTexture = function () {
  104644. var _this = this;
  104645. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  104646. width: this._mainTextureDesiredSize.width,
  104647. height: this._mainTextureDesiredSize.height
  104648. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  104649. this._mainTexture.activeCamera = this._effectLayerOptions.camera;
  104650. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  104651. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  104652. this._mainTexture.anisotropicFilteringLevel = 1;
  104653. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  104654. this._mainTexture.renderParticles = false;
  104655. this._mainTexture.renderList = null;
  104656. this._mainTexture.ignoreCameraViewport = true;
  104657. // Custom render function
  104658. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  104659. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  104660. var index;
  104661. var engine = _this._scene.getEngine();
  104662. if (depthOnlySubMeshes.length) {
  104663. engine.setColorWrite(false);
  104664. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  104665. _this._renderSubMesh(depthOnlySubMeshes.data[index]);
  104666. }
  104667. engine.setColorWrite(true);
  104668. }
  104669. for (index = 0; index < opaqueSubMeshes.length; index++) {
  104670. _this._renderSubMesh(opaqueSubMeshes.data[index]);
  104671. }
  104672. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  104673. _this._renderSubMesh(alphaTestSubMeshes.data[index]);
  104674. }
  104675. for (index = 0; index < transparentSubMeshes.length; index++) {
  104676. _this._renderSubMesh(transparentSubMeshes.data[index]);
  104677. }
  104678. };
  104679. this._mainTexture.onClearObservable.add(function (engine) {
  104680. engine.clear(_this.neutralColor, true, true, true);
  104681. });
  104682. };
  104683. /**
  104684. * Checks for the readiness of the element composing the layer.
  104685. * @param subMesh the mesh to check for
  104686. * @param useInstances specify wether or not to use instances to render the mesh
  104687. * @param emissiveTexture the associated emissive texture used to generate the glow
  104688. * @return true if ready otherwise, false
  104689. */
  104690. EffectLayer.prototype._isReady = function (subMesh, useInstances, emissiveTexture) {
  104691. var material = subMesh.getMaterial();
  104692. if (!material) {
  104693. return false;
  104694. }
  104695. if (!material.isReady(subMesh.getMesh(), useInstances)) {
  104696. return false;
  104697. }
  104698. var defines = [];
  104699. var attribs = [BABYLON.VertexBuffer.PositionKind];
  104700. var mesh = subMesh.getMesh();
  104701. var uv1 = false;
  104702. var uv2 = false;
  104703. // Alpha test
  104704. if (material && material.needAlphaTesting()) {
  104705. var alphaTexture = material.getAlphaTestTexture();
  104706. if (alphaTexture) {
  104707. defines.push("#define ALPHATEST");
  104708. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  104709. alphaTexture.coordinatesIndex === 1) {
  104710. defines.push("#define DIFFUSEUV2");
  104711. uv2 = true;
  104712. }
  104713. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  104714. defines.push("#define DIFFUSEUV1");
  104715. uv1 = true;
  104716. }
  104717. }
  104718. }
  104719. // Emissive
  104720. if (emissiveTexture) {
  104721. defines.push("#define EMISSIVE");
  104722. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  104723. emissiveTexture.coordinatesIndex === 1) {
  104724. defines.push("#define EMISSIVEUV2");
  104725. uv2 = true;
  104726. }
  104727. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  104728. defines.push("#define EMISSIVEUV1");
  104729. uv1 = true;
  104730. }
  104731. }
  104732. if (uv1) {
  104733. attribs.push(BABYLON.VertexBuffer.UVKind);
  104734. defines.push("#define UV1");
  104735. }
  104736. if (uv2) {
  104737. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  104738. defines.push("#define UV2");
  104739. }
  104740. // Bones
  104741. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  104742. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  104743. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  104744. if (mesh.numBoneInfluencers > 4) {
  104745. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  104746. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  104747. }
  104748. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  104749. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  104750. }
  104751. else {
  104752. defines.push("#define NUM_BONE_INFLUENCERS 0");
  104753. }
  104754. // Morph targets
  104755. var manager = mesh.morphTargetManager;
  104756. var morphInfluencers = 0;
  104757. if (manager) {
  104758. if (manager.numInfluencers > 0) {
  104759. defines.push("#define MORPHTARGETS");
  104760. morphInfluencers = manager.numInfluencers;
  104761. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  104762. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  104763. }
  104764. }
  104765. // Instances
  104766. if (useInstances) {
  104767. defines.push("#define INSTANCES");
  104768. attribs.push("world0");
  104769. attribs.push("world1");
  104770. attribs.push("world2");
  104771. attribs.push("world3");
  104772. }
  104773. // Get correct effect
  104774. var join = defines.join("\n");
  104775. if (this._cachedDefines !== join) {
  104776. this._cachedDefines = join;
  104777. this._effectLayerMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix", "morphTargetInfluences"], ["diffuseSampler", "emissiveSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  104778. }
  104779. return this._effectLayerMapGenerationEffect.isReady();
  104780. };
  104781. /**
  104782. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  104783. */
  104784. EffectLayer.prototype.render = function () {
  104785. var currentEffect = this._mergeEffect;
  104786. // Check
  104787. if (!currentEffect.isReady())
  104788. return;
  104789. for (var i = 0; i < this._postProcesses.length; i++) {
  104790. if (!this._postProcesses[i].isReady()) {
  104791. return;
  104792. }
  104793. }
  104794. var engine = this._scene.getEngine();
  104795. this.onBeforeComposeObservable.notifyObservers(this);
  104796. // Render
  104797. engine.enableEffect(currentEffect);
  104798. engine.setState(false);
  104799. // VBOs
  104800. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  104801. // Cache
  104802. var previousAlphaMode = engine.getAlphaMode();
  104803. // Go Blend.
  104804. engine.setAlphaMode(this._effectLayerOptions.alphaBlendingMode);
  104805. // Blends the map on the main canvas.
  104806. this._internalRender(currentEffect);
  104807. // Restore Alpha
  104808. engine.setAlphaMode(previousAlphaMode);
  104809. this.onAfterComposeObservable.notifyObservers(this);
  104810. // Handle size changes.
  104811. var size = this._mainTexture.getSize();
  104812. this._setMainTextureSize();
  104813. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  104814. // Recreate RTT and post processes on size change.
  104815. this.onSizeChangedObservable.notifyObservers(this);
  104816. this._disposeTextureAndPostProcesses();
  104817. this._createMainTexture();
  104818. this._createTextureAndPostProcesses();
  104819. }
  104820. };
  104821. /**
  104822. * Determine if a given mesh will be used in the current effect.
  104823. * @param mesh mesh to test
  104824. * @returns true if the mesh will be used
  104825. */
  104826. EffectLayer.prototype.hasMesh = function (mesh) {
  104827. if (this.renderingGroupId === -1 || mesh.renderingGroupId === this.renderingGroupId) {
  104828. return true;
  104829. }
  104830. return false;
  104831. };
  104832. /**
  104833. * Returns true if the layer contains information to display, otherwise false.
  104834. * @returns true if the glow layer should be rendered
  104835. */
  104836. EffectLayer.prototype.shouldRender = function () {
  104837. return this.isEnabled && this._shouldRender;
  104838. };
  104839. /**
  104840. * Returns true if the mesh should render, otherwise false.
  104841. * @param mesh The mesh to render
  104842. * @returns true if it should render otherwise false
  104843. */
  104844. EffectLayer.prototype._shouldRenderMesh = function (mesh) {
  104845. return true;
  104846. };
  104847. /**
  104848. * Returns true if the mesh should render, otherwise false.
  104849. * @param mesh The mesh to render
  104850. * @returns true if it should render otherwise false
  104851. */
  104852. EffectLayer.prototype._shouldRenderEmissiveTextureForMesh = function (mesh) {
  104853. return true;
  104854. };
  104855. /**
  104856. * Renders the submesh passed in parameter to the generation map.
  104857. */
  104858. EffectLayer.prototype._renderSubMesh = function (subMesh) {
  104859. var _this = this;
  104860. if (!this.shouldRender()) {
  104861. return;
  104862. }
  104863. var material = subMesh.getMaterial();
  104864. var mesh = subMesh.getRenderingMesh();
  104865. var scene = this._scene;
  104866. var engine = scene.getEngine();
  104867. if (!material) {
  104868. return;
  104869. }
  104870. // Do not block in blend mode.
  104871. if (material.needAlphaBlendingForMesh(mesh)) {
  104872. return;
  104873. }
  104874. // Culling
  104875. engine.setState(material.backFaceCulling);
  104876. // Managing instances
  104877. var batch = mesh._getInstancesRenderList(subMesh._id);
  104878. if (batch.mustReturn) {
  104879. return;
  104880. }
  104881. // Early Exit per mesh
  104882. if (!this._shouldRenderMesh(mesh)) {
  104883. return;
  104884. }
  104885. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  104886. this._setEmissiveTextureAndColor(mesh, subMesh, material);
  104887. if (this._isReady(subMesh, hardwareInstancedRendering, this._emissiveTextureAndColor.texture)) {
  104888. engine.enableEffect(this._effectLayerMapGenerationEffect);
  104889. mesh._bind(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  104890. this._effectLayerMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  104891. this._effectLayerMapGenerationEffect.setFloat4("color", this._emissiveTextureAndColor.color.r, this._emissiveTextureAndColor.color.g, this._emissiveTextureAndColor.color.b, this._emissiveTextureAndColor.color.a);
  104892. // Alpha test
  104893. if (material && material.needAlphaTesting()) {
  104894. var alphaTexture = material.getAlphaTestTexture();
  104895. if (alphaTexture) {
  104896. this._effectLayerMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  104897. var textureMatrix = alphaTexture.getTextureMatrix();
  104898. if (textureMatrix) {
  104899. this._effectLayerMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix);
  104900. }
  104901. }
  104902. }
  104903. // Glow emissive only
  104904. if (this._emissiveTextureAndColor.texture) {
  104905. this._effectLayerMapGenerationEffect.setTexture("emissiveSampler", this._emissiveTextureAndColor.texture);
  104906. this._effectLayerMapGenerationEffect.setMatrix("emissiveMatrix", this._emissiveTextureAndColor.texture.getTextureMatrix());
  104907. }
  104908. // Bones
  104909. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  104910. this._effectLayerMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  104911. }
  104912. // Morph targets
  104913. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effectLayerMapGenerationEffect);
  104914. // Draw
  104915. mesh._processRendering(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effectLayerMapGenerationEffect.setMatrix("world", world); });
  104916. }
  104917. else {
  104918. // Need to reset refresh rate of the main map
  104919. this._mainTexture.resetRefreshCounter();
  104920. }
  104921. };
  104922. /**
  104923. * Rebuild the required buffers.
  104924. * @hidden Internal use only.
  104925. */
  104926. EffectLayer.prototype._rebuild = function () {
  104927. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  104928. if (vb) {
  104929. vb._rebuild();
  104930. }
  104931. this._generateIndexBuffer();
  104932. };
  104933. /**
  104934. * Dispose only the render target textures and post process.
  104935. */
  104936. EffectLayer.prototype._disposeTextureAndPostProcesses = function () {
  104937. this._mainTexture.dispose();
  104938. for (var i = 0; i < this._postProcesses.length; i++) {
  104939. if (this._postProcesses[i]) {
  104940. this._postProcesses[i].dispose();
  104941. }
  104942. }
  104943. this._postProcesses = [];
  104944. for (var i = 0; i < this._textures.length; i++) {
  104945. if (this._textures[i]) {
  104946. this._textures[i].dispose();
  104947. }
  104948. }
  104949. this._textures = [];
  104950. };
  104951. /**
  104952. * Dispose the highlight layer and free resources.
  104953. */
  104954. EffectLayer.prototype.dispose = function () {
  104955. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  104956. if (vertexBuffer) {
  104957. vertexBuffer.dispose();
  104958. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  104959. }
  104960. if (this._indexBuffer) {
  104961. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  104962. this._indexBuffer = null;
  104963. }
  104964. // Clean textures and post processes
  104965. this._disposeTextureAndPostProcesses();
  104966. // Remove from scene
  104967. var index = this._scene.effectLayers.indexOf(this, 0);
  104968. if (index > -1) {
  104969. this._scene.effectLayers.splice(index, 1);
  104970. }
  104971. // Callback
  104972. this.onDisposeObservable.notifyObservers(this);
  104973. this.onDisposeObservable.clear();
  104974. this.onBeforeRenderMainTextureObservable.clear();
  104975. this.onBeforeComposeObservable.clear();
  104976. this.onAfterComposeObservable.clear();
  104977. this.onSizeChangedObservable.clear();
  104978. };
  104979. /**
  104980. * Gets the class name of the effect layer
  104981. * @returns the string with the class name of the effect layer
  104982. */
  104983. EffectLayer.prototype.getClassName = function () {
  104984. return "EffectLayer";
  104985. };
  104986. /**
  104987. * Creates an effect layer from parsed effect layer data
  104988. * @param parsedEffectLayer defines effect layer data
  104989. * @param scene defines the current scene
  104990. * @param rootUrl defines the root URL containing the effect layer information
  104991. * @returns a parsed effect Layer
  104992. */
  104993. EffectLayer.Parse = function (parsedEffectLayer, scene, rootUrl) {
  104994. var effectLayerType = BABYLON.Tools.Instantiate(parsedEffectLayer.customType);
  104995. return effectLayerType.Parse(parsedEffectLayer, scene, rootUrl);
  104996. };
  104997. __decorate([
  104998. BABYLON.serialize()
  104999. ], EffectLayer.prototype, "name", void 0);
  105000. __decorate([
  105001. BABYLON.serializeAsColor4()
  105002. ], EffectLayer.prototype, "neutralColor", void 0);
  105003. __decorate([
  105004. BABYLON.serialize()
  105005. ], EffectLayer.prototype, "isEnabled", void 0);
  105006. __decorate([
  105007. BABYLON.serializeAsCameraReference()
  105008. ], EffectLayer.prototype, "camera", null);
  105009. __decorate([
  105010. BABYLON.serialize()
  105011. ], EffectLayer.prototype, "renderingGroupId", null);
  105012. return EffectLayer;
  105013. }());
  105014. BABYLON.EffectLayer = EffectLayer;
  105015. })(BABYLON || (BABYLON = {}));
  105016. //# sourceMappingURL=babylon.effectLayer.js.map
  105017. var BABYLON;
  105018. (function (BABYLON) {
  105019. BABYLON.AbstractScene.prototype.getHighlightLayerByName = function (name) {
  105020. for (var index = 0; index < this.effectLayers.length; index++) {
  105021. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === HighlightLayer.EffectName) {
  105022. return this.effectLayers[index];
  105023. }
  105024. }
  105025. return null;
  105026. };
  105027. /**
  105028. * Special Glow Blur post process only blurring the alpha channel
  105029. * It enforces keeping the most luminous color in the color channel.
  105030. */
  105031. var GlowBlurPostProcess = /** @class */ (function (_super) {
  105032. __extends(GlowBlurPostProcess, _super);
  105033. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  105034. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  105035. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  105036. _this.direction = direction;
  105037. _this.kernel = kernel;
  105038. _this.onApplyObservable.add(function (effect) {
  105039. effect.setFloat2("screenSize", _this.width, _this.height);
  105040. effect.setVector2("direction", _this.direction);
  105041. effect.setFloat("blurWidth", _this.kernel);
  105042. });
  105043. return _this;
  105044. }
  105045. return GlowBlurPostProcess;
  105046. }(BABYLON.PostProcess));
  105047. /**
  105048. * The highlight layer Helps adding a glow effect around a mesh.
  105049. *
  105050. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  105051. * glowy meshes to your scene.
  105052. *
  105053. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  105054. */
  105055. var HighlightLayer = /** @class */ (function (_super) {
  105056. __extends(HighlightLayer, _super);
  105057. /**
  105058. * Instantiates a new highlight Layer and references it to the scene..
  105059. * @param name The name of the layer
  105060. * @param scene The scene to use the layer in
  105061. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  105062. */
  105063. function HighlightLayer(name, scene, options) {
  105064. var _this = _super.call(this, name, scene) || this;
  105065. _this.name = name;
  105066. /**
  105067. * Specifies whether or not the inner glow is ACTIVE in the layer.
  105068. */
  105069. _this.innerGlow = true;
  105070. /**
  105071. * Specifies whether or not the outer glow is ACTIVE in the layer.
  105072. */
  105073. _this.outerGlow = true;
  105074. /**
  105075. * An event triggered when the highlight layer is being blurred.
  105076. */
  105077. _this.onBeforeBlurObservable = new BABYLON.Observable();
  105078. /**
  105079. * An event triggered when the highlight layer has been blurred.
  105080. */
  105081. _this.onAfterBlurObservable = new BABYLON.Observable();
  105082. _this._instanceGlowingMeshStencilReference = HighlightLayer.GlowingMeshStencilReference++;
  105083. _this._meshes = {};
  105084. _this._excludedMeshes = {};
  105085. _this.neutralColor = HighlightLayer.NeutralColor;
  105086. // Warn on stencil
  105087. if (!_this._engine.isStencilEnable) {
  105088. 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 }");
  105089. }
  105090. // Adapt options
  105091. _this._options = __assign({ mainTextureRatio: 0.5, blurTextureSizeRatio: 0.5, blurHorizontalSize: 1.0, blurVerticalSize: 1.0, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null, renderingGroupId: -1 }, options);
  105092. // Initialize the layer
  105093. _this._init({
  105094. alphaBlendingMode: _this._options.alphaBlendingMode,
  105095. camera: _this._options.camera,
  105096. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  105097. mainTextureRatio: _this._options.mainTextureRatio,
  105098. renderingGroupId: _this._options.renderingGroupId
  105099. });
  105100. // Do not render as long as no meshes have been added
  105101. _this._shouldRender = false;
  105102. return _this;
  105103. }
  105104. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  105105. /**
  105106. * Gets the horizontal size of the blur.
  105107. */
  105108. get: function () {
  105109. return this._horizontalBlurPostprocess.kernel;
  105110. },
  105111. /**
  105112. * Specifies the horizontal size of the blur.
  105113. */
  105114. set: function (value) {
  105115. this._horizontalBlurPostprocess.kernel = value;
  105116. },
  105117. enumerable: true,
  105118. configurable: true
  105119. });
  105120. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  105121. /**
  105122. * Gets the vertical size of the blur.
  105123. */
  105124. get: function () {
  105125. return this._verticalBlurPostprocess.kernel;
  105126. },
  105127. /**
  105128. * Specifies the vertical size of the blur.
  105129. */
  105130. set: function (value) {
  105131. this._verticalBlurPostprocess.kernel = value;
  105132. },
  105133. enumerable: true,
  105134. configurable: true
  105135. });
  105136. /**
  105137. * Get the effect name of the layer.
  105138. * @return The effect name
  105139. */
  105140. HighlightLayer.prototype.getEffectName = function () {
  105141. return HighlightLayer.EffectName;
  105142. };
  105143. /**
  105144. * Create the merge effect. This is the shader use to blit the information back
  105145. * to the main canvas at the end of the scene rendering.
  105146. */
  105147. HighlightLayer.prototype._createMergeEffect = function () {
  105148. // Effect
  105149. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], this._options.isStroke ? "#define STROKE \n" : undefined);
  105150. };
  105151. /**
  105152. * Creates the render target textures and post processes used in the highlight layer.
  105153. */
  105154. HighlightLayer.prototype._createTextureAndPostProcesses = function () {
  105155. var _this = this;
  105156. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  105157. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  105158. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  105159. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  105160. var textureType = 0;
  105161. if (this._engine.getCaps().textureHalfFloatRender) {
  105162. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  105163. }
  105164. else {
  105165. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  105166. }
  105167. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  105168. width: blurTextureWidth,
  105169. height: blurTextureHeight
  105170. }, this._scene, false, true, textureType);
  105171. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  105172. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  105173. this._blurTexture.anisotropicFilteringLevel = 16;
  105174. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  105175. this._blurTexture.renderParticles = false;
  105176. this._blurTexture.ignoreCameraViewport = true;
  105177. this._textures = [this._blurTexture];
  105178. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  105179. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  105180. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  105181. effect.setTexture("textureSampler", _this._mainTexture);
  105182. });
  105183. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  105184. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  105185. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  105186. });
  105187. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  105188. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  105189. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  105190. });
  105191. this._postProcesses = [this._downSamplePostprocess, this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  105192. }
  105193. else {
  105194. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize / 2, {
  105195. width: blurTextureWidth,
  105196. height: blurTextureHeight
  105197. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  105198. this._horizontalBlurPostprocess.width = blurTextureWidth;
  105199. this._horizontalBlurPostprocess.height = blurTextureHeight;
  105200. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  105201. effect.setTexture("textureSampler", _this._mainTexture);
  105202. });
  105203. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize / 2, {
  105204. width: blurTextureWidth,
  105205. height: blurTextureHeight
  105206. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  105207. this._postProcesses = [this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  105208. }
  105209. this._mainTexture.onAfterUnbindObservable.add(function () {
  105210. _this.onBeforeBlurObservable.notifyObservers(_this);
  105211. var internalTexture = _this._blurTexture.getInternalTexture();
  105212. if (internalTexture) {
  105213. _this._scene.postProcessManager.directRender(_this._postProcesses, internalTexture, true);
  105214. }
  105215. _this.onAfterBlurObservable.notifyObservers(_this);
  105216. });
  105217. // Prevent autoClear.
  105218. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  105219. };
  105220. /**
  105221. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  105222. */
  105223. HighlightLayer.prototype.needStencil = function () {
  105224. return true;
  105225. };
  105226. /**
  105227. * Checks for the readiness of the element composing the layer.
  105228. * @param subMesh the mesh to check for
  105229. * @param useInstances specify wether or not to use instances to render the mesh
  105230. * @param emissiveTexture the associated emissive texture used to generate the glow
  105231. * @return true if ready otherwise, false
  105232. */
  105233. HighlightLayer.prototype.isReady = function (subMesh, useInstances) {
  105234. var material = subMesh.getMaterial();
  105235. var mesh = subMesh.getRenderingMesh();
  105236. if (!material || !mesh || !this._meshes) {
  105237. return false;
  105238. }
  105239. var emissiveTexture = null;
  105240. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  105241. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  105242. emissiveTexture = material.emissiveTexture;
  105243. }
  105244. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  105245. };
  105246. /**
  105247. * Implementation specific of rendering the generating effect on the main canvas.
  105248. * @param effect The effect used to render through
  105249. */
  105250. HighlightLayer.prototype._internalRender = function (effect) {
  105251. // Texture
  105252. effect.setTexture("textureSampler", this._blurTexture);
  105253. // Cache
  105254. var engine = this._engine;
  105255. var previousStencilBuffer = engine.getStencilBuffer();
  105256. var previousStencilFunction = engine.getStencilFunction();
  105257. var previousStencilMask = engine.getStencilMask();
  105258. var previousStencilOperationPass = engine.getStencilOperationPass();
  105259. var previousStencilOperationFail = engine.getStencilOperationFail();
  105260. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  105261. var previousStencilReference = engine.getStencilFunctionReference();
  105262. // Stencil operations
  105263. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  105264. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  105265. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  105266. // Draw order
  105267. engine.setStencilMask(0x00);
  105268. engine.setStencilBuffer(true);
  105269. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  105270. // 2 passes inner outer
  105271. if (this.outerGlow) {
  105272. effect.setFloat("offset", 0);
  105273. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  105274. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  105275. }
  105276. if (this.innerGlow) {
  105277. effect.setFloat("offset", 1);
  105278. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  105279. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  105280. }
  105281. // Restore Cache
  105282. engine.setStencilFunction(previousStencilFunction);
  105283. engine.setStencilMask(previousStencilMask);
  105284. engine.setStencilBuffer(previousStencilBuffer);
  105285. engine.setStencilOperationPass(previousStencilOperationPass);
  105286. engine.setStencilOperationFail(previousStencilOperationFail);
  105287. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  105288. engine.setStencilFunctionReference(previousStencilReference);
  105289. };
  105290. /**
  105291. * Returns true if the layer contains information to display, otherwise false.
  105292. */
  105293. HighlightLayer.prototype.shouldRender = function () {
  105294. if (_super.prototype.shouldRender.call(this)) {
  105295. return this._meshes ? true : false;
  105296. }
  105297. return false;
  105298. };
  105299. /**
  105300. * Returns true if the mesh should render, otherwise false.
  105301. * @param mesh The mesh to render
  105302. * @returns true if it should render otherwise false
  105303. */
  105304. HighlightLayer.prototype._shouldRenderMesh = function (mesh) {
  105305. // Excluded Mesh
  105306. if (this._excludedMeshes && this._excludedMeshes[mesh.uniqueId]) {
  105307. return false;
  105308. }
  105309. ;
  105310. if (!_super.prototype.hasMesh.call(this, mesh)) {
  105311. return false;
  105312. }
  105313. return true;
  105314. };
  105315. /**
  105316. * Sets the required values for both the emissive texture and and the main color.
  105317. */
  105318. HighlightLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  105319. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  105320. if (highlightLayerMesh) {
  105321. this._emissiveTextureAndColor.color.set(highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  105322. }
  105323. else {
  105324. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  105325. }
  105326. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  105327. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  105328. this._emissiveTextureAndColor.color.set(1.0, 1.0, 1.0, 1.0);
  105329. }
  105330. else {
  105331. this._emissiveTextureAndColor.texture = null;
  105332. }
  105333. };
  105334. /**
  105335. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  105336. * @param mesh The mesh to exclude from the highlight layer
  105337. */
  105338. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  105339. if (!this._excludedMeshes) {
  105340. return;
  105341. }
  105342. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  105343. if (!meshExcluded) {
  105344. this._excludedMeshes[mesh.uniqueId] = {
  105345. mesh: mesh,
  105346. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  105347. mesh.getEngine().setStencilBuffer(false);
  105348. }),
  105349. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  105350. mesh.getEngine().setStencilBuffer(true);
  105351. }),
  105352. };
  105353. }
  105354. };
  105355. /**
  105356. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  105357. * @param mesh The mesh to highlight
  105358. */
  105359. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  105360. if (!this._excludedMeshes) {
  105361. return;
  105362. }
  105363. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  105364. if (meshExcluded) {
  105365. if (meshExcluded.beforeRender) {
  105366. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  105367. }
  105368. if (meshExcluded.afterRender) {
  105369. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  105370. }
  105371. }
  105372. this._excludedMeshes[mesh.uniqueId] = null;
  105373. };
  105374. /**
  105375. * Determine if a given mesh will be highlighted by the current HighlightLayer
  105376. * @param mesh mesh to test
  105377. * @returns true if the mesh will be highlighted by the current HighlightLayer
  105378. */
  105379. HighlightLayer.prototype.hasMesh = function (mesh) {
  105380. if (!this._meshes) {
  105381. return false;
  105382. }
  105383. if (!_super.prototype.hasMesh.call(this, mesh)) {
  105384. return false;
  105385. }
  105386. return this._meshes[mesh.uniqueId] !== undefined && this._meshes[mesh.uniqueId] !== null;
  105387. };
  105388. /**
  105389. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  105390. * @param mesh The mesh to highlight
  105391. * @param color The color of the highlight
  105392. * @param glowEmissiveOnly Extract the glow from the emissive texture
  105393. */
  105394. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  105395. var _this = this;
  105396. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  105397. if (!this._meshes) {
  105398. return;
  105399. }
  105400. var meshHighlight = this._meshes[mesh.uniqueId];
  105401. if (meshHighlight) {
  105402. meshHighlight.color = color;
  105403. }
  105404. else {
  105405. this._meshes[mesh.uniqueId] = {
  105406. mesh: mesh,
  105407. color: color,
  105408. // Lambda required for capture due to Observable this context
  105409. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  105410. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  105411. _this._defaultStencilReference(mesh);
  105412. }
  105413. else {
  105414. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  105415. }
  105416. }),
  105417. observerDefault: mesh.onAfterRenderObservable.add(this._defaultStencilReference),
  105418. glowEmissiveOnly: glowEmissiveOnly
  105419. };
  105420. mesh.onDisposeObservable.add(function () {
  105421. _this._disposeMesh(mesh);
  105422. });
  105423. }
  105424. this._shouldRender = true;
  105425. };
  105426. /**
  105427. * Remove a mesh from the highlight layer in order to make it stop glowing.
  105428. * @param mesh The mesh to highlight
  105429. */
  105430. HighlightLayer.prototype.removeMesh = function (mesh) {
  105431. if (!this._meshes) {
  105432. return;
  105433. }
  105434. var meshHighlight = this._meshes[mesh.uniqueId];
  105435. if (meshHighlight) {
  105436. if (meshHighlight.observerHighlight) {
  105437. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  105438. }
  105439. if (meshHighlight.observerDefault) {
  105440. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  105441. }
  105442. delete this._meshes[mesh.uniqueId];
  105443. }
  105444. this._shouldRender = false;
  105445. for (var meshHighlightToCheck in this._meshes) {
  105446. if (this._meshes[meshHighlightToCheck]) {
  105447. this._shouldRender = true;
  105448. break;
  105449. }
  105450. }
  105451. };
  105452. /**
  105453. * Force the stencil to the normal expected value for none glowing parts
  105454. */
  105455. HighlightLayer.prototype._defaultStencilReference = function (mesh) {
  105456. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.NormalMeshStencilReference);
  105457. };
  105458. /**
  105459. * Free any resources and references associated to a mesh.
  105460. * Internal use
  105461. * @param mesh The mesh to free.
  105462. * @hidden
  105463. */
  105464. HighlightLayer.prototype._disposeMesh = function (mesh) {
  105465. this.removeMesh(mesh);
  105466. this.removeExcludedMesh(mesh);
  105467. };
  105468. /**
  105469. * Dispose the highlight layer and free resources.
  105470. */
  105471. HighlightLayer.prototype.dispose = function () {
  105472. if (this._meshes) {
  105473. // Clean mesh references
  105474. for (var id in this._meshes) {
  105475. var meshHighlight = this._meshes[id];
  105476. if (meshHighlight && meshHighlight.mesh) {
  105477. if (meshHighlight.observerHighlight) {
  105478. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  105479. }
  105480. if (meshHighlight.observerDefault) {
  105481. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  105482. }
  105483. }
  105484. }
  105485. this._meshes = null;
  105486. }
  105487. if (this._excludedMeshes) {
  105488. for (var id in this._excludedMeshes) {
  105489. var meshHighlight = this._excludedMeshes[id];
  105490. if (meshHighlight) {
  105491. if (meshHighlight.beforeRender) {
  105492. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  105493. }
  105494. if (meshHighlight.afterRender) {
  105495. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  105496. }
  105497. }
  105498. }
  105499. this._excludedMeshes = null;
  105500. }
  105501. _super.prototype.dispose.call(this);
  105502. };
  105503. /**
  105504. * Gets the class name of the effect layer
  105505. * @returns the string with the class name of the effect layer
  105506. */
  105507. HighlightLayer.prototype.getClassName = function () {
  105508. return "HighlightLayer";
  105509. };
  105510. /**
  105511. * Serializes this Highlight layer
  105512. * @returns a serialized Highlight layer object
  105513. */
  105514. HighlightLayer.prototype.serialize = function () {
  105515. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  105516. serializationObject.customType = "BABYLON.HighlightLayer";
  105517. // Highlighted meshes
  105518. serializationObject.meshes = [];
  105519. if (this._meshes) {
  105520. for (var m in this._meshes) {
  105521. var mesh = this._meshes[m];
  105522. if (mesh) {
  105523. serializationObject.meshes.push({
  105524. glowEmissiveOnly: mesh.glowEmissiveOnly,
  105525. color: mesh.color.asArray(),
  105526. meshId: mesh.mesh.id
  105527. });
  105528. }
  105529. }
  105530. }
  105531. // Excluded meshes
  105532. serializationObject.excludedMeshes = [];
  105533. if (this._excludedMeshes) {
  105534. for (var e in this._excludedMeshes) {
  105535. var excludedMesh = this._excludedMeshes[e];
  105536. if (excludedMesh) {
  105537. serializationObject.excludedMeshes.push(excludedMesh.mesh.id);
  105538. }
  105539. }
  105540. }
  105541. return serializationObject;
  105542. };
  105543. /**
  105544. * Creates a Highlight layer from parsed Highlight layer data
  105545. * @param parsedHightlightLayer defines the Highlight layer data
  105546. * @param scene defines the current scene
  105547. * @param rootUrl defines the root URL containing the Highlight layer information
  105548. * @returns a parsed Highlight layer
  105549. */
  105550. HighlightLayer.Parse = function (parsedHightlightLayer, scene, rootUrl) {
  105551. var hl = BABYLON.SerializationHelper.Parse(function () { return new HighlightLayer(parsedHightlightLayer.name, scene, parsedHightlightLayer.options); }, parsedHightlightLayer, scene, rootUrl);
  105552. var index;
  105553. // Excluded meshes
  105554. for (index = 0; index < parsedHightlightLayer.excludedMeshes.length; index++) {
  105555. var mesh = scene.getMeshByID(parsedHightlightLayer.excludedMeshes[index]);
  105556. if (mesh) {
  105557. hl.addExcludedMesh(mesh);
  105558. }
  105559. }
  105560. // Included meshes
  105561. for (index = 0; index < parsedHightlightLayer.meshes.length; index++) {
  105562. var highlightedMesh = parsedHightlightLayer.meshes[index];
  105563. var mesh = scene.getMeshByID(highlightedMesh.meshId);
  105564. if (mesh) {
  105565. hl.addMesh(mesh, BABYLON.Color3.FromArray(highlightedMesh.color), highlightedMesh.glowEmissiveOnly);
  105566. }
  105567. }
  105568. return hl;
  105569. };
  105570. /**
  105571. * Effect Name of the highlight layer.
  105572. */
  105573. HighlightLayer.EffectName = "HighlightLayer";
  105574. /**
  105575. * The neutral color used during the preparation of the glow effect.
  105576. * This is black by default as the blend operation is a blend operation.
  105577. */
  105578. HighlightLayer.NeutralColor = new BABYLON.Color4(0, 0, 0, 0);
  105579. /**
  105580. * Stencil value used for glowing meshes.
  105581. */
  105582. HighlightLayer.GlowingMeshStencilReference = 0x02;
  105583. /**
  105584. * Stencil value used for the other meshes in the scene.
  105585. */
  105586. HighlightLayer.NormalMeshStencilReference = 0x01;
  105587. __decorate([
  105588. BABYLON.serialize()
  105589. ], HighlightLayer.prototype, "innerGlow", void 0);
  105590. __decorate([
  105591. BABYLON.serialize()
  105592. ], HighlightLayer.prototype, "outerGlow", void 0);
  105593. __decorate([
  105594. BABYLON.serialize()
  105595. ], HighlightLayer.prototype, "blurHorizontalSize", null);
  105596. __decorate([
  105597. BABYLON.serialize()
  105598. ], HighlightLayer.prototype, "blurVerticalSize", null);
  105599. __decorate([
  105600. BABYLON.serialize("options")
  105601. ], HighlightLayer.prototype, "_options", void 0);
  105602. return HighlightLayer;
  105603. }(BABYLON.EffectLayer));
  105604. BABYLON.HighlightLayer = HighlightLayer;
  105605. })(BABYLON || (BABYLON = {}));
  105606. //# sourceMappingURL=babylon.highlightLayer.js.map
  105607. var BABYLON;
  105608. (function (BABYLON) {
  105609. BABYLON.AbstractScene.prototype.getGlowLayerByName = function (name) {
  105610. for (var index = 0; index < this.effectLayers.length; index++) {
  105611. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === GlowLayer.EffectName) {
  105612. return this.effectLayers[index];
  105613. }
  105614. }
  105615. return null;
  105616. };
  105617. /**
  105618. * The glow layer Helps adding a glow effect around the emissive parts of a mesh.
  105619. *
  105620. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  105621. * glowy meshes to your scene.
  105622. *
  105623. * Documentation: https://doc.babylonjs.com/how_to/glow_layer
  105624. */
  105625. var GlowLayer = /** @class */ (function (_super) {
  105626. __extends(GlowLayer, _super);
  105627. /**
  105628. * Instantiates a new glow Layer and references it to the scene.
  105629. * @param name The name of the layer
  105630. * @param scene The scene to use the layer in
  105631. * @param options Sets of none mandatory options to use with the layer (see IGlowLayerOptions for more information)
  105632. */
  105633. function GlowLayer(name, scene, options) {
  105634. var _this = _super.call(this, name, scene) || this;
  105635. _this._intensity = 1.0;
  105636. _this._includedOnlyMeshes = [];
  105637. _this._excludedMeshes = [];
  105638. _this.neutralColor = new BABYLON.Color4(0, 0, 0, 1);
  105639. // Adapt options
  105640. _this._options = __assign({ mainTextureRatio: GlowLayer.DefaultTextureRatio, blurKernelSize: 32, mainTextureFixedSize: undefined, camera: null, mainTextureSamples: 1, renderingGroupId: -1 }, options);
  105641. // Initialize the layer
  105642. _this._init({
  105643. alphaBlendingMode: BABYLON.Engine.ALPHA_ADD,
  105644. camera: _this._options.camera,
  105645. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  105646. mainTextureRatio: _this._options.mainTextureRatio,
  105647. renderingGroupId: _this._options.renderingGroupId
  105648. });
  105649. return _this;
  105650. }
  105651. Object.defineProperty(GlowLayer.prototype, "blurKernelSize", {
  105652. /**
  105653. * Gets the kernel size of the blur.
  105654. */
  105655. get: function () {
  105656. return this._horizontalBlurPostprocess1.kernel;
  105657. },
  105658. /**
  105659. * Sets the kernel size of the blur.
  105660. */
  105661. set: function (value) {
  105662. this._horizontalBlurPostprocess1.kernel = value;
  105663. this._verticalBlurPostprocess1.kernel = value;
  105664. this._horizontalBlurPostprocess2.kernel = value;
  105665. this._verticalBlurPostprocess2.kernel = value;
  105666. },
  105667. enumerable: true,
  105668. configurable: true
  105669. });
  105670. Object.defineProperty(GlowLayer.prototype, "intensity", {
  105671. /**
  105672. * Gets the glow intensity.
  105673. */
  105674. get: function () {
  105675. return this._intensity;
  105676. },
  105677. /**
  105678. * Sets the glow intensity.
  105679. */
  105680. set: function (value) {
  105681. this._intensity = value;
  105682. },
  105683. enumerable: true,
  105684. configurable: true
  105685. });
  105686. /**
  105687. * Get the effect name of the layer.
  105688. * @return The effect name
  105689. */
  105690. GlowLayer.prototype.getEffectName = function () {
  105691. return GlowLayer.EffectName;
  105692. };
  105693. /**
  105694. * Create the merge effect. This is the shader use to blit the information back
  105695. * to the main canvas at the end of the scene rendering.
  105696. */
  105697. GlowLayer.prototype._createMergeEffect = function () {
  105698. // Effect
  105699. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler", "textureSampler2"], "#define EMISSIVE \n");
  105700. };
  105701. /**
  105702. * Creates the render target textures and post processes used in the glow layer.
  105703. */
  105704. GlowLayer.prototype._createTextureAndPostProcesses = function () {
  105705. var _this = this;
  105706. var blurTextureWidth = this._mainTextureDesiredSize.width;
  105707. var blurTextureHeight = this._mainTextureDesiredSize.height;
  105708. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  105709. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  105710. var textureType = 0;
  105711. if (this._engine.getCaps().textureHalfFloatRender) {
  105712. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  105713. }
  105714. else {
  105715. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  105716. }
  105717. this._blurTexture1 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT", {
  105718. width: blurTextureWidth,
  105719. height: blurTextureHeight
  105720. }, this._scene, false, true, textureType);
  105721. this._blurTexture1.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  105722. this._blurTexture1.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  105723. this._blurTexture1.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  105724. this._blurTexture1.renderParticles = false;
  105725. this._blurTexture1.ignoreCameraViewport = true;
  105726. var blurTextureWidth2 = Math.floor(blurTextureWidth / 2);
  105727. var blurTextureHeight2 = Math.floor(blurTextureHeight / 2);
  105728. this._blurTexture2 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT2", {
  105729. width: blurTextureWidth2,
  105730. height: blurTextureHeight2
  105731. }, this._scene, false, true, textureType);
  105732. this._blurTexture2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  105733. this._blurTexture2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  105734. this._blurTexture2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  105735. this._blurTexture2.renderParticles = false;
  105736. this._blurTexture2.ignoreCameraViewport = true;
  105737. this._textures = [this._blurTexture1, this._blurTexture2];
  105738. this._horizontalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerHBP1", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  105739. width: blurTextureWidth,
  105740. height: blurTextureHeight
  105741. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  105742. this._horizontalBlurPostprocess1.width = blurTextureWidth;
  105743. this._horizontalBlurPostprocess1.height = blurTextureHeight;
  105744. this._horizontalBlurPostprocess1.onApplyObservable.add(function (effect) {
  105745. effect.setTexture("textureSampler", _this._mainTexture);
  105746. });
  105747. this._verticalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerVBP1", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  105748. width: blurTextureWidth,
  105749. height: blurTextureHeight
  105750. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  105751. this._horizontalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerHBP2", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  105752. width: blurTextureWidth2,
  105753. height: blurTextureHeight2
  105754. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  105755. this._horizontalBlurPostprocess2.width = blurTextureWidth2;
  105756. this._horizontalBlurPostprocess2.height = blurTextureHeight2;
  105757. this._horizontalBlurPostprocess2.onApplyObservable.add(function (effect) {
  105758. effect.setTexture("textureSampler", _this._blurTexture1);
  105759. });
  105760. this._verticalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerVBP2", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  105761. width: blurTextureWidth2,
  105762. height: blurTextureHeight2
  105763. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  105764. this._postProcesses = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1, this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  105765. this._postProcesses1 = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1];
  105766. this._postProcesses2 = [this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  105767. this._mainTexture.samples = this._options.mainTextureSamples;
  105768. this._mainTexture.onAfterUnbindObservable.add(function () {
  105769. var internalTexture = _this._blurTexture1.getInternalTexture();
  105770. if (internalTexture) {
  105771. _this._scene.postProcessManager.directRender(_this._postProcesses1, internalTexture, true);
  105772. internalTexture = _this._blurTexture2.getInternalTexture();
  105773. if (internalTexture) {
  105774. _this._scene.postProcessManager.directRender(_this._postProcesses2, internalTexture, true);
  105775. }
  105776. }
  105777. });
  105778. // Prevent autoClear.
  105779. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  105780. };
  105781. /**
  105782. * Checks for the readiness of the element composing the layer.
  105783. * @param subMesh the mesh to check for
  105784. * @param useInstances specify wether or not to use instances to render the mesh
  105785. * @param emissiveTexture the associated emissive texture used to generate the glow
  105786. * @return true if ready otherwise, false
  105787. */
  105788. GlowLayer.prototype.isReady = function (subMesh, useInstances) {
  105789. var material = subMesh.getMaterial();
  105790. var mesh = subMesh.getRenderingMesh();
  105791. if (!material || !mesh) {
  105792. return false;
  105793. }
  105794. var emissiveTexture = material.emissiveTexture;
  105795. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  105796. };
  105797. /**
  105798. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  105799. */
  105800. GlowLayer.prototype.needStencil = function () {
  105801. return false;
  105802. };
  105803. /**
  105804. * Implementation specific of rendering the generating effect on the main canvas.
  105805. * @param effect The effect used to render through
  105806. */
  105807. GlowLayer.prototype._internalRender = function (effect) {
  105808. // Texture
  105809. effect.setTexture("textureSampler", this._blurTexture1);
  105810. effect.setTexture("textureSampler2", this._blurTexture2);
  105811. effect.setFloat("offset", this._intensity);
  105812. // Cache
  105813. var engine = this._engine;
  105814. var previousStencilBuffer = engine.getStencilBuffer();
  105815. // Draw order
  105816. engine.setStencilBuffer(false);
  105817. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  105818. // Draw order
  105819. engine.setStencilBuffer(previousStencilBuffer);
  105820. };
  105821. /**
  105822. * Sets the required values for both the emissive texture and and the main color.
  105823. */
  105824. GlowLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  105825. var textureLevel = 1.0;
  105826. if (this.customEmissiveTextureSelector) {
  105827. this._emissiveTextureAndColor.texture = this.customEmissiveTextureSelector(mesh, subMesh, material);
  105828. }
  105829. else {
  105830. if (material) {
  105831. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  105832. if (this._emissiveTextureAndColor.texture) {
  105833. textureLevel = this._emissiveTextureAndColor.texture.level;
  105834. }
  105835. }
  105836. else {
  105837. this._emissiveTextureAndColor.texture = null;
  105838. }
  105839. }
  105840. if (this.customEmissiveColorSelector) {
  105841. this.customEmissiveColorSelector(mesh, subMesh, material, this._emissiveTextureAndColor.color);
  105842. }
  105843. else {
  105844. if (material.emissiveColor) {
  105845. this._emissiveTextureAndColor.color.set(material.emissiveColor.r * textureLevel, material.emissiveColor.g * textureLevel, material.emissiveColor.b * textureLevel, 1.0);
  105846. }
  105847. else {
  105848. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  105849. }
  105850. }
  105851. };
  105852. /**
  105853. * Returns true if the mesh should render, otherwise false.
  105854. * @param mesh The mesh to render
  105855. * @returns true if it should render otherwise false
  105856. */
  105857. GlowLayer.prototype._shouldRenderMesh = function (mesh) {
  105858. return this.hasMesh(mesh);
  105859. };
  105860. /**
  105861. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the glow layer.
  105862. * @param mesh The mesh to exclude from the glow layer
  105863. */
  105864. GlowLayer.prototype.addExcludedMesh = function (mesh) {
  105865. if (this._excludedMeshes.indexOf(mesh.uniqueId) === -1) {
  105866. this._excludedMeshes.push(mesh.uniqueId);
  105867. }
  105868. };
  105869. /**
  105870. * Remove a mesh from the exclusion list to let it impact or being impacted by the glow layer.
  105871. * @param mesh The mesh to remove
  105872. */
  105873. GlowLayer.prototype.removeExcludedMesh = function (mesh) {
  105874. var index = this._excludedMeshes.indexOf(mesh.uniqueId);
  105875. if (index !== -1) {
  105876. this._excludedMeshes.splice(index, 1);
  105877. }
  105878. };
  105879. /**
  105880. * Add a mesh in the inclusion list to impact or being impacted by the glow layer.
  105881. * @param mesh The mesh to include in the glow layer
  105882. */
  105883. GlowLayer.prototype.addIncludedOnlyMesh = function (mesh) {
  105884. if (this._includedOnlyMeshes.indexOf(mesh.uniqueId) === -1) {
  105885. this._includedOnlyMeshes.push(mesh.uniqueId);
  105886. }
  105887. };
  105888. /**
  105889. * Remove a mesh from the Inclusion list to prevent it to impact or being impacted by the glow layer.
  105890. * @param mesh The mesh to remove
  105891. */
  105892. GlowLayer.prototype.removeIncludedOnlyMesh = function (mesh) {
  105893. var index = this._includedOnlyMeshes.indexOf(mesh.uniqueId);
  105894. if (index !== -1) {
  105895. this._includedOnlyMeshes.splice(index, 1);
  105896. }
  105897. };
  105898. /**
  105899. * Determine if a given mesh will be used in the glow layer
  105900. * @param mesh The mesh to test
  105901. * @returns true if the mesh will be highlighted by the current glow layer
  105902. */
  105903. GlowLayer.prototype.hasMesh = function (mesh) {
  105904. if (!_super.prototype.hasMesh.call(this, mesh)) {
  105905. return false;
  105906. }
  105907. // Included Mesh
  105908. if (this._includedOnlyMeshes.length) {
  105909. return this._includedOnlyMeshes.indexOf(mesh.uniqueId) !== -1;
  105910. }
  105911. ;
  105912. // Excluded Mesh
  105913. if (this._excludedMeshes.length) {
  105914. return this._excludedMeshes.indexOf(mesh.uniqueId) === -1;
  105915. }
  105916. ;
  105917. return true;
  105918. };
  105919. /**
  105920. * Free any resources and references associated to a mesh.
  105921. * Internal use
  105922. * @param mesh The mesh to free.
  105923. * @hidden
  105924. */
  105925. GlowLayer.prototype._disposeMesh = function (mesh) {
  105926. this.removeIncludedOnlyMesh(mesh);
  105927. this.removeExcludedMesh(mesh);
  105928. };
  105929. /**
  105930. * Gets the class name of the effect layer
  105931. * @returns the string with the class name of the effect layer
  105932. */
  105933. GlowLayer.prototype.getClassName = function () {
  105934. return "GlowLayer";
  105935. };
  105936. /**
  105937. * Serializes this glow layer
  105938. * @returns a serialized glow layer object
  105939. */
  105940. GlowLayer.prototype.serialize = function () {
  105941. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  105942. serializationObject.customType = "BABYLON.GlowLayer";
  105943. var index;
  105944. // Included meshes
  105945. serializationObject.includedMeshes = [];
  105946. if (this._includedOnlyMeshes.length) {
  105947. for (index = 0; index < this._includedOnlyMeshes.length; index++) {
  105948. var mesh = this._scene.getMeshByUniqueID(this._includedOnlyMeshes[index]);
  105949. if (mesh) {
  105950. serializationObject.includedMeshes.push(mesh.id);
  105951. }
  105952. }
  105953. }
  105954. // Excluded meshes
  105955. serializationObject.excludedMeshes = [];
  105956. if (this._excludedMeshes.length) {
  105957. for (index = 0; index < this._excludedMeshes.length; index++) {
  105958. var mesh = this._scene.getMeshByUniqueID(this._excludedMeshes[index]);
  105959. if (mesh) {
  105960. serializationObject.excludedMeshes.push(mesh.id);
  105961. }
  105962. }
  105963. }
  105964. return serializationObject;
  105965. };
  105966. /**
  105967. * Creates a Glow Layer from parsed glow layer data
  105968. * @param parsedGlowLayer defines glow layer data
  105969. * @param scene defines the current scene
  105970. * @param rootUrl defines the root URL containing the glow layer information
  105971. * @returns a parsed Glow Layer
  105972. */
  105973. GlowLayer.Parse = function (parsedGlowLayer, scene, rootUrl) {
  105974. var gl = BABYLON.SerializationHelper.Parse(function () { return new GlowLayer(parsedGlowLayer.name, scene, parsedGlowLayer.options); }, parsedGlowLayer, scene, rootUrl);
  105975. var index;
  105976. // Excluded meshes
  105977. for (index = 0; index < parsedGlowLayer.excludedMeshes.length; index++) {
  105978. var mesh = scene.getMeshByID(parsedGlowLayer.excludedMeshes[index]);
  105979. if (mesh) {
  105980. gl.addExcludedMesh(mesh);
  105981. }
  105982. }
  105983. // Included meshes
  105984. for (index = 0; index < parsedGlowLayer.includedMeshes.length; index++) {
  105985. var mesh = scene.getMeshByID(parsedGlowLayer.includedMeshes[index]);
  105986. if (mesh) {
  105987. gl.addIncludedOnlyMesh(mesh);
  105988. }
  105989. }
  105990. return gl;
  105991. };
  105992. /**
  105993. * Effect Name of the layer.
  105994. */
  105995. GlowLayer.EffectName = "GlowLayer";
  105996. /**
  105997. * The default blur kernel size used for the glow.
  105998. */
  105999. GlowLayer.DefaultBlurKernelSize = 32;
  106000. /**
  106001. * The default texture size ratio used for the glow.
  106002. */
  106003. GlowLayer.DefaultTextureRatio = 0.5;
  106004. __decorate([
  106005. BABYLON.serialize()
  106006. ], GlowLayer.prototype, "blurKernelSize", null);
  106007. __decorate([
  106008. BABYLON.serialize()
  106009. ], GlowLayer.prototype, "intensity", null);
  106010. __decorate([
  106011. BABYLON.serialize("options")
  106012. ], GlowLayer.prototype, "_options", void 0);
  106013. return GlowLayer;
  106014. }(BABYLON.EffectLayer));
  106015. BABYLON.GlowLayer = GlowLayer;
  106016. })(BABYLON || (BABYLON = {}));
  106017. //# sourceMappingURL=babylon.glowLayer.js.map
  106018. var BABYLON;
  106019. (function (BABYLON) {
  106020. /**
  106021. * Defines the list of states available for a task inside a {BABYLON.AssetsManager}
  106022. */
  106023. var AssetTaskState;
  106024. (function (AssetTaskState) {
  106025. /**
  106026. * Initialization
  106027. */
  106028. AssetTaskState[AssetTaskState["INIT"] = 0] = "INIT";
  106029. /**
  106030. * Running
  106031. */
  106032. AssetTaskState[AssetTaskState["RUNNING"] = 1] = "RUNNING";
  106033. /**
  106034. * Done
  106035. */
  106036. AssetTaskState[AssetTaskState["DONE"] = 2] = "DONE";
  106037. /**
  106038. * Error
  106039. */
  106040. AssetTaskState[AssetTaskState["ERROR"] = 3] = "ERROR";
  106041. })(AssetTaskState = BABYLON.AssetTaskState || (BABYLON.AssetTaskState = {}));
  106042. /**
  106043. * Define an abstract asset task used with a {BABYLON.AssetsManager} class to load assets into a scene
  106044. */
  106045. var AbstractAssetTask = /** @class */ (function () {
  106046. /**
  106047. * Creates a new {BABYLON.AssetsManager}
  106048. * @param name defines the name of the task
  106049. */
  106050. function AbstractAssetTask(
  106051. /**
  106052. * Task name
  106053. */ name) {
  106054. this.name = name;
  106055. this._isCompleted = false;
  106056. this._taskState = AssetTaskState.INIT;
  106057. }
  106058. Object.defineProperty(AbstractAssetTask.prototype, "isCompleted", {
  106059. /**
  106060. * Get if the task is completed
  106061. */
  106062. get: function () {
  106063. return this._isCompleted;
  106064. },
  106065. enumerable: true,
  106066. configurable: true
  106067. });
  106068. Object.defineProperty(AbstractAssetTask.prototype, "taskState", {
  106069. /**
  106070. * Gets the current state of the task
  106071. */
  106072. get: function () {
  106073. return this._taskState;
  106074. },
  106075. enumerable: true,
  106076. configurable: true
  106077. });
  106078. Object.defineProperty(AbstractAssetTask.prototype, "errorObject", {
  106079. /**
  106080. * Gets the current error object (if task is in error)
  106081. */
  106082. get: function () {
  106083. return this._errorObject;
  106084. },
  106085. enumerable: true,
  106086. configurable: true
  106087. });
  106088. /**
  106089. * Internal only
  106090. * @hidden
  106091. */
  106092. AbstractAssetTask.prototype._setErrorObject = function (message, exception) {
  106093. if (this._errorObject) {
  106094. return;
  106095. }
  106096. this._errorObject = {
  106097. message: message,
  106098. exception: exception
  106099. };
  106100. };
  106101. /**
  106102. * Execute the current task
  106103. * @param scene defines the scene where you want your assets to be loaded
  106104. * @param onSuccess is a callback called when the task is successfully executed
  106105. * @param onError is a callback called if an error occurs
  106106. */
  106107. AbstractAssetTask.prototype.run = function (scene, onSuccess, onError) {
  106108. var _this = this;
  106109. this._taskState = AssetTaskState.RUNNING;
  106110. this.runTask(scene, function () {
  106111. _this.onDoneCallback(onSuccess, onError);
  106112. }, function (msg, exception) {
  106113. _this.onErrorCallback(onError, msg, exception);
  106114. });
  106115. };
  106116. /**
  106117. * Execute the current task
  106118. * @param scene defines the scene where you want your assets to be loaded
  106119. * @param onSuccess is a callback called when the task is successfully executed
  106120. * @param onError is a callback called if an error occurs
  106121. */
  106122. AbstractAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  106123. throw new Error("runTask is not implemented");
  106124. };
  106125. /**
  106126. * Reset will set the task state back to INIT, so the next load call of the assets manager will execute this task again.
  106127. * This can be used with failed tasks that have the reason for failure fixed.
  106128. */
  106129. AbstractAssetTask.prototype.reset = function () {
  106130. this._taskState = AssetTaskState.INIT;
  106131. };
  106132. AbstractAssetTask.prototype.onErrorCallback = function (onError, message, exception) {
  106133. this._taskState = AssetTaskState.ERROR;
  106134. this._errorObject = {
  106135. message: message,
  106136. exception: exception
  106137. };
  106138. if (this.onError) {
  106139. this.onError(this, message, exception);
  106140. }
  106141. onError();
  106142. };
  106143. AbstractAssetTask.prototype.onDoneCallback = function (onSuccess, onError) {
  106144. try {
  106145. this._taskState = AssetTaskState.DONE;
  106146. this._isCompleted = true;
  106147. if (this.onSuccess) {
  106148. this.onSuccess(this);
  106149. }
  106150. onSuccess();
  106151. }
  106152. catch (e) {
  106153. this.onErrorCallback(onError, "Task is done, error executing success callback(s)", e);
  106154. }
  106155. };
  106156. return AbstractAssetTask;
  106157. }());
  106158. BABYLON.AbstractAssetTask = AbstractAssetTask;
  106159. /**
  106160. * Class used to share progress information about assets loading
  106161. */
  106162. var AssetsProgressEvent = /** @class */ (function () {
  106163. /**
  106164. * Creates a {BABYLON.AssetsProgressEvent}
  106165. * @param remainingCount defines the number of remaining tasks to process
  106166. * @param totalCount defines the total number of tasks
  106167. * @param task defines the task that was just processed
  106168. */
  106169. function AssetsProgressEvent(remainingCount, totalCount, task) {
  106170. this.remainingCount = remainingCount;
  106171. this.totalCount = totalCount;
  106172. this.task = task;
  106173. }
  106174. return AssetsProgressEvent;
  106175. }());
  106176. BABYLON.AssetsProgressEvent = AssetsProgressEvent;
  106177. /**
  106178. * Define a task used by {BABYLON.AssetsManager} to load meshes
  106179. */
  106180. var MeshAssetTask = /** @class */ (function (_super) {
  106181. __extends(MeshAssetTask, _super);
  106182. /**
  106183. * Creates a new {BABYLON.MeshAssetTask}
  106184. * @param name defines the name of the task
  106185. * @param meshesNames defines the list of mesh's names you want to load
  106186. * @param rootUrl defines the root url to use as a base to load your meshes and associated resources
  106187. * @param sceneFilename defines the filename of the scene to load from
  106188. */
  106189. function MeshAssetTask(
  106190. /**
  106191. * Defines the name of the task
  106192. */
  106193. name,
  106194. /**
  106195. * Defines the list of mesh's names you want to load
  106196. */
  106197. meshesNames,
  106198. /**
  106199. * Defines the root url to use as a base to load your meshes and associated resources
  106200. */
  106201. rootUrl,
  106202. /**
  106203. * Defines the filename of the scene to load from
  106204. */
  106205. sceneFilename) {
  106206. var _this = _super.call(this, name) || this;
  106207. _this.name = name;
  106208. _this.meshesNames = meshesNames;
  106209. _this.rootUrl = rootUrl;
  106210. _this.sceneFilename = sceneFilename;
  106211. return _this;
  106212. }
  106213. /**
  106214. * Execute the current task
  106215. * @param scene defines the scene where you want your assets to be loaded
  106216. * @param onSuccess is a callback called when the task is successfully executed
  106217. * @param onError is a callback called if an error occurs
  106218. */
  106219. MeshAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  106220. var _this = this;
  106221. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  106222. _this.loadedMeshes = meshes;
  106223. _this.loadedParticleSystems = particleSystems;
  106224. _this.loadedSkeletons = skeletons;
  106225. onSuccess();
  106226. }, null, function (scene, message, exception) {
  106227. onError(message, exception);
  106228. });
  106229. };
  106230. return MeshAssetTask;
  106231. }(AbstractAssetTask));
  106232. BABYLON.MeshAssetTask = MeshAssetTask;
  106233. /**
  106234. * Define a task used by {BABYLON.AssetsManager} to load text content
  106235. */
  106236. var TextFileAssetTask = /** @class */ (function (_super) {
  106237. __extends(TextFileAssetTask, _super);
  106238. /**
  106239. * Creates a new TextFileAssetTask object
  106240. * @param name defines the name of the task
  106241. * @param url defines the location of the file to load
  106242. */
  106243. function TextFileAssetTask(
  106244. /**
  106245. * Defines the name of the task
  106246. */
  106247. name,
  106248. /**
  106249. * Defines the location of the file to load
  106250. */
  106251. url) {
  106252. var _this = _super.call(this, name) || this;
  106253. _this.name = name;
  106254. _this.url = url;
  106255. return _this;
  106256. }
  106257. /**
  106258. * Execute the current task
  106259. * @param scene defines the scene where you want your assets to be loaded
  106260. * @param onSuccess is a callback called when the task is successfully executed
  106261. * @param onError is a callback called if an error occurs
  106262. */
  106263. TextFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  106264. var _this = this;
  106265. scene._loadFile(this.url, function (data) {
  106266. _this.text = data;
  106267. onSuccess();
  106268. }, undefined, false, false, function (request, exception) {
  106269. if (request) {
  106270. onError(request.status + " " + request.statusText, exception);
  106271. }
  106272. });
  106273. };
  106274. return TextFileAssetTask;
  106275. }(AbstractAssetTask));
  106276. BABYLON.TextFileAssetTask = TextFileAssetTask;
  106277. /**
  106278. * Define a task used by {BABYLON.AssetsManager} to load binary data
  106279. */
  106280. var BinaryFileAssetTask = /** @class */ (function (_super) {
  106281. __extends(BinaryFileAssetTask, _super);
  106282. /**
  106283. * Creates a new BinaryFileAssetTask object
  106284. * @param name defines the name of the new task
  106285. * @param url defines the location of the file to load
  106286. */
  106287. function BinaryFileAssetTask(
  106288. /**
  106289. * Defines the name of the task
  106290. */
  106291. name,
  106292. /**
  106293. * Defines the location of the file to load
  106294. */
  106295. url) {
  106296. var _this = _super.call(this, name) || this;
  106297. _this.name = name;
  106298. _this.url = url;
  106299. return _this;
  106300. }
  106301. /**
  106302. * Execute the current task
  106303. * @param scene defines the scene where you want your assets to be loaded
  106304. * @param onSuccess is a callback called when the task is successfully executed
  106305. * @param onError is a callback called if an error occurs
  106306. */
  106307. BinaryFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  106308. var _this = this;
  106309. scene._loadFile(this.url, function (data) {
  106310. _this.data = data;
  106311. onSuccess();
  106312. }, undefined, true, true, function (request, exception) {
  106313. if (request) {
  106314. onError(request.status + " " + request.statusText, exception);
  106315. }
  106316. });
  106317. };
  106318. return BinaryFileAssetTask;
  106319. }(AbstractAssetTask));
  106320. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  106321. /**
  106322. * Define a task used by {BABYLON.AssetsManager} to load images
  106323. */
  106324. var ImageAssetTask = /** @class */ (function (_super) {
  106325. __extends(ImageAssetTask, _super);
  106326. /**
  106327. * Creates a new ImageAssetTask
  106328. * @param name defines the name of the task
  106329. * @param url defines the location of the image to load
  106330. */
  106331. function ImageAssetTask(
  106332. /**
  106333. * Defines the name of the task
  106334. */
  106335. name,
  106336. /**
  106337. * Defines the location of the image to load
  106338. */
  106339. url) {
  106340. var _this = _super.call(this, name) || this;
  106341. _this.name = name;
  106342. _this.url = url;
  106343. return _this;
  106344. }
  106345. /**
  106346. * Execute the current task
  106347. * @param scene defines the scene where you want your assets to be loaded
  106348. * @param onSuccess is a callback called when the task is successfully executed
  106349. * @param onError is a callback called if an error occurs
  106350. */
  106351. ImageAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  106352. var _this = this;
  106353. var img = new Image();
  106354. BABYLON.Tools.SetCorsBehavior(this.url, img);
  106355. img.onload = function () {
  106356. _this.image = img;
  106357. onSuccess();
  106358. };
  106359. img.onerror = function (err) {
  106360. onError("Error loading image", err);
  106361. };
  106362. img.src = this.url;
  106363. };
  106364. return ImageAssetTask;
  106365. }(AbstractAssetTask));
  106366. BABYLON.ImageAssetTask = ImageAssetTask;
  106367. /**
  106368. * Define a task used by {BABYLON.AssetsManager} to load 2D textures
  106369. */
  106370. var TextureAssetTask = /** @class */ (function (_super) {
  106371. __extends(TextureAssetTask, _super);
  106372. /**
  106373. * Creates a new TextureAssetTask object
  106374. * @param name defines the name of the task
  106375. * @param url defines the location of the file to load
  106376. * @param noMipmap defines if mipmap should not be generated (default is false)
  106377. * @param invertY defines if texture must be inverted on Y axis (default is false)
  106378. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  106379. */
  106380. function TextureAssetTask(
  106381. /**
  106382. * Defines the name of the task
  106383. */
  106384. name,
  106385. /**
  106386. * Defines the location of the file to load
  106387. */
  106388. url,
  106389. /**
  106390. * Defines if mipmap should not be generated (default is false)
  106391. */
  106392. noMipmap,
  106393. /**
  106394. * Defines if texture must be inverted on Y axis (default is false)
  106395. */
  106396. invertY,
  106397. /**
  106398. * Defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  106399. */
  106400. samplingMode) {
  106401. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  106402. var _this = _super.call(this, name) || this;
  106403. _this.name = name;
  106404. _this.url = url;
  106405. _this.noMipmap = noMipmap;
  106406. _this.invertY = invertY;
  106407. _this.samplingMode = samplingMode;
  106408. return _this;
  106409. }
  106410. /**
  106411. * Execute the current task
  106412. * @param scene defines the scene where you want your assets to be loaded
  106413. * @param onSuccess is a callback called when the task is successfully executed
  106414. * @param onError is a callback called if an error occurs
  106415. */
  106416. TextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  106417. var onload = function () {
  106418. onSuccess();
  106419. };
  106420. var onerror = function (message, exception) {
  106421. onError(message, exception);
  106422. };
  106423. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  106424. };
  106425. return TextureAssetTask;
  106426. }(AbstractAssetTask));
  106427. BABYLON.TextureAssetTask = TextureAssetTask;
  106428. /**
  106429. * Define a task used by {BABYLON.AssetsManager} to load cube textures
  106430. */
  106431. var CubeTextureAssetTask = /** @class */ (function (_super) {
  106432. __extends(CubeTextureAssetTask, _super);
  106433. /**
  106434. * Creates a new CubeTextureAssetTask
  106435. * @param name defines the name of the task
  106436. * @param url defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  106437. * @param extensions defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  106438. * @param noMipmap defines if mipmaps should not be generated (default is false)
  106439. * @param files defines the explicit list of files (undefined by default)
  106440. */
  106441. function CubeTextureAssetTask(
  106442. /**
  106443. * Defines the name of the task
  106444. */
  106445. name,
  106446. /**
  106447. * Defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  106448. */
  106449. url,
  106450. /**
  106451. * Defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  106452. */
  106453. extensions,
  106454. /**
  106455. * Defines if mipmaps should not be generated (default is false)
  106456. */
  106457. noMipmap,
  106458. /**
  106459. * Defines the explicit list of files (undefined by default)
  106460. */
  106461. files) {
  106462. var _this = _super.call(this, name) || this;
  106463. _this.name = name;
  106464. _this.url = url;
  106465. _this.extensions = extensions;
  106466. _this.noMipmap = noMipmap;
  106467. _this.files = files;
  106468. return _this;
  106469. }
  106470. /**
  106471. * Execute the current task
  106472. * @param scene defines the scene where you want your assets to be loaded
  106473. * @param onSuccess is a callback called when the task is successfully executed
  106474. * @param onError is a callback called if an error occurs
  106475. */
  106476. CubeTextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  106477. var onload = function () {
  106478. onSuccess();
  106479. };
  106480. var onerror = function (message, exception) {
  106481. onError(message, exception);
  106482. };
  106483. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  106484. };
  106485. return CubeTextureAssetTask;
  106486. }(AbstractAssetTask));
  106487. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  106488. /**
  106489. * Define a task used by {BABYLON.AssetsManager} to load HDR cube textures
  106490. */
  106491. var HDRCubeTextureAssetTask = /** @class */ (function (_super) {
  106492. __extends(HDRCubeTextureAssetTask, _super);
  106493. /**
  106494. * Creates a new HDRCubeTextureAssetTask object
  106495. * @param name defines the name of the task
  106496. * @param url defines the location of the file to load
  106497. * @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.
  106498. * @param noMipmap defines if mipmaps should not be generated (default is false)
  106499. * @param generateHarmonics specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  106500. * @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)
  106501. * @param reserved Internal use only
  106502. */
  106503. function HDRCubeTextureAssetTask(
  106504. /**
  106505. * Defines the name of the task
  106506. */
  106507. name,
  106508. /**
  106509. * Defines the location of the file to load
  106510. */
  106511. url,
  106512. /**
  106513. * Defines the desired size (the more it increases the longer the generation will be)
  106514. */
  106515. size,
  106516. /**
  106517. * Defines if mipmaps should not be generated (default is false)
  106518. */
  106519. noMipmap,
  106520. /**
  106521. * Specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  106522. */
  106523. generateHarmonics,
  106524. /**
  106525. * 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)
  106526. */
  106527. gammaSpace,
  106528. /**
  106529. * Internal Use Only
  106530. */
  106531. reserved) {
  106532. if (noMipmap === void 0) { noMipmap = false; }
  106533. if (generateHarmonics === void 0) { generateHarmonics = true; }
  106534. if (gammaSpace === void 0) { gammaSpace = false; }
  106535. if (reserved === void 0) { reserved = false; }
  106536. var _this = _super.call(this, name) || this;
  106537. _this.name = name;
  106538. _this.url = url;
  106539. _this.size = size;
  106540. _this.noMipmap = noMipmap;
  106541. _this.generateHarmonics = generateHarmonics;
  106542. _this.gammaSpace = gammaSpace;
  106543. _this.reserved = reserved;
  106544. return _this;
  106545. }
  106546. /**
  106547. * Execute the current task
  106548. * @param scene defines the scene where you want your assets to be loaded
  106549. * @param onSuccess is a callback called when the task is successfully executed
  106550. * @param onError is a callback called if an error occurs
  106551. */
  106552. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  106553. var onload = function () {
  106554. onSuccess();
  106555. };
  106556. var onerror = function (message, exception) {
  106557. onError(message, exception);
  106558. };
  106559. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.gammaSpace, this.reserved, onload, onerror);
  106560. };
  106561. return HDRCubeTextureAssetTask;
  106562. }(AbstractAssetTask));
  106563. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  106564. /**
  106565. * This class can be used to easily import assets into a scene
  106566. * @see http://doc.babylonjs.com/how_to/how_to_use_assetsmanager
  106567. */
  106568. var AssetsManager = /** @class */ (function () {
  106569. /**
  106570. * Creates a new AssetsManager
  106571. * @param scene defines the scene to work on
  106572. */
  106573. function AssetsManager(scene) {
  106574. this._isLoading = false;
  106575. this._tasks = new Array();
  106576. this._waitingTasksCount = 0;
  106577. this._totalTasksCount = 0;
  106578. /**
  106579. * Observable called when all tasks are processed
  106580. */
  106581. this.onTaskSuccessObservable = new BABYLON.Observable();
  106582. /**
  106583. * Observable called when a task had an error
  106584. */
  106585. this.onTaskErrorObservable = new BABYLON.Observable();
  106586. /**
  106587. * Observable called when a task is successful
  106588. */
  106589. this.onTasksDoneObservable = new BABYLON.Observable();
  106590. /**
  106591. * Observable called when a task is done (whatever the result is)
  106592. */
  106593. this.onProgressObservable = new BABYLON.Observable();
  106594. /**
  106595. * Gets or sets a boolean defining if the {BABYLON.AssetsManager} should use the default loading screen
  106596. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  106597. */
  106598. this.useDefaultLoadingScreen = true;
  106599. this._scene = scene;
  106600. }
  106601. /**
  106602. * Add a {BABYLON.MeshAssetTask} to the list of active tasks
  106603. * @param taskName defines the name of the new task
  106604. * @param meshesNames defines the name of meshes to load
  106605. * @param rootUrl defines the root url to use to locate files
  106606. * @param sceneFilename defines the filename of the scene file
  106607. * @returns a new {BABYLON.MeshAssetTask} object
  106608. */
  106609. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  106610. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  106611. this._tasks.push(task);
  106612. return task;
  106613. };
  106614. /**
  106615. * Add a {BABYLON.TextFileAssetTask} to the list of active tasks
  106616. * @param taskName defines the name of the new task
  106617. * @param url defines the url of the file to load
  106618. * @returns a new {BABYLON.TextFileAssetTask} object
  106619. */
  106620. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  106621. var task = new TextFileAssetTask(taskName, url);
  106622. this._tasks.push(task);
  106623. return task;
  106624. };
  106625. /**
  106626. * Add a {BABYLON.BinaryFileAssetTask} to the list of active tasks
  106627. * @param taskName defines the name of the new task
  106628. * @param url defines the url of the file to load
  106629. * @returns a new {BABYLON.BinaryFileAssetTask} object
  106630. */
  106631. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  106632. var task = new BinaryFileAssetTask(taskName, url);
  106633. this._tasks.push(task);
  106634. return task;
  106635. };
  106636. /**
  106637. * Add a {BABYLON.ImageAssetTask} to the list of active tasks
  106638. * @param taskName defines the name of the new task
  106639. * @param url defines the url of the file to load
  106640. * @returns a new {BABYLON.ImageAssetTask} object
  106641. */
  106642. AssetsManager.prototype.addImageTask = function (taskName, url) {
  106643. var task = new ImageAssetTask(taskName, url);
  106644. this._tasks.push(task);
  106645. return task;
  106646. };
  106647. /**
  106648. * Add a {BABYLON.TextureAssetTask} to the list of active tasks
  106649. * @param taskName defines the name of the new task
  106650. * @param url defines the url of the file to load
  106651. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  106652. * @param invertY defines if you want to invert Y axis of the loaded texture (false by default)
  106653. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  106654. * @returns a new {BABYLON.TextureAssetTask} object
  106655. */
  106656. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  106657. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  106658. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  106659. this._tasks.push(task);
  106660. return task;
  106661. };
  106662. /**
  106663. * Add a {BABYLON.CubeTextureAssetTask} to the list of active tasks
  106664. * @param taskName defines the name of the new task
  106665. * @param url defines the url of the file to load
  106666. * @param extensions defines the extension to use to load the cube map (can be null)
  106667. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  106668. * @param files defines the list of files to load (can be null)
  106669. * @returns a new {BABYLON.CubeTextureAssetTask} object
  106670. */
  106671. AssetsManager.prototype.addCubeTextureTask = function (taskName, url, extensions, noMipmap, files) {
  106672. var task = new CubeTextureAssetTask(taskName, url, extensions, noMipmap, files);
  106673. this._tasks.push(task);
  106674. return task;
  106675. };
  106676. /**
  106677. *
  106678. * Add a {BABYLON.HDRCubeTextureAssetTask} to the list of active tasks
  106679. * @param taskName defines the name of the new task
  106680. * @param url defines the url of the file to load
  106681. * @param size defines the size you want for the cubemap (can be null)
  106682. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  106683. * @param generateHarmonics defines if you want to automatically generate (true by default)
  106684. * @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)
  106685. * @param reserved Internal use only
  106686. * @returns a new {BABYLON.HDRCubeTextureAssetTask} object
  106687. */
  106688. AssetsManager.prototype.addHDRCubeTextureTask = function (taskName, url, size, noMipmap, generateHarmonics, gammaSpace, reserved) {
  106689. if (noMipmap === void 0) { noMipmap = false; }
  106690. if (generateHarmonics === void 0) { generateHarmonics = true; }
  106691. if (gammaSpace === void 0) { gammaSpace = false; }
  106692. if (reserved === void 0) { reserved = false; }
  106693. var task = new HDRCubeTextureAssetTask(taskName, url, size, noMipmap, generateHarmonics, gammaSpace, reserved);
  106694. this._tasks.push(task);
  106695. return task;
  106696. };
  106697. /**
  106698. * Remove a task from the assets manager.
  106699. * @param task the task to remove
  106700. */
  106701. AssetsManager.prototype.removeTask = function (task) {
  106702. var index = this._tasks.indexOf(task);
  106703. if (index > -1) {
  106704. this._tasks.splice(index, 1);
  106705. }
  106706. };
  106707. AssetsManager.prototype._decreaseWaitingTasksCount = function (task) {
  106708. this._waitingTasksCount--;
  106709. try {
  106710. if (this.onProgress) {
  106711. this.onProgress(this._waitingTasksCount, this._totalTasksCount, task);
  106712. }
  106713. this.onProgressObservable.notifyObservers(new AssetsProgressEvent(this._waitingTasksCount, this._totalTasksCount, task));
  106714. }
  106715. catch (e) {
  106716. BABYLON.Tools.Error("Error running progress callbacks.");
  106717. console.log(e);
  106718. }
  106719. if (this._waitingTasksCount === 0) {
  106720. try {
  106721. if (this.onFinish) {
  106722. this.onFinish(this._tasks);
  106723. }
  106724. // Let's remove successfull tasks
  106725. var currentTasks = this._tasks.slice();
  106726. for (var _i = 0, currentTasks_1 = currentTasks; _i < currentTasks_1.length; _i++) {
  106727. var task = currentTasks_1[_i];
  106728. if (task.taskState === AssetTaskState.DONE) {
  106729. var index = this._tasks.indexOf(task);
  106730. if (index > -1) {
  106731. this._tasks.splice(index, 1);
  106732. }
  106733. }
  106734. }
  106735. this.onTasksDoneObservable.notifyObservers(this._tasks);
  106736. }
  106737. catch (e) {
  106738. BABYLON.Tools.Error("Error running tasks-done callbacks.");
  106739. console.log(e);
  106740. }
  106741. this._isLoading = false;
  106742. this._scene.getEngine().hideLoadingUI();
  106743. }
  106744. };
  106745. AssetsManager.prototype._runTask = function (task) {
  106746. var _this = this;
  106747. var done = function () {
  106748. try {
  106749. if (_this.onTaskSuccess) {
  106750. _this.onTaskSuccess(task);
  106751. }
  106752. _this.onTaskSuccessObservable.notifyObservers(task);
  106753. _this._decreaseWaitingTasksCount(task);
  106754. }
  106755. catch (e) {
  106756. error("Error executing task success callbacks", e);
  106757. }
  106758. };
  106759. var error = function (message, exception) {
  106760. task._setErrorObject(message, exception);
  106761. if (_this.onTaskError) {
  106762. _this.onTaskError(task);
  106763. }
  106764. _this.onTaskErrorObservable.notifyObservers(task);
  106765. _this._decreaseWaitingTasksCount(task);
  106766. };
  106767. task.run(this._scene, done, error);
  106768. };
  106769. /**
  106770. * Reset the {BABYLON.AssetsManager} and remove all tasks
  106771. * @return the current instance of the {BABYLON.AssetsManager}
  106772. */
  106773. AssetsManager.prototype.reset = function () {
  106774. this._isLoading = false;
  106775. this._tasks = new Array();
  106776. return this;
  106777. };
  106778. /**
  106779. * Start the loading process
  106780. * @return the current instance of the {BABYLON.AssetsManager}
  106781. */
  106782. AssetsManager.prototype.load = function () {
  106783. if (this._isLoading) {
  106784. return this;
  106785. }
  106786. this._isLoading = true;
  106787. this._waitingTasksCount = this._tasks.length;
  106788. this._totalTasksCount = this._tasks.length;
  106789. if (this._waitingTasksCount === 0) {
  106790. this._isLoading = false;
  106791. if (this.onFinish) {
  106792. this.onFinish(this._tasks);
  106793. }
  106794. this.onTasksDoneObservable.notifyObservers(this._tasks);
  106795. return this;
  106796. }
  106797. if (this.useDefaultLoadingScreen) {
  106798. this._scene.getEngine().displayLoadingUI();
  106799. }
  106800. for (var index = 0; index < this._tasks.length; index++) {
  106801. var task = this._tasks[index];
  106802. if (task.taskState === AssetTaskState.INIT) {
  106803. this._runTask(task);
  106804. }
  106805. }
  106806. return this;
  106807. };
  106808. return AssetsManager;
  106809. }());
  106810. BABYLON.AssetsManager = AssetsManager;
  106811. })(BABYLON || (BABYLON = {}));
  106812. //# sourceMappingURL=babylon.assetsManager.js.map
  106813. var BABYLON;
  106814. (function (BABYLON) {
  106815. var serializedGeometries = [];
  106816. var serializeGeometry = function (geometry, serializationGeometries) {
  106817. if (serializedGeometries[geometry.id]) {
  106818. return;
  106819. }
  106820. if (geometry.doNotSerialize) {
  106821. return;
  106822. }
  106823. if (geometry instanceof BABYLON.BoxGeometry) {
  106824. serializationGeometries.boxes.push(geometry.serialize());
  106825. }
  106826. else if (geometry instanceof BABYLON.SphereGeometry) {
  106827. serializationGeometries.spheres.push(geometry.serialize());
  106828. }
  106829. else if (geometry instanceof BABYLON.CylinderGeometry) {
  106830. serializationGeometries.cylinders.push(geometry.serialize());
  106831. }
  106832. else if (geometry instanceof BABYLON.TorusGeometry) {
  106833. serializationGeometries.toruses.push(geometry.serialize());
  106834. }
  106835. else if (geometry instanceof BABYLON.GroundGeometry) {
  106836. serializationGeometries.grounds.push(geometry.serialize());
  106837. }
  106838. else if (geometry instanceof BABYLON.Plane) {
  106839. serializationGeometries.planes.push(geometry.serialize());
  106840. }
  106841. else if (geometry instanceof BABYLON.TorusKnotGeometry) {
  106842. serializationGeometries.torusKnots.push(geometry.serialize());
  106843. }
  106844. else if (geometry instanceof BABYLON._PrimitiveGeometry) {
  106845. throw new Error("Unknown primitive type");
  106846. }
  106847. else {
  106848. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  106849. }
  106850. serializedGeometries[geometry.id] = true;
  106851. };
  106852. var serializeMesh = function (mesh, serializationScene) {
  106853. var serializationObject = {};
  106854. // Geometry
  106855. var geometry = mesh._geometry;
  106856. if (geometry) {
  106857. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  106858. // 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
  106859. serializeGeometry(geometry, serializationScene.geometries);
  106860. }
  106861. }
  106862. // Custom
  106863. if (mesh.serialize) {
  106864. mesh.serialize(serializationObject);
  106865. }
  106866. return serializationObject;
  106867. };
  106868. var finalizeSingleMesh = function (mesh, serializationObject) {
  106869. //only works if the mesh is already loaded
  106870. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  106871. //serialize material
  106872. if (mesh.material) {
  106873. if (mesh.material instanceof BABYLON.MultiMaterial) {
  106874. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  106875. serializationObject.materials = serializationObject.materials || [];
  106876. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  106877. serializationObject.multiMaterials.push(mesh.material.serialize());
  106878. var _loop_1 = function (submaterial) {
  106879. if (submaterial) {
  106880. if (!serializationObject.materials.some(function (mat) { return (mat.id === submaterial.id); })) {
  106881. serializationObject.materials.push(submaterial.serialize());
  106882. }
  106883. }
  106884. };
  106885. for (var _i = 0, _a = mesh.material.subMaterials; _i < _a.length; _i++) {
  106886. var submaterial = _a[_i];
  106887. _loop_1(submaterial);
  106888. }
  106889. }
  106890. }
  106891. else {
  106892. serializationObject.materials = serializationObject.materials || [];
  106893. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  106894. serializationObject.materials.push(mesh.material.serialize());
  106895. }
  106896. }
  106897. }
  106898. //serialize geometry
  106899. var geometry = mesh._geometry;
  106900. if (geometry) {
  106901. if (!serializationObject.geometries) {
  106902. serializationObject.geometries = {};
  106903. serializationObject.geometries.boxes = [];
  106904. serializationObject.geometries.spheres = [];
  106905. serializationObject.geometries.cylinders = [];
  106906. serializationObject.geometries.toruses = [];
  106907. serializationObject.geometries.grounds = [];
  106908. serializationObject.geometries.planes = [];
  106909. serializationObject.geometries.torusKnots = [];
  106910. serializationObject.geometries.vertexData = [];
  106911. }
  106912. serializeGeometry(geometry, serializationObject.geometries);
  106913. }
  106914. // Skeletons
  106915. if (mesh.skeleton) {
  106916. serializationObject.skeletons = serializationObject.skeletons || [];
  106917. serializationObject.skeletons.push(mesh.skeleton.serialize());
  106918. }
  106919. //serialize the actual mesh
  106920. serializationObject.meshes = serializationObject.meshes || [];
  106921. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  106922. }
  106923. };
  106924. var SceneSerializer = /** @class */ (function () {
  106925. function SceneSerializer() {
  106926. }
  106927. SceneSerializer.ClearCache = function () {
  106928. serializedGeometries = [];
  106929. };
  106930. SceneSerializer.Serialize = function (scene) {
  106931. var serializationObject = {};
  106932. SceneSerializer.ClearCache();
  106933. // Scene
  106934. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  106935. serializationObject.autoClear = scene.autoClear;
  106936. serializationObject.clearColor = scene.clearColor.asArray();
  106937. serializationObject.ambientColor = scene.ambientColor.asArray();
  106938. serializationObject.gravity = scene.gravity.asArray();
  106939. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  106940. serializationObject.workerCollisions = scene.workerCollisions;
  106941. // Fog
  106942. if (scene.fogMode && scene.fogMode !== 0) {
  106943. serializationObject.fogMode = scene.fogMode;
  106944. serializationObject.fogColor = scene.fogColor.asArray();
  106945. serializationObject.fogStart = scene.fogStart;
  106946. serializationObject.fogEnd = scene.fogEnd;
  106947. serializationObject.fogDensity = scene.fogDensity;
  106948. }
  106949. //Physics
  106950. if (scene.isPhysicsEnabled()) {
  106951. var physicEngine = scene.getPhysicsEngine();
  106952. if (physicEngine) {
  106953. serializationObject.physicsEnabled = true;
  106954. serializationObject.physicsGravity = physicEngine.gravity.asArray();
  106955. serializationObject.physicsEngine = physicEngine.getPhysicsPluginName();
  106956. }
  106957. }
  106958. // Metadata
  106959. if (scene.metadata) {
  106960. serializationObject.metadata = scene.metadata;
  106961. }
  106962. // Morph targets
  106963. serializationObject.morphTargetManagers = [];
  106964. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  106965. var abstractMesh = _a[_i];
  106966. var manager = abstractMesh.morphTargetManager;
  106967. if (manager) {
  106968. serializationObject.morphTargetManagers.push(manager.serialize());
  106969. }
  106970. }
  106971. // Lights
  106972. serializationObject.lights = [];
  106973. var index;
  106974. var light;
  106975. for (index = 0; index < scene.lights.length; index++) {
  106976. light = scene.lights[index];
  106977. if (!light.doNotSerialize) {
  106978. serializationObject.lights.push(light.serialize());
  106979. }
  106980. }
  106981. // Cameras
  106982. serializationObject.cameras = [];
  106983. for (index = 0; index < scene.cameras.length; index++) {
  106984. var camera = scene.cameras[index];
  106985. if (!camera.doNotSerialize) {
  106986. serializationObject.cameras.push(camera.serialize());
  106987. }
  106988. }
  106989. if (scene.activeCamera) {
  106990. serializationObject.activeCameraID = scene.activeCamera.id;
  106991. }
  106992. // Animations
  106993. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  106994. // Materials
  106995. serializationObject.materials = [];
  106996. serializationObject.multiMaterials = [];
  106997. var material;
  106998. for (index = 0; index < scene.materials.length; index++) {
  106999. material = scene.materials[index];
  107000. if (!material.doNotSerialize) {
  107001. serializationObject.materials.push(material.serialize());
  107002. }
  107003. }
  107004. // MultiMaterials
  107005. serializationObject.multiMaterials = [];
  107006. for (index = 0; index < scene.multiMaterials.length; index++) {
  107007. var multiMaterial = scene.multiMaterials[index];
  107008. serializationObject.multiMaterials.push(multiMaterial.serialize());
  107009. }
  107010. // Environment texture
  107011. if (scene.environmentTexture) {
  107012. serializationObject.environmentTexture = scene.environmentTexture.name;
  107013. }
  107014. // Skeletons
  107015. serializationObject.skeletons = [];
  107016. for (index = 0; index < scene.skeletons.length; index++) {
  107017. var skeleton = scene.skeletons[index];
  107018. if (!skeleton.doNotSerialize) {
  107019. serializationObject.skeletons.push(skeleton.serialize());
  107020. }
  107021. }
  107022. // Transform nodes
  107023. serializationObject.transformNodes = [];
  107024. for (index = 0; index < scene.transformNodes.length; index++) {
  107025. serializationObject.transformNodes.push(scene.transformNodes[index].serialize());
  107026. }
  107027. // Geometries
  107028. serializationObject.geometries = {};
  107029. serializationObject.geometries.boxes = [];
  107030. serializationObject.geometries.spheres = [];
  107031. serializationObject.geometries.cylinders = [];
  107032. serializationObject.geometries.toruses = [];
  107033. serializationObject.geometries.grounds = [];
  107034. serializationObject.geometries.planes = [];
  107035. serializationObject.geometries.torusKnots = [];
  107036. serializationObject.geometries.vertexData = [];
  107037. serializedGeometries = [];
  107038. var geometries = scene.getGeometries();
  107039. for (index = 0; index < geometries.length; index++) {
  107040. var geometry = geometries[index];
  107041. if (geometry.isReady()) {
  107042. serializeGeometry(geometry, serializationObject.geometries);
  107043. }
  107044. }
  107045. // Meshes
  107046. serializationObject.meshes = [];
  107047. for (index = 0; index < scene.meshes.length; index++) {
  107048. var abstractMesh = scene.meshes[index];
  107049. if (abstractMesh instanceof BABYLON.Mesh) {
  107050. var mesh = abstractMesh;
  107051. if (!mesh.doNotSerialize) {
  107052. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  107053. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  107054. }
  107055. }
  107056. }
  107057. }
  107058. // Particles Systems
  107059. serializationObject.particleSystems = [];
  107060. for (index = 0; index < scene.particleSystems.length; index++) {
  107061. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  107062. }
  107063. // Action Manager
  107064. if (scene.actionManager) {
  107065. serializationObject.actions = scene.actionManager.serialize("scene");
  107066. }
  107067. // Components
  107068. for (var _b = 0, _c = scene._serializableComponents; _b < _c.length; _b++) {
  107069. var component = _c[_b];
  107070. component.serialize(serializationObject);
  107071. }
  107072. return serializationObject;
  107073. };
  107074. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  107075. if (withParents === void 0) { withParents = false; }
  107076. if (withChildren === void 0) { withChildren = false; }
  107077. var serializationObject = {};
  107078. SceneSerializer.ClearCache();
  107079. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  107080. if (withParents || withChildren) {
  107081. //deliberate for loop! not for each, appended should be processed as well.
  107082. for (var i = 0; i < toSerialize.length; ++i) {
  107083. if (withChildren) {
  107084. toSerialize[i].getDescendants().forEach(function (node) {
  107085. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  107086. toSerialize.push(node);
  107087. }
  107088. });
  107089. }
  107090. //make sure the array doesn't contain the object already
  107091. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  107092. toSerialize.push(toSerialize[i].parent);
  107093. }
  107094. }
  107095. }
  107096. toSerialize.forEach(function (mesh) {
  107097. finalizeSingleMesh(mesh, serializationObject);
  107098. });
  107099. return serializationObject;
  107100. };
  107101. return SceneSerializer;
  107102. }());
  107103. BABYLON.SceneSerializer = SceneSerializer;
  107104. })(BABYLON || (BABYLON = {}));
  107105. //# sourceMappingURL=babylon.sceneSerializer.js.map
  107106. var BABYLON;
  107107. (function (BABYLON) {
  107108. /**
  107109. * Class used to generate realtime reflection / refraction cube textures
  107110. * @see http://doc.babylonjs.com/how_to/how_to_use_reflection_probes
  107111. */
  107112. var ReflectionProbe = /** @class */ (function () {
  107113. /**
  107114. * Creates a new reflection probe
  107115. * @param name defines the name of the probe
  107116. * @param size defines the texture resolution (for each face)
  107117. * @param scene defines the hosting scene
  107118. * @param generateMipMaps defines if mip maps should be generated automatically (true by default)
  107119. * @param useFloat defines if HDR data (flaot data) should be used to store colors (false by default)
  107120. */
  107121. function ReflectionProbe(
  107122. /** defines the name of the probe */
  107123. name, size, scene, generateMipMaps, useFloat) {
  107124. if (generateMipMaps === void 0) { generateMipMaps = true; }
  107125. if (useFloat === void 0) { useFloat = false; }
  107126. var _this = this;
  107127. this.name = name;
  107128. this._viewMatrix = BABYLON.Matrix.Identity();
  107129. this._target = BABYLON.Vector3.Zero();
  107130. this._add = BABYLON.Vector3.Zero();
  107131. this._invertYAxis = false;
  107132. /** Gets or sets probe position (center of the cube map) */
  107133. this.position = BABYLON.Vector3.Zero();
  107134. this._scene = scene;
  107135. // Create the scene field if not exist.
  107136. if (!this._scene.reflectionProbes) {
  107137. this._scene.reflectionProbes = new Array();
  107138. }
  107139. this._scene.reflectionProbes.push(this);
  107140. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, useFloat ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  107141. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  107142. switch (faceIndex) {
  107143. case 0:
  107144. _this._add.copyFromFloats(1, 0, 0);
  107145. break;
  107146. case 1:
  107147. _this._add.copyFromFloats(-1, 0, 0);
  107148. break;
  107149. case 2:
  107150. _this._add.copyFromFloats(0, _this._invertYAxis ? 1 : -1, 0);
  107151. break;
  107152. case 3:
  107153. _this._add.copyFromFloats(0, _this._invertYAxis ? -1 : 1, 0);
  107154. break;
  107155. case 4:
  107156. _this._add.copyFromFloats(0, 0, 1);
  107157. break;
  107158. case 5:
  107159. _this._add.copyFromFloats(0, 0, -1);
  107160. break;
  107161. }
  107162. if (_this._attachedMesh) {
  107163. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  107164. }
  107165. _this.position.addToRef(_this._add, _this._target);
  107166. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  107167. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  107168. scene._forcedViewPosition = _this.position;
  107169. });
  107170. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  107171. scene._forcedViewPosition = null;
  107172. scene.updateTransformMatrix(true);
  107173. });
  107174. if (scene.activeCamera) {
  107175. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  107176. }
  107177. }
  107178. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  107179. /** Gets or sets the number of samples to use for multi-sampling (0 by default). Required WebGL2 */
  107180. get: function () {
  107181. return this._renderTargetTexture.samples;
  107182. },
  107183. set: function (value) {
  107184. this._renderTargetTexture.samples = value;
  107185. },
  107186. enumerable: true,
  107187. configurable: true
  107188. });
  107189. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  107190. /** Gets or sets the refresh rate to use (on every frame by default) */
  107191. get: function () {
  107192. return this._renderTargetTexture.refreshRate;
  107193. },
  107194. set: function (value) {
  107195. this._renderTargetTexture.refreshRate = value;
  107196. },
  107197. enumerable: true,
  107198. configurable: true
  107199. });
  107200. /**
  107201. * Gets the hosting scene
  107202. * @returns a Scene
  107203. */
  107204. ReflectionProbe.prototype.getScene = function () {
  107205. return this._scene;
  107206. };
  107207. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  107208. /** Gets the internal CubeTexture used to render to */
  107209. get: function () {
  107210. return this._renderTargetTexture;
  107211. },
  107212. enumerable: true,
  107213. configurable: true
  107214. });
  107215. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  107216. /** Gets the list of meshes to render */
  107217. get: function () {
  107218. return this._renderTargetTexture.renderList;
  107219. },
  107220. enumerable: true,
  107221. configurable: true
  107222. });
  107223. /**
  107224. * Attach the probe to a specific mesh (Rendering will be done from attached mesh's position)
  107225. * @param mesh defines the mesh to attach to
  107226. */
  107227. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  107228. this._attachedMesh = mesh;
  107229. };
  107230. /**
  107231. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups
  107232. * @param renderingGroupId The rendering group id corresponding to its index
  107233. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  107234. */
  107235. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  107236. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  107237. };
  107238. /**
  107239. * Clean all associated resources
  107240. */
  107241. ReflectionProbe.prototype.dispose = function () {
  107242. var index = this._scene.reflectionProbes.indexOf(this);
  107243. if (index !== -1) {
  107244. // Remove from the scene if found
  107245. this._scene.reflectionProbes.splice(index, 1);
  107246. }
  107247. if (this._renderTargetTexture) {
  107248. this._renderTargetTexture.dispose();
  107249. this._renderTargetTexture = null;
  107250. }
  107251. };
  107252. return ReflectionProbe;
  107253. }());
  107254. BABYLON.ReflectionProbe = ReflectionProbe;
  107255. })(BABYLON || (BABYLON = {}));
  107256. //# sourceMappingURL=babylon.reflectionProbe.js.map
  107257. var BABYLON;
  107258. (function (BABYLON) {
  107259. /**
  107260. * Defines the layer scene component responsible to manage any layers
  107261. * in a given scene.
  107262. */
  107263. var LayerSceneComponent = /** @class */ (function () {
  107264. /**
  107265. * Creates a new instance of the component for the given scene
  107266. * @param scene Defines the scene to register the component in
  107267. */
  107268. function LayerSceneComponent(scene) {
  107269. /**
  107270. * The component name helpfull to identify the component in the list of scene components.
  107271. */
  107272. this.name = BABYLON.SceneComponentConstants.NAME_LAYER;
  107273. this.scene = scene;
  107274. this._engine = scene.getEngine();
  107275. scene.layers = new Array();
  107276. }
  107277. /**
  107278. * Registers the component in a given scene
  107279. */
  107280. LayerSceneComponent.prototype.register = function () {
  107281. this.scene._beforeCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERADRAW_LAYER, this, this._drawBackground);
  107282. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_LAYER, this, this._drawForeground);
  107283. };
  107284. /**
  107285. * Rebuilds the elements related to this component in case of
  107286. * context lost for instance.
  107287. */
  107288. LayerSceneComponent.prototype.rebuild = function () {
  107289. var layers = this.scene.layers;
  107290. for (var _i = 0, layers_1 = layers; _i < layers_1.length; _i++) {
  107291. var layer = layers_1[_i];
  107292. layer._rebuild();
  107293. }
  107294. };
  107295. /**
  107296. * Disposes the component and the associated ressources.
  107297. */
  107298. LayerSceneComponent.prototype.dispose = function () {
  107299. var layers = this.scene.layers;
  107300. while (layers.length) {
  107301. layers[0].dispose();
  107302. }
  107303. };
  107304. LayerSceneComponent.prototype._draw = function (camera, isBackground) {
  107305. var layers = this.scene.layers;
  107306. if (layers.length) {
  107307. this._engine.setDepthBuffer(false);
  107308. var cameraLayerMask = camera.layerMask;
  107309. for (var _i = 0, layers_2 = layers; _i < layers_2.length; _i++) {
  107310. var layer = layers_2[_i];
  107311. if (layer.isBackground === isBackground && ((layer.layerMask & cameraLayerMask) !== 0)) {
  107312. layer.render();
  107313. }
  107314. }
  107315. this._engine.setDepthBuffer(true);
  107316. }
  107317. };
  107318. LayerSceneComponent.prototype._drawBackground = function (camera) {
  107319. this._draw(camera, true);
  107320. };
  107321. LayerSceneComponent.prototype._drawForeground = function (camera) {
  107322. this._draw(camera, false);
  107323. };
  107324. return LayerSceneComponent;
  107325. }());
  107326. BABYLON.LayerSceneComponent = LayerSceneComponent;
  107327. })(BABYLON || (BABYLON = {}));
  107328. //# sourceMappingURL=babylon.layerSceneComponent.js.map
  107329. var BABYLON;
  107330. (function (BABYLON) {
  107331. var Layer = /** @class */ (function () {
  107332. function Layer(name, imgUrl, scene, isBackground, color) {
  107333. this.name = name;
  107334. this.scale = new BABYLON.Vector2(1, 1);
  107335. this.offset = new BABYLON.Vector2(0, 0);
  107336. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  107337. this.layerMask = 0x0FFFFFFF;
  107338. this._vertexBuffers = {};
  107339. // Events
  107340. /**
  107341. * An event triggered when the layer is disposed.
  107342. */
  107343. this.onDisposeObservable = new BABYLON.Observable();
  107344. /**
  107345. * An event triggered before rendering the scene
  107346. */
  107347. this.onBeforeRenderObservable = new BABYLON.Observable();
  107348. /**
  107349. * An event triggered after rendering the scene
  107350. */
  107351. this.onAfterRenderObservable = new BABYLON.Observable();
  107352. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  107353. this.isBackground = isBackground === undefined ? true : isBackground;
  107354. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  107355. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  107356. var layerComponent = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_LAYER);
  107357. if (!layerComponent) {
  107358. layerComponent = new BABYLON.LayerSceneComponent(this._scene);
  107359. this._scene._addComponent(layerComponent);
  107360. }
  107361. this._scene.layers.push(this);
  107362. var engine = this._scene.getEngine();
  107363. // VBO
  107364. var vertices = [];
  107365. vertices.push(1, 1);
  107366. vertices.push(-1, 1);
  107367. vertices.push(-1, -1);
  107368. vertices.push(1, -1);
  107369. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  107370. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  107371. this._createIndexBuffer();
  107372. // Effects
  107373. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  107374. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  107375. }
  107376. Object.defineProperty(Layer.prototype, "onDispose", {
  107377. set: function (callback) {
  107378. if (this._onDisposeObserver) {
  107379. this.onDisposeObservable.remove(this._onDisposeObserver);
  107380. }
  107381. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  107382. },
  107383. enumerable: true,
  107384. configurable: true
  107385. });
  107386. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  107387. set: function (callback) {
  107388. if (this._onBeforeRenderObserver) {
  107389. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  107390. }
  107391. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  107392. },
  107393. enumerable: true,
  107394. configurable: true
  107395. });
  107396. Object.defineProperty(Layer.prototype, "onAfterRender", {
  107397. set: function (callback) {
  107398. if (this._onAfterRenderObserver) {
  107399. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  107400. }
  107401. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  107402. },
  107403. enumerable: true,
  107404. configurable: true
  107405. });
  107406. Layer.prototype._createIndexBuffer = function () {
  107407. var engine = this._scene.getEngine();
  107408. // Indices
  107409. var indices = [];
  107410. indices.push(0);
  107411. indices.push(1);
  107412. indices.push(2);
  107413. indices.push(0);
  107414. indices.push(2);
  107415. indices.push(3);
  107416. this._indexBuffer = engine.createIndexBuffer(indices);
  107417. };
  107418. /** @hidden */
  107419. Layer.prototype._rebuild = function () {
  107420. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  107421. if (vb) {
  107422. vb._rebuild();
  107423. }
  107424. this._createIndexBuffer();
  107425. };
  107426. Layer.prototype.render = function () {
  107427. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  107428. // Check
  107429. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  107430. return;
  107431. var engine = this._scene.getEngine();
  107432. this.onBeforeRenderObservable.notifyObservers(this);
  107433. // Render
  107434. engine.enableEffect(currentEffect);
  107435. engine.setState(false);
  107436. // Texture
  107437. currentEffect.setTexture("textureSampler", this.texture);
  107438. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  107439. // Color
  107440. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  107441. // Scale / offset
  107442. currentEffect.setVector2("offset", this.offset);
  107443. currentEffect.setVector2("scale", this.scale);
  107444. // VBOs
  107445. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  107446. // Draw order
  107447. if (!this.alphaTest) {
  107448. engine.setAlphaMode(this.alphaBlendingMode);
  107449. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  107450. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  107451. }
  107452. else {
  107453. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  107454. }
  107455. this.onAfterRenderObservable.notifyObservers(this);
  107456. };
  107457. Layer.prototype.dispose = function () {
  107458. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  107459. if (vertexBuffer) {
  107460. vertexBuffer.dispose();
  107461. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  107462. }
  107463. if (this._indexBuffer) {
  107464. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  107465. this._indexBuffer = null;
  107466. }
  107467. if (this.texture) {
  107468. this.texture.dispose();
  107469. this.texture = null;
  107470. }
  107471. // Remove from scene
  107472. var index = this._scene.layers.indexOf(this);
  107473. this._scene.layers.splice(index, 1);
  107474. // Callback
  107475. this.onDisposeObservable.notifyObservers(this);
  107476. this.onDisposeObservable.clear();
  107477. this.onAfterRenderObservable.clear();
  107478. this.onBeforeRenderObservable.clear();
  107479. };
  107480. return Layer;
  107481. }());
  107482. BABYLON.Layer = Layer;
  107483. })(BABYLON || (BABYLON = {}));
  107484. //# sourceMappingURL=babylon.layer.js.map
  107485. var BABYLON;
  107486. (function (BABYLON) {
  107487. var TextureTools = /** @class */ (function () {
  107488. function TextureTools() {
  107489. }
  107490. /**
  107491. * Uses the GPU to create a copy texture rescaled at a given size
  107492. * @param texture Texture to copy from
  107493. * @param width Desired width
  107494. * @param height Desired height
  107495. * @return Generated texture
  107496. */
  107497. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  107498. if (useBilinearMode === void 0) { useBilinearMode = true; }
  107499. var scene = texture.getScene();
  107500. var engine = scene.getEngine();
  107501. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  107502. rtt.wrapU = texture.wrapU;
  107503. rtt.wrapV = texture.wrapV;
  107504. rtt.uOffset = texture.uOffset;
  107505. rtt.vOffset = texture.vOffset;
  107506. rtt.uScale = texture.uScale;
  107507. rtt.vScale = texture.vScale;
  107508. rtt.uAng = texture.uAng;
  107509. rtt.vAng = texture.vAng;
  107510. rtt.wAng = texture.wAng;
  107511. rtt.coordinatesIndex = texture.coordinatesIndex;
  107512. rtt.level = texture.level;
  107513. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  107514. rtt._texture.isReady = false;
  107515. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  107516. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  107517. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  107518. passPostProcess.getEffect().executeWhenCompiled(function () {
  107519. passPostProcess.onApply = function (effect) {
  107520. effect.setTexture("textureSampler", texture);
  107521. };
  107522. var internalTexture = rtt.getInternalTexture();
  107523. if (internalTexture) {
  107524. scene.postProcessManager.directRender([passPostProcess], internalTexture);
  107525. engine.unBindFramebuffer(internalTexture);
  107526. rtt.disposeFramebufferObjects();
  107527. passPostProcess.dispose();
  107528. internalTexture.isReady = true;
  107529. }
  107530. });
  107531. return rtt;
  107532. };
  107533. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  107534. if (!scene._environmentBRDFTexture) {
  107535. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  107536. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  107537. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  107538. scene._environmentBRDFTexture = texture;
  107539. }
  107540. return scene._environmentBRDFTexture;
  107541. };
  107542. 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=";
  107543. return TextureTools;
  107544. }());
  107545. BABYLON.TextureTools = TextureTools;
  107546. })(BABYLON || (BABYLON = {}));
  107547. //# sourceMappingURL=babylon.textureTools.js.map
  107548. var BABYLON;
  107549. (function (BABYLON) {
  107550. /**
  107551. * The framing behavior (BABYLON.FramingBehavior) is designed to automatically position an ArcRotateCamera when its target is set to a mesh. It is also useful if you want to prevent the camera to go under a virtual horizontal plane.
  107552. * @see http://doc.babylonjs.com/how_to/camera_behaviors#framing-behavior
  107553. */
  107554. var FramingBehavior = /** @class */ (function () {
  107555. function FramingBehavior() {
  107556. this._mode = FramingBehavior.FitFrustumSidesMode;
  107557. this._radiusScale = 1.0;
  107558. this._positionScale = 0.5;
  107559. this._defaultElevation = 0.3;
  107560. this._elevationReturnTime = 1500;
  107561. this._elevationReturnWaitTime = 1000;
  107562. this._zoomStopsAnimation = false;
  107563. this._framingTime = 1500;
  107564. /**
  107565. * Define if the behavior should automatically change the configured
  107566. * camera limits and sensibilities.
  107567. */
  107568. this.autoCorrectCameraLimitsAndSensibility = true;
  107569. this._isPointerDown = false;
  107570. this._lastInteractionTime = -Infinity;
  107571. // Framing control
  107572. this._animatables = new Array();
  107573. this._betaIsAnimating = false;
  107574. }
  107575. Object.defineProperty(FramingBehavior.prototype, "name", {
  107576. /**
  107577. * Gets the name of the behavior.
  107578. */
  107579. get: function () {
  107580. return "Framing";
  107581. },
  107582. enumerable: true,
  107583. configurable: true
  107584. });
  107585. Object.defineProperty(FramingBehavior.prototype, "mode", {
  107586. /**
  107587. * Gets current mode used by the behavior.
  107588. */
  107589. get: function () {
  107590. return this._mode;
  107591. },
  107592. /**
  107593. * Sets the current mode used by the behavior
  107594. */
  107595. set: function (mode) {
  107596. this._mode = mode;
  107597. },
  107598. enumerable: true,
  107599. configurable: true
  107600. });
  107601. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  107602. /**
  107603. * Gets the scale applied to the radius
  107604. */
  107605. get: function () {
  107606. return this._radiusScale;
  107607. },
  107608. /**
  107609. * Sets the scale applied to the radius (1 by default)
  107610. */
  107611. set: function (radius) {
  107612. this._radiusScale = radius;
  107613. },
  107614. enumerable: true,
  107615. configurable: true
  107616. });
  107617. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  107618. /**
  107619. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  107620. */
  107621. get: function () {
  107622. return this._positionScale;
  107623. },
  107624. /**
  107625. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  107626. */
  107627. set: function (scale) {
  107628. this._positionScale = scale;
  107629. },
  107630. enumerable: true,
  107631. configurable: true
  107632. });
  107633. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  107634. /**
  107635. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  107636. * behaviour is triggered, in radians.
  107637. */
  107638. get: function () {
  107639. return this._defaultElevation;
  107640. },
  107641. /**
  107642. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  107643. * behaviour is triggered, in radians.
  107644. */
  107645. set: function (elevation) {
  107646. this._defaultElevation = elevation;
  107647. },
  107648. enumerable: true,
  107649. configurable: true
  107650. });
  107651. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  107652. /**
  107653. * Gets the time (in milliseconds) taken to return to the default beta position.
  107654. * Negative value indicates camera should not return to default.
  107655. */
  107656. get: function () {
  107657. return this._elevationReturnTime;
  107658. },
  107659. /**
  107660. * Sets the time (in milliseconds) taken to return to the default beta position.
  107661. * Negative value indicates camera should not return to default.
  107662. */
  107663. set: function (speed) {
  107664. this._elevationReturnTime = speed;
  107665. },
  107666. enumerable: true,
  107667. configurable: true
  107668. });
  107669. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  107670. /**
  107671. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  107672. */
  107673. get: function () {
  107674. return this._elevationReturnWaitTime;
  107675. },
  107676. /**
  107677. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  107678. */
  107679. set: function (time) {
  107680. this._elevationReturnWaitTime = time;
  107681. },
  107682. enumerable: true,
  107683. configurable: true
  107684. });
  107685. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  107686. /**
  107687. * Gets the flag that indicates if user zooming should stop animation.
  107688. */
  107689. get: function () {
  107690. return this._zoomStopsAnimation;
  107691. },
  107692. /**
  107693. * Sets the flag that indicates if user zooming should stop animation.
  107694. */
  107695. set: function (flag) {
  107696. this._zoomStopsAnimation = flag;
  107697. },
  107698. enumerable: true,
  107699. configurable: true
  107700. });
  107701. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  107702. /**
  107703. * Gets the transition time when framing the mesh, in milliseconds
  107704. */
  107705. get: function () {
  107706. return this._framingTime;
  107707. },
  107708. /**
  107709. * Sets the transition time when framing the mesh, in milliseconds
  107710. */
  107711. set: function (time) {
  107712. this._framingTime = time;
  107713. },
  107714. enumerable: true,
  107715. configurable: true
  107716. });
  107717. /**
  107718. * Initializes the behavior.
  107719. */
  107720. FramingBehavior.prototype.init = function () {
  107721. // Do notihng
  107722. };
  107723. /**
  107724. * Attaches the behavior to its arc rotate camera.
  107725. * @param camera Defines the camera to attach the behavior to
  107726. */
  107727. FramingBehavior.prototype.attach = function (camera) {
  107728. var _this = this;
  107729. this._attachedCamera = camera;
  107730. var scene = this._attachedCamera.getScene();
  107731. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  107732. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  107733. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  107734. _this._isPointerDown = true;
  107735. return;
  107736. }
  107737. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  107738. _this._isPointerDown = false;
  107739. }
  107740. });
  107741. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  107742. if (mesh) {
  107743. _this.zoomOnMesh(mesh);
  107744. }
  107745. });
  107746. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  107747. // Stop the animation if there is user interaction and the animation should stop for this interaction
  107748. _this._applyUserInteraction();
  107749. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  107750. // back to the default position after a given timeout
  107751. _this._maintainCameraAboveGround();
  107752. });
  107753. };
  107754. /**
  107755. * Detaches the behavior from its current arc rotate camera.
  107756. */
  107757. FramingBehavior.prototype.detach = function () {
  107758. if (!this._attachedCamera) {
  107759. return;
  107760. }
  107761. var scene = this._attachedCamera.getScene();
  107762. if (this._onPrePointerObservableObserver) {
  107763. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  107764. }
  107765. if (this._onAfterCheckInputsObserver) {
  107766. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  107767. }
  107768. if (this._onMeshTargetChangedObserver) {
  107769. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  107770. }
  107771. this._attachedCamera = null;
  107772. };
  107773. /**
  107774. * Targets the given mesh and updates zoom level accordingly.
  107775. * @param mesh The mesh to target.
  107776. * @param radius Optional. If a cached radius position already exists, overrides default.
  107777. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  107778. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  107779. * @param onAnimationEnd Callback triggered at the end of the framing animation
  107780. */
  107781. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  107782. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  107783. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  107784. mesh.computeWorldMatrix(true);
  107785. var boundingBox = mesh.getBoundingInfo().boundingBox;
  107786. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  107787. };
  107788. /**
  107789. * Targets the given mesh with its children and updates zoom level accordingly.
  107790. * @param mesh The mesh to target.
  107791. * @param radius Optional. If a cached radius position already exists, overrides default.
  107792. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  107793. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  107794. * @param onAnimationEnd Callback triggered at the end of the framing animation
  107795. */
  107796. FramingBehavior.prototype.zoomOnMeshHierarchy = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  107797. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  107798. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  107799. mesh.computeWorldMatrix(true);
  107800. var boundingBox = mesh.getHierarchyBoundingVectors(true);
  107801. this.zoomOnBoundingInfo(boundingBox.min, boundingBox.max, focusOnOriginXZ, onAnimationEnd);
  107802. };
  107803. /**
  107804. * Targets the given meshes with their children and updates zoom level accordingly.
  107805. * @param meshes The mesh to target.
  107806. * @param radius Optional. If a cached radius position already exists, overrides default.
  107807. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  107808. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  107809. * @param onAnimationEnd Callback triggered at the end of the framing animation
  107810. */
  107811. FramingBehavior.prototype.zoomOnMeshesHierarchy = function (meshes, focusOnOriginXZ, onAnimationEnd) {
  107812. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  107813. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  107814. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  107815. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  107816. for (var i = 0; i < meshes.length; i++) {
  107817. var boundingInfo = meshes[i].getHierarchyBoundingVectors(true);
  107818. BABYLON.Tools.CheckExtends(boundingInfo.min, min, max);
  107819. BABYLON.Tools.CheckExtends(boundingInfo.max, min, max);
  107820. }
  107821. this.zoomOnBoundingInfo(min, max, focusOnOriginXZ, onAnimationEnd);
  107822. };
  107823. /**
  107824. * Targets the bounding box info defined by its extends and updates zoom level accordingly.
  107825. * @param minimumWorld Determines the smaller position of the bounding box extend
  107826. * @param maximumWorld Determines the bigger position of the bounding box extend
  107827. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  107828. * @param onAnimationEnd Callback triggered at the end of the framing animation
  107829. */
  107830. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  107831. var _this = this;
  107832. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  107833. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  107834. var zoomTarget;
  107835. if (!this._attachedCamera) {
  107836. return;
  107837. }
  107838. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  107839. var bottom = minimumWorld.y;
  107840. var top = maximumWorld.y;
  107841. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  107842. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  107843. if (focusOnOriginXZ) {
  107844. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  107845. }
  107846. else {
  107847. var centerWorld = minimumWorld.add(radiusWorld);
  107848. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  107849. }
  107850. if (!this._vectorTransition) {
  107851. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  107852. }
  107853. this._betaIsAnimating = true;
  107854. var animatable = BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);
  107855. if (animatable) {
  107856. this._animatables.push(animatable);
  107857. }
  107858. // sets the radius and lower radius bounds
  107859. // Small delta ensures camera is not always at lower zoom limit.
  107860. var radius = 0;
  107861. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  107862. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  107863. if (this.autoCorrectCameraLimitsAndSensibility) {
  107864. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  107865. }
  107866. radius = position;
  107867. }
  107868. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  107869. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  107870. if (this.autoCorrectCameraLimitsAndSensibility && this._attachedCamera.lowerRadiusLimit === null) {
  107871. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  107872. }
  107873. }
  107874. // Set sensibilities
  107875. if (this.autoCorrectCameraLimitsAndSensibility) {
  107876. var extend = maximumWorld.subtract(minimumWorld).length();
  107877. this._attachedCamera.panningSensibility = 5000 / extend;
  107878. this._attachedCamera.wheelPrecision = 100 / radius;
  107879. }
  107880. // transition to new radius
  107881. if (!this._radiusTransition) {
  107882. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  107883. }
  107884. animatable = BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {
  107885. _this.stopAllAnimations();
  107886. if (onAnimationEnd) {
  107887. onAnimationEnd();
  107888. }
  107889. if (_this._attachedCamera) {
  107890. _this._attachedCamera.storeState();
  107891. }
  107892. });
  107893. if (animatable) {
  107894. this._animatables.push(animatable);
  107895. }
  107896. };
  107897. /**
  107898. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  107899. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  107900. * frustum width.
  107901. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  107902. * to fully enclose the mesh in the viewing frustum.
  107903. */
  107904. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  107905. var size = maximumWorld.subtract(minimumWorld);
  107906. var boxVectorGlobalDiagonal = size.length();
  107907. var frustumSlope = this._getFrustumSlope();
  107908. // Formula for setting distance
  107909. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  107910. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  107911. // Horizon distance
  107912. var radius = radiusWithoutFraming * this._radiusScale;
  107913. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  107914. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  107915. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  107916. var camera = this._attachedCamera;
  107917. if (!camera) {
  107918. return 0;
  107919. }
  107920. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  107921. // Don't exceed the requested limit
  107922. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  107923. }
  107924. // Don't exceed the upper radius limit
  107925. if (camera.upperRadiusLimit) {
  107926. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  107927. }
  107928. return distance;
  107929. };
  107930. /**
  107931. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  107932. * is automatically returned to its default position (expected to be above ground plane).
  107933. */
  107934. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  107935. var _this = this;
  107936. if (this._elevationReturnTime < 0) {
  107937. return;
  107938. }
  107939. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  107940. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  107941. var limitBeta = Math.PI * 0.5;
  107942. // Bring the camera back up if below the ground plane
  107943. if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  107944. this._betaIsAnimating = true;
  107945. //Transition to new position
  107946. this.stopAllAnimations();
  107947. if (!this._betaTransition) {
  107948. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  107949. }
  107950. var animatabe = BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  107951. _this._clearAnimationLocks();
  107952. _this.stopAllAnimations();
  107953. });
  107954. if (animatabe) {
  107955. this._animatables.push(animatabe);
  107956. }
  107957. }
  107958. };
  107959. /**
  107960. * Returns the frustum slope based on the canvas ratio and camera FOV
  107961. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  107962. */
  107963. FramingBehavior.prototype._getFrustumSlope = function () {
  107964. // Calculate the viewport ratio
  107965. // Aspect Ratio is Height/Width.
  107966. var camera = this._attachedCamera;
  107967. if (!camera) {
  107968. return BABYLON.Vector2.Zero();
  107969. }
  107970. var engine = camera.getScene().getEngine();
  107971. var aspectRatio = engine.getAspectRatio(camera);
  107972. // Camera FOV is the vertical field of view (top-bottom) in radians.
  107973. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  107974. var frustumSlopeY = Math.tan(camera.fov / 2);
  107975. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  107976. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  107977. // along the forward vector.
  107978. var frustumSlopeX = frustumSlopeY * aspectRatio;
  107979. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  107980. };
  107981. /**
  107982. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  107983. */
  107984. FramingBehavior.prototype._clearAnimationLocks = function () {
  107985. this._betaIsAnimating = false;
  107986. };
  107987. /**
  107988. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  107989. */
  107990. FramingBehavior.prototype._applyUserInteraction = function () {
  107991. if (this.isUserIsMoving) {
  107992. this._lastInteractionTime = BABYLON.Tools.Now;
  107993. this.stopAllAnimations();
  107994. this._clearAnimationLocks();
  107995. }
  107996. };
  107997. /**
  107998. * Stops and removes all animations that have been applied to the camera
  107999. */
  108000. FramingBehavior.prototype.stopAllAnimations = function () {
  108001. if (this._attachedCamera) {
  108002. this._attachedCamera.animations = [];
  108003. }
  108004. while (this._animatables.length) {
  108005. if (this._animatables[0]) {
  108006. this._animatables[0].onAnimationEnd = null;
  108007. this._animatables[0].stop();
  108008. }
  108009. this._animatables.shift();
  108010. }
  108011. };
  108012. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  108013. /**
  108014. * Gets a value indicating if the user is moving the camera
  108015. */
  108016. get: function () {
  108017. if (!this._attachedCamera) {
  108018. return false;
  108019. }
  108020. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  108021. this._attachedCamera.inertialBetaOffset !== 0 ||
  108022. this._attachedCamera.inertialRadiusOffset !== 0 ||
  108023. this._attachedCamera.inertialPanningX !== 0 ||
  108024. this._attachedCamera.inertialPanningY !== 0 ||
  108025. this._isPointerDown;
  108026. },
  108027. enumerable: true,
  108028. configurable: true
  108029. });
  108030. /**
  108031. * The easing function used by animations
  108032. */
  108033. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  108034. /**
  108035. * The easing mode used by animations
  108036. */
  108037. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  108038. // Statics
  108039. /**
  108040. * The camera can move all the way towards the mesh.
  108041. */
  108042. FramingBehavior.IgnoreBoundsSizeMode = 0;
  108043. /**
  108044. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  108045. */
  108046. FramingBehavior.FitFrustumSidesMode = 1;
  108047. return FramingBehavior;
  108048. }());
  108049. BABYLON.FramingBehavior = FramingBehavior;
  108050. })(BABYLON || (BABYLON = {}));
  108051. //# sourceMappingURL=babylon.framingBehavior.js.map
  108052. var BABYLON;
  108053. (function (BABYLON) {
  108054. /**
  108055. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  108056. * @see http://doc.babylonjs.com/how_to/camera_behaviors#bouncing-behavior
  108057. */
  108058. var BouncingBehavior = /** @class */ (function () {
  108059. function BouncingBehavior() {
  108060. /**
  108061. * The duration of the animation, in milliseconds
  108062. */
  108063. this.transitionDuration = 450;
  108064. /**
  108065. * Length of the distance animated by the transition when lower radius is reached
  108066. */
  108067. this.lowerRadiusTransitionRange = 2;
  108068. /**
  108069. * Length of the distance animated by the transition when upper radius is reached
  108070. */
  108071. this.upperRadiusTransitionRange = -2;
  108072. this._autoTransitionRange = false;
  108073. // Animations
  108074. this._radiusIsAnimating = false;
  108075. this._radiusBounceTransition = null;
  108076. this._animatables = new Array();
  108077. }
  108078. Object.defineProperty(BouncingBehavior.prototype, "name", {
  108079. /**
  108080. * Gets the name of the behavior.
  108081. */
  108082. get: function () {
  108083. return "Bouncing";
  108084. },
  108085. enumerable: true,
  108086. configurable: true
  108087. });
  108088. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  108089. /**
  108090. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  108091. */
  108092. get: function () {
  108093. return this._autoTransitionRange;
  108094. },
  108095. /**
  108096. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  108097. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  108098. */
  108099. set: function (value) {
  108100. var _this = this;
  108101. if (this._autoTransitionRange === value) {
  108102. return;
  108103. }
  108104. this._autoTransitionRange = value;
  108105. var camera = this._attachedCamera;
  108106. if (!camera) {
  108107. return;
  108108. }
  108109. if (value) {
  108110. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  108111. if (!mesh) {
  108112. return;
  108113. }
  108114. mesh.computeWorldMatrix(true);
  108115. var diagonal = mesh.getBoundingInfo().diagonalLength;
  108116. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  108117. _this.upperRadiusTransitionRange = diagonal * 0.05;
  108118. });
  108119. }
  108120. else if (this._onMeshTargetChangedObserver) {
  108121. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  108122. }
  108123. },
  108124. enumerable: true,
  108125. configurable: true
  108126. });
  108127. /**
  108128. * Initializes the behavior.
  108129. */
  108130. BouncingBehavior.prototype.init = function () {
  108131. // Do notihng
  108132. };
  108133. /**
  108134. * Attaches the behavior to its arc rotate camera.
  108135. * @param camera Defines the camera to attach the behavior to
  108136. */
  108137. BouncingBehavior.prototype.attach = function (camera) {
  108138. var _this = this;
  108139. this._attachedCamera = camera;
  108140. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  108141. if (!_this._attachedCamera) {
  108142. return;
  108143. }
  108144. // Add the bounce animation to the lower radius limit
  108145. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  108146. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  108147. }
  108148. // Add the bounce animation to the upper radius limit
  108149. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  108150. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  108151. }
  108152. });
  108153. };
  108154. /**
  108155. * Detaches the behavior from its current arc rotate camera.
  108156. */
  108157. BouncingBehavior.prototype.detach = function () {
  108158. if (!this._attachedCamera) {
  108159. return;
  108160. }
  108161. if (this._onAfterCheckInputsObserver) {
  108162. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  108163. }
  108164. if (this._onMeshTargetChangedObserver) {
  108165. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  108166. }
  108167. this._attachedCamera = null;
  108168. };
  108169. /**
  108170. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  108171. * @param radiusLimit The limit to check against.
  108172. * @return Bool to indicate if at limit.
  108173. */
  108174. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  108175. if (!this._attachedCamera) {
  108176. return false;
  108177. }
  108178. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  108179. return true;
  108180. }
  108181. return false;
  108182. };
  108183. /**
  108184. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  108185. * @param radiusDelta The delta by which to animate to. Can be negative.
  108186. */
  108187. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  108188. var _this = this;
  108189. if (!this._attachedCamera) {
  108190. return;
  108191. }
  108192. if (!this._radiusBounceTransition) {
  108193. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  108194. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  108195. }
  108196. // Prevent zoom until bounce has completed
  108197. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  108198. this._attachedCamera.wheelPrecision = Infinity;
  108199. this._attachedCamera.inertialRadiusOffset = 0;
  108200. // Animate to the radius limit
  108201. this.stopAllAnimations();
  108202. this._radiusIsAnimating = true;
  108203. var animatable = BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); });
  108204. if (animatable) {
  108205. this._animatables.push(animatable);
  108206. }
  108207. };
  108208. /**
  108209. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  108210. */
  108211. BouncingBehavior.prototype._clearAnimationLocks = function () {
  108212. this._radiusIsAnimating = false;
  108213. if (this._attachedCamera) {
  108214. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  108215. }
  108216. };
  108217. /**
  108218. * Stops and removes all animations that have been applied to the camera
  108219. */
  108220. BouncingBehavior.prototype.stopAllAnimations = function () {
  108221. if (this._attachedCamera) {
  108222. this._attachedCamera.animations = [];
  108223. }
  108224. while (this._animatables.length) {
  108225. this._animatables[0].onAnimationEnd = null;
  108226. this._animatables[0].stop();
  108227. this._animatables.shift();
  108228. }
  108229. };
  108230. /**
  108231. * The easing function used by animations
  108232. */
  108233. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  108234. /**
  108235. * The easing mode used by animations
  108236. */
  108237. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  108238. return BouncingBehavior;
  108239. }());
  108240. BABYLON.BouncingBehavior = BouncingBehavior;
  108241. })(BABYLON || (BABYLON = {}));
  108242. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  108243. var BABYLON;
  108244. (function (BABYLON) {
  108245. /**
  108246. * The autoRotation behavior (BABYLON.AutoRotationBehavior) is designed to create a smooth rotation of an ArcRotateCamera when there is no user interaction.
  108247. * @see http://doc.babylonjs.com/how_to/camera_behaviors#autorotation-behavior
  108248. */
  108249. var AutoRotationBehavior = /** @class */ (function () {
  108250. function AutoRotationBehavior() {
  108251. this._zoomStopsAnimation = false;
  108252. this._idleRotationSpeed = 0.05;
  108253. this._idleRotationWaitTime = 2000;
  108254. this._idleRotationSpinupTime = 2000;
  108255. this._isPointerDown = false;
  108256. this._lastFrameTime = null;
  108257. this._lastInteractionTime = -Infinity;
  108258. this._cameraRotationSpeed = 0;
  108259. this._lastFrameRadius = 0;
  108260. }
  108261. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  108262. /**
  108263. * Gets the name of the behavior.
  108264. */
  108265. get: function () {
  108266. return "AutoRotation";
  108267. },
  108268. enumerable: true,
  108269. configurable: true
  108270. });
  108271. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  108272. /**
  108273. * Gets the flag that indicates if user zooming should stop animation.
  108274. */
  108275. get: function () {
  108276. return this._zoomStopsAnimation;
  108277. },
  108278. /**
  108279. * Sets the flag that indicates if user zooming should stop animation.
  108280. */
  108281. set: function (flag) {
  108282. this._zoomStopsAnimation = flag;
  108283. },
  108284. enumerable: true,
  108285. configurable: true
  108286. });
  108287. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  108288. /**
  108289. * Gets the default speed at which the camera rotates around the model.
  108290. */
  108291. get: function () {
  108292. return this._idleRotationSpeed;
  108293. },
  108294. /**
  108295. * Sets the default speed at which the camera rotates around the model.
  108296. */
  108297. set: function (speed) {
  108298. this._idleRotationSpeed = speed;
  108299. },
  108300. enumerable: true,
  108301. configurable: true
  108302. });
  108303. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  108304. /**
  108305. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  108306. */
  108307. get: function () {
  108308. return this._idleRotationWaitTime;
  108309. },
  108310. /**
  108311. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  108312. */
  108313. set: function (time) {
  108314. this._idleRotationWaitTime = time;
  108315. },
  108316. enumerable: true,
  108317. configurable: true
  108318. });
  108319. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  108320. /**
  108321. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  108322. */
  108323. get: function () {
  108324. return this._idleRotationSpinupTime;
  108325. },
  108326. /**
  108327. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  108328. */
  108329. set: function (time) {
  108330. this._idleRotationSpinupTime = time;
  108331. },
  108332. enumerable: true,
  108333. configurable: true
  108334. });
  108335. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  108336. /**
  108337. * Gets a value indicating if the camera is currently rotating because of this behavior
  108338. */
  108339. get: function () {
  108340. return Math.abs(this._cameraRotationSpeed) > 0;
  108341. },
  108342. enumerable: true,
  108343. configurable: true
  108344. });
  108345. /**
  108346. * Initializes the behavior.
  108347. */
  108348. AutoRotationBehavior.prototype.init = function () {
  108349. // Do notihng
  108350. };
  108351. /**
  108352. * Attaches the behavior to its arc rotate camera.
  108353. * @param camera Defines the camera to attach the behavior to
  108354. */
  108355. AutoRotationBehavior.prototype.attach = function (camera) {
  108356. var _this = this;
  108357. this._attachedCamera = camera;
  108358. var scene = this._attachedCamera.getScene();
  108359. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  108360. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  108361. _this._isPointerDown = true;
  108362. return;
  108363. }
  108364. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  108365. _this._isPointerDown = false;
  108366. }
  108367. });
  108368. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  108369. var now = BABYLON.Tools.Now;
  108370. var dt = 0;
  108371. if (_this._lastFrameTime != null) {
  108372. dt = now - _this._lastFrameTime;
  108373. }
  108374. _this._lastFrameTime = now;
  108375. // Stop the animation if there is user interaction and the animation should stop for this interaction
  108376. _this._applyUserInteraction();
  108377. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  108378. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  108379. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  108380. // Step camera rotation by rotation speed
  108381. if (_this._attachedCamera) {
  108382. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  108383. }
  108384. });
  108385. };
  108386. /**
  108387. * Detaches the behavior from its current arc rotate camera.
  108388. */
  108389. AutoRotationBehavior.prototype.detach = function () {
  108390. if (!this._attachedCamera) {
  108391. return;
  108392. }
  108393. var scene = this._attachedCamera.getScene();
  108394. if (this._onPrePointerObservableObserver) {
  108395. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  108396. }
  108397. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  108398. this._attachedCamera = null;
  108399. };
  108400. /**
  108401. * Returns true if user is scrolling.
  108402. * @return true if user is scrolling.
  108403. */
  108404. AutoRotationBehavior.prototype._userIsZooming = function () {
  108405. if (!this._attachedCamera) {
  108406. return false;
  108407. }
  108408. return this._attachedCamera.inertialRadiusOffset !== 0;
  108409. };
  108410. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  108411. if (!this._attachedCamera) {
  108412. return false;
  108413. }
  108414. var zoomHasHitLimit = false;
  108415. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  108416. zoomHasHitLimit = true;
  108417. }
  108418. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  108419. this._lastFrameRadius = this._attachedCamera.radius;
  108420. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  108421. };
  108422. /**
  108423. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  108424. */
  108425. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  108426. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  108427. this._lastInteractionTime = BABYLON.Tools.Now;
  108428. }
  108429. };
  108430. // Tools
  108431. AutoRotationBehavior.prototype._userIsMoving = function () {
  108432. if (!this._attachedCamera) {
  108433. return false;
  108434. }
  108435. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  108436. this._attachedCamera.inertialBetaOffset !== 0 ||
  108437. this._attachedCamera.inertialRadiusOffset !== 0 ||
  108438. this._attachedCamera.inertialPanningX !== 0 ||
  108439. this._attachedCamera.inertialPanningY !== 0 ||
  108440. this._isPointerDown;
  108441. };
  108442. return AutoRotationBehavior;
  108443. }());
  108444. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  108445. })(BABYLON || (BABYLON = {}));
  108446. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  108447. var BABYLON;
  108448. (function (BABYLON) {
  108449. var NullEngineOptions = /** @class */ (function () {
  108450. function NullEngineOptions() {
  108451. this.renderWidth = 512;
  108452. this.renderHeight = 256;
  108453. this.textureSize = 512;
  108454. this.deterministicLockstep = false;
  108455. this.lockstepMaxSteps = 4;
  108456. }
  108457. return NullEngineOptions;
  108458. }());
  108459. BABYLON.NullEngineOptions = NullEngineOptions;
  108460. /**
  108461. * The null engine class provides support for headless version of babylon.js.
  108462. * This can be used in server side scenario or for testing purposes
  108463. */
  108464. var NullEngine = /** @class */ (function (_super) {
  108465. __extends(NullEngine, _super);
  108466. function NullEngine(options) {
  108467. if (options === void 0) { options = new NullEngineOptions(); }
  108468. var _this = _super.call(this, null) || this;
  108469. if (options.deterministicLockstep === undefined) {
  108470. options.deterministicLockstep = false;
  108471. }
  108472. if (options.lockstepMaxSteps === undefined) {
  108473. options.lockstepMaxSteps = 4;
  108474. }
  108475. _this._options = options;
  108476. // Init caps
  108477. // We consider we are on a webgl1 capable device
  108478. _this._caps = new BABYLON.EngineCapabilities();
  108479. _this._caps.maxTexturesImageUnits = 16;
  108480. _this._caps.maxVertexTextureImageUnits = 16;
  108481. _this._caps.maxTextureSize = 512;
  108482. _this._caps.maxCubemapTextureSize = 512;
  108483. _this._caps.maxRenderTextureSize = 512;
  108484. _this._caps.maxVertexAttribs = 16;
  108485. _this._caps.maxVaryingVectors = 16;
  108486. _this._caps.maxFragmentUniformVectors = 16;
  108487. _this._caps.maxVertexUniformVectors = 16;
  108488. // Extensions
  108489. _this._caps.standardDerivatives = false;
  108490. _this._caps.astc = null;
  108491. _this._caps.s3tc = null;
  108492. _this._caps.pvrtc = null;
  108493. _this._caps.etc1 = null;
  108494. _this._caps.etc2 = null;
  108495. _this._caps.textureAnisotropicFilterExtension = null;
  108496. _this._caps.maxAnisotropy = 0;
  108497. _this._caps.uintIndices = false;
  108498. _this._caps.fragmentDepthSupported = false;
  108499. _this._caps.highPrecisionShaderSupported = true;
  108500. _this._caps.colorBufferFloat = false;
  108501. _this._caps.textureFloat = false;
  108502. _this._caps.textureFloatLinearFiltering = false;
  108503. _this._caps.textureFloatRender = false;
  108504. _this._caps.textureHalfFloat = false;
  108505. _this._caps.textureHalfFloatLinearFiltering = false;
  108506. _this._caps.textureHalfFloatRender = false;
  108507. _this._caps.textureLOD = false;
  108508. _this._caps.drawBuffersExtension = false;
  108509. _this._caps.depthTextureExtension = false;
  108510. _this._caps.vertexArrayObject = false;
  108511. _this._caps.instancedArrays = false;
  108512. BABYLON.Tools.Log("Babylon.js null engine (v" + BABYLON.Engine.Version + ") launched");
  108513. // Wrappers
  108514. if (typeof URL === "undefined") {
  108515. URL = {
  108516. createObjectURL: function () { },
  108517. revokeObjectURL: function () { }
  108518. };
  108519. }
  108520. if (typeof Blob === "undefined") {
  108521. Blob = function () { };
  108522. }
  108523. return _this;
  108524. }
  108525. NullEngine.prototype.isDeterministicLockStep = function () {
  108526. return this._options.deterministicLockstep;
  108527. };
  108528. NullEngine.prototype.getLockstepMaxSteps = function () {
  108529. return this._options.lockstepMaxSteps;
  108530. };
  108531. NullEngine.prototype.getHardwareScalingLevel = function () {
  108532. return 1.0;
  108533. };
  108534. NullEngine.prototype.createVertexBuffer = function (vertices) {
  108535. return {
  108536. capacity: 0,
  108537. references: 1,
  108538. is32Bits: false
  108539. };
  108540. };
  108541. NullEngine.prototype.createIndexBuffer = function (indices) {
  108542. return {
  108543. capacity: 0,
  108544. references: 1,
  108545. is32Bits: false
  108546. };
  108547. };
  108548. NullEngine.prototype.clear = function (color, backBuffer, depth, stencil) {
  108549. if (stencil === void 0) { stencil = false; }
  108550. };
  108551. NullEngine.prototype.getRenderWidth = function (useScreen) {
  108552. if (useScreen === void 0) { useScreen = false; }
  108553. if (!useScreen && this._currentRenderTarget) {
  108554. return this._currentRenderTarget.width;
  108555. }
  108556. return this._options.renderWidth;
  108557. };
  108558. NullEngine.prototype.getRenderHeight = function (useScreen) {
  108559. if (useScreen === void 0) { useScreen = false; }
  108560. if (!useScreen && this._currentRenderTarget) {
  108561. return this._currentRenderTarget.height;
  108562. }
  108563. return this._options.renderHeight;
  108564. };
  108565. NullEngine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  108566. this._cachedViewport = viewport;
  108567. };
  108568. NullEngine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  108569. return {
  108570. transformFeedback: null,
  108571. __SPECTOR_rebuildProgram: null
  108572. };
  108573. };
  108574. NullEngine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  108575. return [];
  108576. };
  108577. NullEngine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  108578. return [];
  108579. };
  108580. NullEngine.prototype.bindSamplers = function (effect) {
  108581. this._currentEffect = null;
  108582. };
  108583. NullEngine.prototype.enableEffect = function (effect) {
  108584. this._currentEffect = effect;
  108585. if (effect.onBind) {
  108586. effect.onBind(effect);
  108587. }
  108588. if (effect._onBindObservable) {
  108589. effect._onBindObservable.notifyObservers(effect);
  108590. }
  108591. };
  108592. NullEngine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  108593. if (zOffset === void 0) { zOffset = 0; }
  108594. if (reverseSide === void 0) { reverseSide = false; }
  108595. };
  108596. NullEngine.prototype.setIntArray = function (uniform, array) {
  108597. };
  108598. NullEngine.prototype.setIntArray2 = function (uniform, array) {
  108599. };
  108600. NullEngine.prototype.setIntArray3 = function (uniform, array) {
  108601. };
  108602. NullEngine.prototype.setIntArray4 = function (uniform, array) {
  108603. };
  108604. NullEngine.prototype.setFloatArray = function (uniform, array) {
  108605. };
  108606. NullEngine.prototype.setFloatArray2 = function (uniform, array) {
  108607. };
  108608. NullEngine.prototype.setFloatArray3 = function (uniform, array) {
  108609. };
  108610. NullEngine.prototype.setFloatArray4 = function (uniform, array) {
  108611. };
  108612. NullEngine.prototype.setArray = function (uniform, array) {
  108613. };
  108614. NullEngine.prototype.setArray2 = function (uniform, array) {
  108615. };
  108616. NullEngine.prototype.setArray3 = function (uniform, array) {
  108617. };
  108618. NullEngine.prototype.setArray4 = function (uniform, array) {
  108619. };
  108620. NullEngine.prototype.setMatrices = function (uniform, matrices) {
  108621. };
  108622. NullEngine.prototype.setMatrix = function (uniform, matrix) {
  108623. };
  108624. NullEngine.prototype.setMatrix3x3 = function (uniform, matrix) {
  108625. };
  108626. NullEngine.prototype.setMatrix2x2 = function (uniform, matrix) {
  108627. };
  108628. NullEngine.prototype.setFloat = function (uniform, value) {
  108629. };
  108630. NullEngine.prototype.setFloat2 = function (uniform, x, y) {
  108631. };
  108632. NullEngine.prototype.setFloat3 = function (uniform, x, y, z) {
  108633. };
  108634. NullEngine.prototype.setBool = function (uniform, bool) {
  108635. };
  108636. NullEngine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  108637. };
  108638. NullEngine.prototype.setColor3 = function (uniform, color3) {
  108639. };
  108640. NullEngine.prototype.setColor4 = function (uniform, color3, alpha) {
  108641. };
  108642. NullEngine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  108643. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  108644. if (this._alphaMode === mode) {
  108645. return;
  108646. }
  108647. this._alphaState.alphaBlend = (mode !== BABYLON.Engine.ALPHA_DISABLE);
  108648. if (!noDepthWriteChange) {
  108649. this.setDepthWrite(mode === BABYLON.Engine.ALPHA_DISABLE);
  108650. }
  108651. this._alphaMode = mode;
  108652. };
  108653. NullEngine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  108654. };
  108655. NullEngine.prototype.wipeCaches = function (bruteForce) {
  108656. if (this.preventCacheWipeBetweenFrames) {
  108657. return;
  108658. }
  108659. this.resetTextureCache();
  108660. this._currentEffect = null;
  108661. if (bruteForce) {
  108662. this._currentProgram = null;
  108663. this._stencilState.reset();
  108664. this._depthCullingState.reset();
  108665. this._alphaState.reset();
  108666. }
  108667. this._cachedVertexBuffers = null;
  108668. this._cachedIndexBuffer = null;
  108669. this._cachedEffectForVertexBuffers = null;
  108670. };
  108671. NullEngine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  108672. };
  108673. NullEngine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  108674. };
  108675. NullEngine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  108676. };
  108677. /** @hidden */
  108678. NullEngine.prototype._createTexture = function () {
  108679. return {};
  108680. };
  108681. /** @hidden */
  108682. NullEngine.prototype._releaseTexture = function (texture) {
  108683. };
  108684. NullEngine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  108685. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  108686. if (onLoad === void 0) { onLoad = null; }
  108687. if (onError === void 0) { onError = null; }
  108688. if (buffer === void 0) { buffer = null; }
  108689. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  108690. var url = String(urlArg);
  108691. texture.url = url;
  108692. texture.generateMipMaps = !noMipmap;
  108693. texture.samplingMode = samplingMode;
  108694. texture.invertY = invertY;
  108695. texture.baseWidth = this._options.textureSize;
  108696. texture.baseHeight = this._options.textureSize;
  108697. texture.width = this._options.textureSize;
  108698. texture.height = this._options.textureSize;
  108699. if (format) {
  108700. texture.format = format;
  108701. }
  108702. texture.isReady = true;
  108703. if (onLoad) {
  108704. onLoad();
  108705. }
  108706. this._internalTexturesCache.push(texture);
  108707. return texture;
  108708. };
  108709. NullEngine.prototype.createRenderTargetTexture = function (size, options) {
  108710. var fullOptions = new BABYLON.RenderTargetCreationOptions();
  108711. if (options !== undefined && typeof options === "object") {
  108712. fullOptions.generateMipMaps = options.generateMipMaps;
  108713. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  108714. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  108715. fullOptions.type = options.type === undefined ? BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  108716. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  108717. }
  108718. else {
  108719. fullOptions.generateMipMaps = options;
  108720. fullOptions.generateDepthBuffer = true;
  108721. fullOptions.generateStencilBuffer = false;
  108722. fullOptions.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  108723. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  108724. }
  108725. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  108726. var width = size.width || size;
  108727. var height = size.height || size;
  108728. texture._depthStencilBuffer = {};
  108729. texture._framebuffer = {};
  108730. texture.baseWidth = width;
  108731. texture.baseHeight = height;
  108732. texture.width = width;
  108733. texture.height = height;
  108734. texture.isReady = true;
  108735. texture.samples = 1;
  108736. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  108737. texture.samplingMode = fullOptions.samplingMode;
  108738. texture.type = fullOptions.type;
  108739. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  108740. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  108741. this._internalTexturesCache.push(texture);
  108742. return texture;
  108743. };
  108744. NullEngine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  108745. texture.samplingMode = samplingMode;
  108746. };
  108747. NullEngine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  108748. if (this._currentRenderTarget) {
  108749. this.unBindFramebuffer(this._currentRenderTarget);
  108750. }
  108751. this._currentRenderTarget = texture;
  108752. this._currentFramebuffer = texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer;
  108753. if (this._cachedViewport && !forceFullscreenViewport) {
  108754. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  108755. }
  108756. };
  108757. NullEngine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  108758. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  108759. this._currentRenderTarget = null;
  108760. if (onBeforeUnbind) {
  108761. if (texture._MSAAFramebuffer) {
  108762. this._currentFramebuffer = texture._framebuffer;
  108763. }
  108764. onBeforeUnbind();
  108765. }
  108766. this._currentFramebuffer = null;
  108767. };
  108768. NullEngine.prototype.createDynamicVertexBuffer = function (vertices) {
  108769. var vbo = {
  108770. capacity: 1,
  108771. references: 1,
  108772. is32Bits: false
  108773. };
  108774. return vbo;
  108775. };
  108776. NullEngine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  108777. if (premulAlpha === void 0) { premulAlpha = false; }
  108778. };
  108779. /**
  108780. * @hidden
  108781. * Get the current error code of the webGL context
  108782. * @returns the error code
  108783. * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/getError
  108784. */
  108785. NullEngine.prototype.getError = function () {
  108786. return 0;
  108787. };
  108788. /** @hidden */
  108789. NullEngine.prototype._getUnpackAlignement = function () {
  108790. return 1;
  108791. };
  108792. /** @hidden */
  108793. NullEngine.prototype._unpackFlipY = function (value) {
  108794. };
  108795. NullEngine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  108796. if (offset === void 0) { offset = 0; }
  108797. };
  108798. /**
  108799. * Updates a dynamic vertex buffer.
  108800. * @param vertexBuffer the vertex buffer to update
  108801. * @param data the data used to update the vertex buffer
  108802. * @param byteOffset the byte offset of the data (optional)
  108803. * @param byteLength the byte length of the data (optional)
  108804. */
  108805. NullEngine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, byteOffset, byteLength) {
  108806. };
  108807. NullEngine.prototype._bindTextureDirectly = function (target, texture) {
  108808. if (this._boundTexturesCache[this._activeChannel] !== texture) {
  108809. this._boundTexturesCache[this._activeChannel] = texture;
  108810. return true;
  108811. }
  108812. return false;
  108813. };
  108814. /** @hidden */
  108815. NullEngine.prototype._bindTexture = function (channel, texture) {
  108816. if (channel < 0) {
  108817. return;
  108818. }
  108819. this._bindTextureDirectly(0, texture);
  108820. };
  108821. /** @hidden */
  108822. NullEngine.prototype._releaseBuffer = function (buffer) {
  108823. buffer.references--;
  108824. if (buffer.references === 0) {
  108825. return true;
  108826. }
  108827. return false;
  108828. };
  108829. NullEngine.prototype.releaseEffects = function () {
  108830. };
  108831. NullEngine.prototype.displayLoadingUI = function () {
  108832. };
  108833. NullEngine.prototype.hideLoadingUI = function () {
  108834. };
  108835. /** @hidden */
  108836. NullEngine.prototype._uploadCompressedDataToTextureDirectly = function (texture, internalFormat, width, height, data, faceIndex, lod) {
  108837. if (faceIndex === void 0) { faceIndex = 0; }
  108838. if (lod === void 0) { lod = 0; }
  108839. };
  108840. /** @hidden */
  108841. NullEngine.prototype._uploadDataToTextureDirectly = function (texture, imageData, faceIndex, lod) {
  108842. if (faceIndex === void 0) { faceIndex = 0; }
  108843. if (lod === void 0) { lod = 0; }
  108844. };
  108845. /** @hidden */
  108846. NullEngine.prototype._uploadArrayBufferViewToTexture = function (texture, imageData, faceIndex, lod) {
  108847. if (faceIndex === void 0) { faceIndex = 0; }
  108848. if (lod === void 0) { lod = 0; }
  108849. };
  108850. /** @hidden */
  108851. NullEngine.prototype._uploadImageToTexture = function (texture, image, faceIndex, lod) {
  108852. if (faceIndex === void 0) { faceIndex = 0; }
  108853. if (lod === void 0) { lod = 0; }
  108854. };
  108855. return NullEngine;
  108856. }(BABYLON.Engine));
  108857. BABYLON.NullEngine = NullEngine;
  108858. })(BABYLON || (BABYLON = {}));
  108859. //# sourceMappingURL=babylon.nullEngine.js.map
  108860. var BABYLON;
  108861. (function (BABYLON) {
  108862. /**
  108863. * This class can be used to get instrumentation data from a Babylon engine
  108864. */
  108865. var EngineInstrumentation = /** @class */ (function () {
  108866. function EngineInstrumentation(engine) {
  108867. this.engine = engine;
  108868. this._captureGPUFrameTime = false;
  108869. this._gpuFrameTime = new BABYLON.PerfCounter();
  108870. this._captureShaderCompilationTime = false;
  108871. this._shaderCompilationTime = new BABYLON.PerfCounter();
  108872. // Observers
  108873. this._onBeginFrameObserver = null;
  108874. this._onEndFrameObserver = null;
  108875. this._onBeforeShaderCompilationObserver = null;
  108876. this._onAfterShaderCompilationObserver = null;
  108877. }
  108878. Object.defineProperty(EngineInstrumentation.prototype, "gpuFrameTimeCounter", {
  108879. // Properties
  108880. /**
  108881. * Gets the perf counter used for GPU frame time
  108882. */
  108883. get: function () {
  108884. return this._gpuFrameTime;
  108885. },
  108886. enumerable: true,
  108887. configurable: true
  108888. });
  108889. Object.defineProperty(EngineInstrumentation.prototype, "captureGPUFrameTime", {
  108890. /**
  108891. * Gets the GPU frame time capture status
  108892. */
  108893. get: function () {
  108894. return this._captureGPUFrameTime;
  108895. },
  108896. /**
  108897. * Enable or disable the GPU frame time capture
  108898. */
  108899. set: function (value) {
  108900. var _this = this;
  108901. if (value === this._captureGPUFrameTime) {
  108902. return;
  108903. }
  108904. this._captureGPUFrameTime = value;
  108905. if (value) {
  108906. this._onBeginFrameObserver = this.engine.onBeginFrameObservable.add(function () {
  108907. if (!_this._gpuFrameTimeToken) {
  108908. _this._gpuFrameTimeToken = _this.engine.startTimeQuery();
  108909. }
  108910. });
  108911. this._onEndFrameObserver = this.engine.onEndFrameObservable.add(function () {
  108912. if (!_this._gpuFrameTimeToken) {
  108913. return;
  108914. }
  108915. var time = _this.engine.endTimeQuery(_this._gpuFrameTimeToken);
  108916. if (time > -1) {
  108917. _this._gpuFrameTimeToken = null;
  108918. _this._gpuFrameTime.fetchNewFrame();
  108919. _this._gpuFrameTime.addCount(time, true);
  108920. }
  108921. });
  108922. }
  108923. else {
  108924. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  108925. this._onBeginFrameObserver = null;
  108926. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  108927. this._onEndFrameObserver = null;
  108928. }
  108929. },
  108930. enumerable: true,
  108931. configurable: true
  108932. });
  108933. Object.defineProperty(EngineInstrumentation.prototype, "shaderCompilationTimeCounter", {
  108934. /**
  108935. * Gets the perf counter used for shader compilation time
  108936. */
  108937. get: function () {
  108938. return this._shaderCompilationTime;
  108939. },
  108940. enumerable: true,
  108941. configurable: true
  108942. });
  108943. Object.defineProperty(EngineInstrumentation.prototype, "captureShaderCompilationTime", {
  108944. /**
  108945. * Gets the shader compilation time capture status
  108946. */
  108947. get: function () {
  108948. return this._captureShaderCompilationTime;
  108949. },
  108950. /**
  108951. * Enable or disable the shader compilation time capture
  108952. */
  108953. set: function (value) {
  108954. var _this = this;
  108955. if (value === this._captureShaderCompilationTime) {
  108956. return;
  108957. }
  108958. this._captureShaderCompilationTime = value;
  108959. if (value) {
  108960. this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(function () {
  108961. _this._shaderCompilationTime.fetchNewFrame();
  108962. _this._shaderCompilationTime.beginMonitoring();
  108963. });
  108964. this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(function () {
  108965. _this._shaderCompilationTime.endMonitoring();
  108966. });
  108967. }
  108968. else {
  108969. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  108970. this._onBeforeShaderCompilationObserver = null;
  108971. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  108972. this._onAfterShaderCompilationObserver = null;
  108973. }
  108974. },
  108975. enumerable: true,
  108976. configurable: true
  108977. });
  108978. EngineInstrumentation.prototype.dispose = function () {
  108979. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  108980. this._onBeginFrameObserver = null;
  108981. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  108982. this._onEndFrameObserver = null;
  108983. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  108984. this._onBeforeShaderCompilationObserver = null;
  108985. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  108986. this._onAfterShaderCompilationObserver = null;
  108987. this.engine = null;
  108988. };
  108989. return EngineInstrumentation;
  108990. }());
  108991. BABYLON.EngineInstrumentation = EngineInstrumentation;
  108992. })(BABYLON || (BABYLON = {}));
  108993. //# sourceMappingURL=babylon.engineInstrumentation.js.map
  108994. var BABYLON;
  108995. (function (BABYLON) {
  108996. /**
  108997. * This class can be used to get instrumentation data from a Babylon engine
  108998. */
  108999. var SceneInstrumentation = /** @class */ (function () {
  109000. function SceneInstrumentation(scene) {
  109001. var _this = this;
  109002. this.scene = scene;
  109003. this._captureActiveMeshesEvaluationTime = false;
  109004. this._activeMeshesEvaluationTime = new BABYLON.PerfCounter();
  109005. this._captureRenderTargetsRenderTime = false;
  109006. this._renderTargetsRenderTime = new BABYLON.PerfCounter();
  109007. this._captureFrameTime = false;
  109008. this._frameTime = new BABYLON.PerfCounter();
  109009. this._captureRenderTime = false;
  109010. this._renderTime = new BABYLON.PerfCounter();
  109011. this._captureInterFrameTime = false;
  109012. this._interFrameTime = new BABYLON.PerfCounter();
  109013. this._captureParticlesRenderTime = false;
  109014. this._particlesRenderTime = new BABYLON.PerfCounter();
  109015. this._captureSpritesRenderTime = false;
  109016. this._spritesRenderTime = new BABYLON.PerfCounter();
  109017. this._capturePhysicsTime = false;
  109018. this._physicsTime = new BABYLON.PerfCounter();
  109019. this._captureAnimationsTime = false;
  109020. this._animationsTime = new BABYLON.PerfCounter();
  109021. this._captureCameraRenderTime = false;
  109022. this._cameraRenderTime = new BABYLON.PerfCounter();
  109023. // Observers
  109024. this._onBeforeActiveMeshesEvaluationObserver = null;
  109025. this._onAfterActiveMeshesEvaluationObserver = null;
  109026. this._onBeforeRenderTargetsRenderObserver = null;
  109027. this._onAfterRenderTargetsRenderObserver = null;
  109028. this._onAfterRenderObserver = null;
  109029. this._onBeforeDrawPhaseObserver = null;
  109030. this._onAfterDrawPhaseObserver = null;
  109031. this._onBeforeAnimationsObserver = null;
  109032. this._onBeforeParticlesRenderingObserver = null;
  109033. this._onAfterParticlesRenderingObserver = null;
  109034. this._onBeforeSpritesRenderingObserver = null;
  109035. this._onAfterSpritesRenderingObserver = null;
  109036. this._onBeforePhysicsObserver = null;
  109037. this._onAfterPhysicsObserver = null;
  109038. this._onAfterAnimationsObserver = null;
  109039. this._onBeforeCameraRenderObserver = null;
  109040. this._onAfterCameraRenderObserver = null;
  109041. // Before render
  109042. this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(function () {
  109043. if (_this._captureActiveMeshesEvaluationTime) {
  109044. _this._activeMeshesEvaluationTime.fetchNewFrame();
  109045. }
  109046. if (_this._captureRenderTargetsRenderTime) {
  109047. _this._renderTargetsRenderTime.fetchNewFrame();
  109048. }
  109049. if (_this._captureFrameTime) {
  109050. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  109051. _this._frameTime.beginMonitoring();
  109052. }
  109053. if (_this._captureInterFrameTime) {
  109054. _this._interFrameTime.endMonitoring();
  109055. }
  109056. if (_this._captureParticlesRenderTime) {
  109057. _this._particlesRenderTime.fetchNewFrame();
  109058. }
  109059. if (_this._captureSpritesRenderTime) {
  109060. _this._spritesRenderTime.fetchNewFrame();
  109061. }
  109062. if (_this._captureAnimationsTime) {
  109063. _this._animationsTime.beginMonitoring();
  109064. }
  109065. _this.scene.getEngine()._drawCalls.fetchNewFrame();
  109066. _this.scene.getEngine()._textureCollisions.fetchNewFrame();
  109067. });
  109068. // After render
  109069. this._onAfterRenderObserver = scene.onAfterRenderObservable.add(function () {
  109070. if (_this._captureFrameTime) {
  109071. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  109072. _this._frameTime.endMonitoring();
  109073. }
  109074. if (_this._captureRenderTime) {
  109075. _this._renderTime.endMonitoring(false);
  109076. }
  109077. if (_this._captureInterFrameTime) {
  109078. _this._interFrameTime.beginMonitoring();
  109079. }
  109080. });
  109081. }
  109082. Object.defineProperty(SceneInstrumentation.prototype, "activeMeshesEvaluationTimeCounter", {
  109083. // Properties
  109084. /**
  109085. * Gets the perf counter used for active meshes evaluation time
  109086. */
  109087. get: function () {
  109088. return this._activeMeshesEvaluationTime;
  109089. },
  109090. enumerable: true,
  109091. configurable: true
  109092. });
  109093. Object.defineProperty(SceneInstrumentation.prototype, "captureActiveMeshesEvaluationTime", {
  109094. /**
  109095. * Gets the active meshes evaluation time capture status
  109096. */
  109097. get: function () {
  109098. return this._captureActiveMeshesEvaluationTime;
  109099. },
  109100. /**
  109101. * Enable or disable the active meshes evaluation time capture
  109102. */
  109103. set: function (value) {
  109104. var _this = this;
  109105. if (value === this._captureActiveMeshesEvaluationTime) {
  109106. return;
  109107. }
  109108. this._captureActiveMeshesEvaluationTime = value;
  109109. if (value) {
  109110. this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(function () {
  109111. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  109112. _this._activeMeshesEvaluationTime.beginMonitoring();
  109113. });
  109114. this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(function () {
  109115. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  109116. _this._activeMeshesEvaluationTime.endMonitoring();
  109117. });
  109118. }
  109119. else {
  109120. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  109121. this._onBeforeActiveMeshesEvaluationObserver = null;
  109122. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  109123. this._onAfterActiveMeshesEvaluationObserver = null;
  109124. }
  109125. },
  109126. enumerable: true,
  109127. configurable: true
  109128. });
  109129. Object.defineProperty(SceneInstrumentation.prototype, "renderTargetsRenderTimeCounter", {
  109130. /**
  109131. * Gets the perf counter used for render targets render time
  109132. */
  109133. get: function () {
  109134. return this._renderTargetsRenderTime;
  109135. },
  109136. enumerable: true,
  109137. configurable: true
  109138. });
  109139. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTargetsRenderTime", {
  109140. /**
  109141. * Gets the render targets render time capture status
  109142. */
  109143. get: function () {
  109144. return this._captureRenderTargetsRenderTime;
  109145. },
  109146. /**
  109147. * Enable or disable the render targets render time capture
  109148. */
  109149. set: function (value) {
  109150. var _this = this;
  109151. if (value === this._captureRenderTargetsRenderTime) {
  109152. return;
  109153. }
  109154. this._captureRenderTargetsRenderTime = value;
  109155. if (value) {
  109156. this._onBeforeRenderTargetsRenderObserver = this.scene.onBeforeRenderTargetsRenderObservable.add(function () {
  109157. BABYLON.Tools.StartPerformanceCounter("Render targets rendering");
  109158. _this._renderTargetsRenderTime.beginMonitoring();
  109159. });
  109160. this._onAfterRenderTargetsRenderObserver = this.scene.onAfterRenderTargetsRenderObservable.add(function () {
  109161. BABYLON.Tools.EndPerformanceCounter("Render targets rendering");
  109162. _this._renderTargetsRenderTime.endMonitoring(false);
  109163. });
  109164. }
  109165. else {
  109166. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  109167. this._onBeforeRenderTargetsRenderObserver = null;
  109168. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  109169. this._onAfterRenderTargetsRenderObserver = null;
  109170. }
  109171. },
  109172. enumerable: true,
  109173. configurable: true
  109174. });
  109175. Object.defineProperty(SceneInstrumentation.prototype, "particlesRenderTimeCounter", {
  109176. /**
  109177. * Gets the perf counter used for particles render time
  109178. */
  109179. get: function () {
  109180. return this._particlesRenderTime;
  109181. },
  109182. enumerable: true,
  109183. configurable: true
  109184. });
  109185. Object.defineProperty(SceneInstrumentation.prototype, "captureParticlesRenderTime", {
  109186. /**
  109187. * Gets the particles render time capture status
  109188. */
  109189. get: function () {
  109190. return this._captureParticlesRenderTime;
  109191. },
  109192. /**
  109193. * Enable or disable the particles render time capture
  109194. */
  109195. set: function (value) {
  109196. var _this = this;
  109197. if (value === this._captureParticlesRenderTime) {
  109198. return;
  109199. }
  109200. this._captureParticlesRenderTime = value;
  109201. if (value) {
  109202. this._onBeforeParticlesRenderingObserver = this.scene.onBeforeParticlesRenderingObservable.add(function () {
  109203. BABYLON.Tools.StartPerformanceCounter("Particles");
  109204. _this._particlesRenderTime.beginMonitoring();
  109205. });
  109206. this._onAfterParticlesRenderingObserver = this.scene.onAfterParticlesRenderingObservable.add(function () {
  109207. BABYLON.Tools.EndPerformanceCounter("Particles");
  109208. _this._particlesRenderTime.endMonitoring(false);
  109209. });
  109210. }
  109211. else {
  109212. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  109213. this._onBeforeParticlesRenderingObserver = null;
  109214. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  109215. this._onAfterParticlesRenderingObserver = null;
  109216. }
  109217. },
  109218. enumerable: true,
  109219. configurable: true
  109220. });
  109221. Object.defineProperty(SceneInstrumentation.prototype, "spritesRenderTimeCounter", {
  109222. /**
  109223. * Gets the perf counter used for sprites render time
  109224. */
  109225. get: function () {
  109226. return this._spritesRenderTime;
  109227. },
  109228. enumerable: true,
  109229. configurable: true
  109230. });
  109231. Object.defineProperty(SceneInstrumentation.prototype, "captureSpritesRenderTime", {
  109232. /**
  109233. * Gets the sprites render time capture status
  109234. */
  109235. get: function () {
  109236. return this._captureSpritesRenderTime;
  109237. },
  109238. /**
  109239. * Enable or disable the sprites render time capture
  109240. */
  109241. set: function (value) {
  109242. var _this = this;
  109243. if (value === this._captureSpritesRenderTime) {
  109244. return;
  109245. }
  109246. this._captureSpritesRenderTime = value;
  109247. if (!this.scene.spriteManagers) {
  109248. return;
  109249. }
  109250. if (value) {
  109251. this._onBeforeSpritesRenderingObserver = this.scene.onBeforeSpritesRenderingObservable.add(function () {
  109252. BABYLON.Tools.StartPerformanceCounter("Sprites");
  109253. _this._spritesRenderTime.beginMonitoring();
  109254. });
  109255. this._onAfterSpritesRenderingObserver = this.scene.onAfterSpritesRenderingObservable.add(function () {
  109256. BABYLON.Tools.EndPerformanceCounter("Sprites");
  109257. _this._spritesRenderTime.endMonitoring(false);
  109258. });
  109259. }
  109260. else {
  109261. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  109262. this._onBeforeSpritesRenderingObserver = null;
  109263. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  109264. this._onAfterSpritesRenderingObserver = null;
  109265. }
  109266. },
  109267. enumerable: true,
  109268. configurable: true
  109269. });
  109270. Object.defineProperty(SceneInstrumentation.prototype, "physicsTimeCounter", {
  109271. /**
  109272. * Gets the perf counter used for physics time
  109273. */
  109274. get: function () {
  109275. return this._physicsTime;
  109276. },
  109277. enumerable: true,
  109278. configurable: true
  109279. });
  109280. Object.defineProperty(SceneInstrumentation.prototype, "capturePhysicsTime", {
  109281. /**
  109282. * Gets the physics time capture status
  109283. */
  109284. get: function () {
  109285. return this._capturePhysicsTime;
  109286. },
  109287. /**
  109288. * Enable or disable the physics time capture
  109289. */
  109290. set: function (value) {
  109291. var _this = this;
  109292. if (value === this._capturePhysicsTime) {
  109293. return;
  109294. }
  109295. if (!this.scene.onBeforePhysicsObservable) {
  109296. return;
  109297. }
  109298. this._capturePhysicsTime = value;
  109299. if (value) {
  109300. this._onBeforePhysicsObserver = this.scene.onBeforePhysicsObservable.add(function () {
  109301. BABYLON.Tools.StartPerformanceCounter("Physics");
  109302. _this._physicsTime.beginMonitoring();
  109303. });
  109304. this._onAfterPhysicsObserver = this.scene.onAfterPhysicsObservable.add(function () {
  109305. BABYLON.Tools.EndPerformanceCounter("Physics");
  109306. _this._physicsTime.endMonitoring();
  109307. });
  109308. }
  109309. else {
  109310. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  109311. this._onBeforePhysicsObserver = null;
  109312. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  109313. this._onAfterPhysicsObserver = null;
  109314. }
  109315. },
  109316. enumerable: true,
  109317. configurable: true
  109318. });
  109319. Object.defineProperty(SceneInstrumentation.prototype, "animationsTimeCounter", {
  109320. /**
  109321. * Gets the perf counter used for animations time
  109322. */
  109323. get: function () {
  109324. return this._animationsTime;
  109325. },
  109326. enumerable: true,
  109327. configurable: true
  109328. });
  109329. Object.defineProperty(SceneInstrumentation.prototype, "captureAnimationsTime", {
  109330. /**
  109331. * Gets the animations time capture status
  109332. */
  109333. get: function () {
  109334. return this._captureAnimationsTime;
  109335. },
  109336. /**
  109337. * Enable or disable the animations time capture
  109338. */
  109339. set: function (value) {
  109340. var _this = this;
  109341. if (value === this._captureAnimationsTime) {
  109342. return;
  109343. }
  109344. this._captureAnimationsTime = value;
  109345. if (value) {
  109346. this._onAfterAnimationsObserver = this.scene.onAfterAnimationsObservable.add(function () {
  109347. _this._animationsTime.endMonitoring();
  109348. });
  109349. }
  109350. else {
  109351. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  109352. this._onAfterAnimationsObserver = null;
  109353. }
  109354. },
  109355. enumerable: true,
  109356. configurable: true
  109357. });
  109358. Object.defineProperty(SceneInstrumentation.prototype, "frameTimeCounter", {
  109359. /**
  109360. * Gets the perf counter used for frame time capture
  109361. */
  109362. get: function () {
  109363. return this._frameTime;
  109364. },
  109365. enumerable: true,
  109366. configurable: true
  109367. });
  109368. Object.defineProperty(SceneInstrumentation.prototype, "captureFrameTime", {
  109369. /**
  109370. * Gets the frame time capture status
  109371. */
  109372. get: function () {
  109373. return this._captureFrameTime;
  109374. },
  109375. /**
  109376. * Enable or disable the frame time capture
  109377. */
  109378. set: function (value) {
  109379. this._captureFrameTime = value;
  109380. },
  109381. enumerable: true,
  109382. configurable: true
  109383. });
  109384. Object.defineProperty(SceneInstrumentation.prototype, "interFrameTimeCounter", {
  109385. /**
  109386. * Gets the perf counter used for inter-frames time capture
  109387. */
  109388. get: function () {
  109389. return this._interFrameTime;
  109390. },
  109391. enumerable: true,
  109392. configurable: true
  109393. });
  109394. Object.defineProperty(SceneInstrumentation.prototype, "captureInterFrameTime", {
  109395. /**
  109396. * Gets the inter-frames time capture status
  109397. */
  109398. get: function () {
  109399. return this._captureInterFrameTime;
  109400. },
  109401. /**
  109402. * Enable or disable the inter-frames time capture
  109403. */
  109404. set: function (value) {
  109405. this._captureInterFrameTime = value;
  109406. },
  109407. enumerable: true,
  109408. configurable: true
  109409. });
  109410. Object.defineProperty(SceneInstrumentation.prototype, "renderTimeCounter", {
  109411. /**
  109412. * Gets the perf counter used for render time capture
  109413. */
  109414. get: function () {
  109415. return this._renderTime;
  109416. },
  109417. enumerable: true,
  109418. configurable: true
  109419. });
  109420. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTime", {
  109421. /**
  109422. * Gets the render time capture status
  109423. */
  109424. get: function () {
  109425. return this._captureRenderTime;
  109426. },
  109427. /**
  109428. * Enable or disable the render time capture
  109429. */
  109430. set: function (value) {
  109431. var _this = this;
  109432. if (value === this._captureRenderTime) {
  109433. return;
  109434. }
  109435. this._captureRenderTime = value;
  109436. if (value) {
  109437. this._onBeforeDrawPhaseObserver = this.scene.onBeforeDrawPhaseObservable.add(function () {
  109438. _this._renderTime.beginMonitoring();
  109439. BABYLON.Tools.StartPerformanceCounter("Main render");
  109440. });
  109441. this._onAfterDrawPhaseObserver = this.scene.onAfterDrawPhaseObservable.add(function () {
  109442. _this._renderTime.endMonitoring(false);
  109443. BABYLON.Tools.EndPerformanceCounter("Main render");
  109444. });
  109445. }
  109446. else {
  109447. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  109448. this._onBeforeDrawPhaseObserver = null;
  109449. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  109450. this._onAfterDrawPhaseObserver = null;
  109451. }
  109452. },
  109453. enumerable: true,
  109454. configurable: true
  109455. });
  109456. Object.defineProperty(SceneInstrumentation.prototype, "cameraRenderTimeCounter", {
  109457. /**
  109458. * Gets the perf counter used for camera render time capture
  109459. */
  109460. get: function () {
  109461. return this._cameraRenderTime;
  109462. },
  109463. enumerable: true,
  109464. configurable: true
  109465. });
  109466. Object.defineProperty(SceneInstrumentation.prototype, "captureCameraRenderTime", {
  109467. /**
  109468. * Gets the camera render time capture status
  109469. */
  109470. get: function () {
  109471. return this._captureCameraRenderTime;
  109472. },
  109473. /**
  109474. * Enable or disable the camera render time capture
  109475. */
  109476. set: function (value) {
  109477. var _this = this;
  109478. if (value === this._captureCameraRenderTime) {
  109479. return;
  109480. }
  109481. this._captureCameraRenderTime = value;
  109482. if (value) {
  109483. this._onBeforeCameraRenderObserver = this.scene.onBeforeCameraRenderObservable.add(function (camera) {
  109484. _this._cameraRenderTime.beginMonitoring();
  109485. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + camera.name);
  109486. });
  109487. this._onAfterCameraRenderObserver = this.scene.onAfterCameraRenderObservable.add(function (camera) {
  109488. _this._cameraRenderTime.endMonitoring(false);
  109489. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + camera.name);
  109490. });
  109491. }
  109492. else {
  109493. this.scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  109494. this._onBeforeCameraRenderObserver = null;
  109495. this.scene.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  109496. this._onAfterCameraRenderObserver = null;
  109497. }
  109498. },
  109499. enumerable: true,
  109500. configurable: true
  109501. });
  109502. Object.defineProperty(SceneInstrumentation.prototype, "drawCallsCounter", {
  109503. /**
  109504. * Gets the perf counter used for draw calls
  109505. */
  109506. get: function () {
  109507. return this.scene.getEngine()._drawCalls;
  109508. },
  109509. enumerable: true,
  109510. configurable: true
  109511. });
  109512. Object.defineProperty(SceneInstrumentation.prototype, "textureCollisionsCounter", {
  109513. /**
  109514. * Gets the perf counter used for texture collisions
  109515. */
  109516. get: function () {
  109517. return this.scene.getEngine()._textureCollisions;
  109518. },
  109519. enumerable: true,
  109520. configurable: true
  109521. });
  109522. SceneInstrumentation.prototype.dispose = function () {
  109523. this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  109524. this._onAfterRenderObserver = null;
  109525. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  109526. this._onBeforeActiveMeshesEvaluationObserver = null;
  109527. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  109528. this._onAfterActiveMeshesEvaluationObserver = null;
  109529. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  109530. this._onBeforeRenderTargetsRenderObserver = null;
  109531. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  109532. this._onAfterRenderTargetsRenderObserver = null;
  109533. this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver);
  109534. this._onBeforeAnimationsObserver = null;
  109535. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  109536. this._onBeforeParticlesRenderingObserver = null;
  109537. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  109538. this._onAfterParticlesRenderingObserver = null;
  109539. if (this._onBeforeSpritesRenderingObserver) {
  109540. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  109541. this._onBeforeSpritesRenderingObserver = null;
  109542. }
  109543. if (this._onAfterSpritesRenderingObserver) {
  109544. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  109545. this._onAfterSpritesRenderingObserver = null;
  109546. }
  109547. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  109548. this._onBeforeDrawPhaseObserver = null;
  109549. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  109550. this._onAfterDrawPhaseObserver = null;
  109551. if (this._onBeforePhysicsObserver) {
  109552. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  109553. this._onBeforePhysicsObserver = null;
  109554. }
  109555. if (this._onAfterPhysicsObserver) {
  109556. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  109557. this._onAfterPhysicsObserver = null;
  109558. }
  109559. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  109560. this._onAfterAnimationsObserver = null;
  109561. this.scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  109562. this._onBeforeCameraRenderObserver = null;
  109563. this.scene.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  109564. this._onAfterCameraRenderObserver = null;
  109565. this.scene = null;
  109566. };
  109567. return SceneInstrumentation;
  109568. }());
  109569. BABYLON.SceneInstrumentation = SceneInstrumentation;
  109570. })(BABYLON || (BABYLON = {}));
  109571. //# sourceMappingURL=babylon.sceneInstrumentation.js.map
  109572. var BABYLON;
  109573. (function (BABYLON) {
  109574. /**
  109575. * @hidden
  109576. **/
  109577. var _TimeToken = /** @class */ (function () {
  109578. function _TimeToken() {
  109579. this._timeElapsedQueryEnded = false;
  109580. }
  109581. return _TimeToken;
  109582. }());
  109583. BABYLON._TimeToken = _TimeToken;
  109584. })(BABYLON || (BABYLON = {}));
  109585. //# sourceMappingURL=babylon.timeToken.js.map
  109586. var BABYLON;
  109587. (function (BABYLON) {
  109588. /**
  109589. * Background material defines definition.
  109590. * @hidden Mainly internal Use
  109591. */
  109592. var BackgroundMaterialDefines = /** @class */ (function (_super) {
  109593. __extends(BackgroundMaterialDefines, _super);
  109594. /**
  109595. * Constructor of the defines.
  109596. */
  109597. function BackgroundMaterialDefines() {
  109598. var _this = _super.call(this) || this;
  109599. /**
  109600. * True if the diffuse texture is in use.
  109601. */
  109602. _this.DIFFUSE = false;
  109603. /**
  109604. * The direct UV channel to use.
  109605. */
  109606. _this.DIFFUSEDIRECTUV = 0;
  109607. /**
  109608. * True if the diffuse texture is in gamma space.
  109609. */
  109610. _this.GAMMADIFFUSE = false;
  109611. /**
  109612. * True if the diffuse texture has opacity in the alpha channel.
  109613. */
  109614. _this.DIFFUSEHASALPHA = false;
  109615. /**
  109616. * True if you want the material to fade to transparent at grazing angle.
  109617. */
  109618. _this.OPACITYFRESNEL = false;
  109619. /**
  109620. * True if an extra blur needs to be added in the reflection.
  109621. */
  109622. _this.REFLECTIONBLUR = false;
  109623. /**
  109624. * True if you want the material to fade to reflection at grazing angle.
  109625. */
  109626. _this.REFLECTIONFRESNEL = false;
  109627. /**
  109628. * True if you want the material to falloff as far as you move away from the scene center.
  109629. */
  109630. _this.REFLECTIONFALLOFF = false;
  109631. /**
  109632. * False if the current Webgl implementation does not support the texture lod extension.
  109633. */
  109634. _this.TEXTURELODSUPPORT = false;
  109635. /**
  109636. * True to ensure the data are premultiplied.
  109637. */
  109638. _this.PREMULTIPLYALPHA = false;
  109639. /**
  109640. * True if the texture contains cooked RGB values and not gray scaled multipliers.
  109641. */
  109642. _this.USERGBCOLOR = false;
  109643. /**
  109644. * True if highlight and shadow levels have been specified. It can help ensuring the main perceived color
  109645. * stays aligned with the desired configuration.
  109646. */
  109647. _this.USEHIGHLIGHTANDSHADOWCOLORS = false;
  109648. /**
  109649. * True to add noise in order to reduce the banding effect.
  109650. */
  109651. _this.NOISE = false;
  109652. /**
  109653. * is the reflection texture in BGR color scheme?
  109654. * Mainly used to solve a bug in ios10 video tag
  109655. */
  109656. _this.REFLECTIONBGR = false;
  109657. _this.IMAGEPROCESSING = false;
  109658. _this.VIGNETTE = false;
  109659. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  109660. _this.VIGNETTEBLENDMODEOPAQUE = false;
  109661. _this.TONEMAPPING = false;
  109662. _this.TONEMAPPING_ACES = false;
  109663. _this.CONTRAST = false;
  109664. _this.COLORCURVES = false;
  109665. _this.COLORGRADING = false;
  109666. _this.COLORGRADING3D = false;
  109667. _this.SAMPLER3DGREENDEPTH = false;
  109668. _this.SAMPLER3DBGRMAP = false;
  109669. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  109670. _this.EXPOSURE = false;
  109671. // Reflection.
  109672. _this.REFLECTION = false;
  109673. _this.REFLECTIONMAP_3D = false;
  109674. _this.REFLECTIONMAP_SPHERICAL = false;
  109675. _this.REFLECTIONMAP_PLANAR = false;
  109676. _this.REFLECTIONMAP_CUBIC = false;
  109677. _this.REFLECTIONMAP_PROJECTION = false;
  109678. _this.REFLECTIONMAP_SKYBOX = false;
  109679. _this.REFLECTIONMAP_SKYBOX_TRANSFORMED = false;
  109680. _this.REFLECTIONMAP_EXPLICIT = false;
  109681. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  109682. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  109683. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  109684. _this.INVERTCUBICMAP = false;
  109685. _this.REFLECTIONMAP_OPPOSITEZ = false;
  109686. _this.LODINREFLECTIONALPHA = false;
  109687. _this.GAMMAREFLECTION = false;
  109688. _this.RGBDREFLECTION = false;
  109689. _this.EQUIRECTANGULAR_RELFECTION_FOV = false;
  109690. // Default BJS.
  109691. _this.MAINUV1 = false;
  109692. _this.MAINUV2 = false;
  109693. _this.UV1 = false;
  109694. _this.UV2 = false;
  109695. _this.CLIPPLANE = false;
  109696. _this.CLIPPLANE2 = false;
  109697. _this.CLIPPLANE3 = false;
  109698. _this.CLIPPLANE4 = false;
  109699. _this.POINTSIZE = false;
  109700. _this.FOG = false;
  109701. _this.NORMAL = false;
  109702. _this.NUM_BONE_INFLUENCERS = 0;
  109703. _this.BonesPerMesh = 0;
  109704. _this.INSTANCES = false;
  109705. _this.SHADOWFLOAT = false;
  109706. _this.rebuild();
  109707. return _this;
  109708. }
  109709. return BackgroundMaterialDefines;
  109710. }(BABYLON.MaterialDefines));
  109711. /**
  109712. * Background material used to create an efficient environement around your scene.
  109713. */
  109714. var BackgroundMaterial = /** @class */ (function (_super) {
  109715. __extends(BackgroundMaterial, _super);
  109716. /**
  109717. * Instantiates a Background Material in the given scene
  109718. * @param name The friendly name of the material
  109719. * @param scene The scene to add the material to
  109720. */
  109721. function BackgroundMaterial(name, scene) {
  109722. var _this = _super.call(this, name, scene) || this;
  109723. /**
  109724. * Key light Color (multiply against the environement texture)
  109725. */
  109726. _this.primaryColor = BABYLON.Color3.White();
  109727. _this._primaryColorShadowLevel = 0;
  109728. _this._primaryColorHighlightLevel = 0;
  109729. /**
  109730. * Reflection Texture used in the material.
  109731. * Should be author in a specific way for the best result (refer to the documentation).
  109732. */
  109733. _this.reflectionTexture = null;
  109734. /**
  109735. * Reflection Texture level of blur.
  109736. *
  109737. * Can be use to reuse an existing HDR Texture and target a specific LOD to prevent authoring the
  109738. * texture twice.
  109739. */
  109740. _this.reflectionBlur = 0;
  109741. /**
  109742. * Diffuse Texture used in the material.
  109743. * Should be author in a specific way for the best result (refer to the documentation).
  109744. */
  109745. _this.diffuseTexture = null;
  109746. _this._shadowLights = null;
  109747. /**
  109748. * Specify the list of lights casting shadow on the material.
  109749. * All scene shadow lights will be included if null.
  109750. */
  109751. _this.shadowLights = null;
  109752. /**
  109753. * Helps adjusting the shadow to a softer level if required.
  109754. * 0 means black shadows and 1 means no shadows.
  109755. */
  109756. _this.shadowLevel = 0;
  109757. /**
  109758. * In case of opacity Fresnel or reflection falloff, this is use as a scene center.
  109759. * It is usually zero but might be interesting to modify according to your setup.
  109760. */
  109761. _this.sceneCenter = BABYLON.Vector3.Zero();
  109762. /**
  109763. * This helps specifying that the material is falling off to the sky box at grazing angle.
  109764. * This helps ensuring a nice transition when the camera goes under the ground.
  109765. */
  109766. _this.opacityFresnel = true;
  109767. /**
  109768. * This helps specifying that the material is falling off from diffuse to the reflection texture at grazing angle.
  109769. * This helps adding a mirror texture on the ground.
  109770. */
  109771. _this.reflectionFresnel = false;
  109772. /**
  109773. * This helps specifying the falloff radius off the reflection texture from the sceneCenter.
  109774. * This helps adding a nice falloff effect to the reflection if used as a mirror for instance.
  109775. */
  109776. _this.reflectionFalloffDistance = 0.0;
  109777. /**
  109778. * This specifies the weight of the reflection against the background in case of reflection Fresnel.
  109779. */
  109780. _this.reflectionAmount = 1.0;
  109781. /**
  109782. * This specifies the weight of the reflection at grazing angle.
  109783. */
  109784. _this.reflectionReflectance0 = 0.05;
  109785. /**
  109786. * This specifies the weight of the reflection at a perpendicular point of view.
  109787. */
  109788. _this.reflectionReflectance90 = 0.5;
  109789. /**
  109790. * Helps to directly use the maps channels instead of their level.
  109791. */
  109792. _this.useRGBColor = true;
  109793. /**
  109794. * This helps reducing the banding effect that could occur on the background.
  109795. */
  109796. _this.enableNoise = false;
  109797. _this._fovMultiplier = 1.0;
  109798. /**
  109799. * Enable the FOV adjustment feature controlled by fovMultiplier.
  109800. */
  109801. _this.useEquirectangularFOV = false;
  109802. _this._maxSimultaneousLights = 4;
  109803. /**
  109804. * Number of Simultaneous lights allowed on the material.
  109805. */
  109806. _this.maxSimultaneousLights = 4;
  109807. /**
  109808. * Keep track of the image processing observer to allow dispose and replace.
  109809. */
  109810. _this._imageProcessingObserver = null;
  109811. /**
  109812. * Due to a bug in iOS10, video tags (which are using the background material) are in BGR and not RGB.
  109813. * Setting this flag to true (not done automatically!) will convert it back to RGB.
  109814. */
  109815. _this.switchToBGR = false;
  109816. // Temp values kept as cache in the material.
  109817. _this._renderTargets = new BABYLON.SmartArray(16);
  109818. _this._reflectionControls = BABYLON.Vector4.Zero();
  109819. _this._white = BABYLON.Color3.White();
  109820. _this._primaryShadowColor = BABYLON.Color3.Black();
  109821. _this._primaryHighlightColor = BABYLON.Color3.Black();
  109822. // Setup the default processing configuration to the scene.
  109823. _this._attachImageProcessingConfiguration(null);
  109824. _this.getRenderTargetTextures = function () {
  109825. _this._renderTargets.reset();
  109826. if (_this._diffuseTexture && _this._diffuseTexture.isRenderTarget) {
  109827. _this._renderTargets.push(_this._diffuseTexture);
  109828. }
  109829. if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  109830. _this._renderTargets.push(_this._reflectionTexture);
  109831. }
  109832. return _this._renderTargets;
  109833. };
  109834. return _this;
  109835. }
  109836. Object.defineProperty(BackgroundMaterial.prototype, "_perceptualColor", {
  109837. /**
  109838. * Experimental Internal Use Only.
  109839. *
  109840. * Key light Color in "perceptual value" meaning the color you would like to see on screen.
  109841. * This acts as a helper to set the primary color to a more "human friendly" value.
  109842. * Conversion to linear space as well as exposure and tone mapping correction will be applied to keep the
  109843. * output color as close as possible from the chosen value.
  109844. * (This does not account for contrast color grading and color curves as they are considered post effect and not directly
  109845. * part of lighting setup.)
  109846. */
  109847. get: function () {
  109848. return this.__perceptualColor;
  109849. },
  109850. set: function (value) {
  109851. this.__perceptualColor = value;
  109852. this._computePrimaryColorFromPerceptualColor();
  109853. this._markAllSubMeshesAsLightsDirty();
  109854. },
  109855. enumerable: true,
  109856. configurable: true
  109857. });
  109858. Object.defineProperty(BackgroundMaterial.prototype, "primaryColorShadowLevel", {
  109859. /**
  109860. * Defines the level of the shadows (dark area of the reflection map) in order to help scaling the colors.
  109861. * The color opposite to the primary color is used at the level chosen to define what the black area would look.
  109862. */
  109863. get: function () {
  109864. return this._primaryColorShadowLevel;
  109865. },
  109866. set: function (value) {
  109867. this._primaryColorShadowLevel = value;
  109868. this._computePrimaryColors();
  109869. this._markAllSubMeshesAsLightsDirty();
  109870. },
  109871. enumerable: true,
  109872. configurable: true
  109873. });
  109874. Object.defineProperty(BackgroundMaterial.prototype, "primaryColorHighlightLevel", {
  109875. /**
  109876. * Defines the level of the highliights (highlight area of the reflection map) in order to help scaling the colors.
  109877. * The primary color is used at the level chosen to define what the white area would look.
  109878. */
  109879. get: function () {
  109880. return this._primaryColorHighlightLevel;
  109881. },
  109882. set: function (value) {
  109883. this._primaryColorHighlightLevel = value;
  109884. this._computePrimaryColors();
  109885. this._markAllSubMeshesAsLightsDirty();
  109886. },
  109887. enumerable: true,
  109888. configurable: true
  109889. });
  109890. Object.defineProperty(BackgroundMaterial.prototype, "reflectionStandardFresnelWeight", {
  109891. /**
  109892. * Sets the reflection reflectance fresnel values according to the default standard
  109893. * empirically know to work well :-)
  109894. */
  109895. set: function (value) {
  109896. var reflectionWeight = value;
  109897. if (reflectionWeight < 0.5) {
  109898. reflectionWeight = reflectionWeight * 2.0;
  109899. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 * reflectionWeight;
  109900. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 * reflectionWeight;
  109901. }
  109902. else {
  109903. reflectionWeight = reflectionWeight * 2.0 - 1.0;
  109904. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 + (1.0 - BackgroundMaterial.StandardReflectance0) * reflectionWeight;
  109905. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 + (1.0 - BackgroundMaterial.StandardReflectance90) * reflectionWeight;
  109906. }
  109907. },
  109908. enumerable: true,
  109909. configurable: true
  109910. });
  109911. Object.defineProperty(BackgroundMaterial.prototype, "fovMultiplier", {
  109912. /**
  109913. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  109914. * Best used when trying to implement visual zoom effects like fish-eye or binoculars while not adjusting camera fov.
  109915. * Recommended to be keep at 1.0 except for special cases.
  109916. */
  109917. get: function () {
  109918. return this._fovMultiplier;
  109919. },
  109920. set: function (value) {
  109921. if (isNaN(value)) {
  109922. value = 1.0;
  109923. }
  109924. this._fovMultiplier = Math.max(0.0, Math.min(2.0, value));
  109925. },
  109926. enumerable: true,
  109927. configurable: true
  109928. });
  109929. /**
  109930. * Attaches a new image processing configuration to the PBR Material.
  109931. * @param configuration (if null the scene configuration will be use)
  109932. */
  109933. BackgroundMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  109934. var _this = this;
  109935. if (configuration === this._imageProcessingConfiguration) {
  109936. return;
  109937. }
  109938. // Detaches observer.
  109939. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  109940. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  109941. }
  109942. // Pick the scene configuration if needed.
  109943. if (!configuration) {
  109944. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  109945. }
  109946. else {
  109947. this._imageProcessingConfiguration = configuration;
  109948. }
  109949. // Attaches observer.
  109950. if (this._imageProcessingConfiguration) {
  109951. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  109952. _this._computePrimaryColorFromPerceptualColor();
  109953. _this._markAllSubMeshesAsImageProcessingDirty();
  109954. });
  109955. }
  109956. };
  109957. Object.defineProperty(BackgroundMaterial.prototype, "imageProcessingConfiguration", {
  109958. /**
  109959. * Gets the image processing configuration used either in this material.
  109960. */
  109961. get: function () {
  109962. return this._imageProcessingConfiguration;
  109963. },
  109964. /**
  109965. * Sets the Default image processing configuration used either in the this material.
  109966. *
  109967. * If sets to null, the scene one is in use.
  109968. */
  109969. set: function (value) {
  109970. this._attachImageProcessingConfiguration(value);
  109971. // Ensure the effect will be rebuilt.
  109972. this._markAllSubMeshesAsTexturesDirty();
  109973. },
  109974. enumerable: true,
  109975. configurable: true
  109976. });
  109977. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurvesEnabled", {
  109978. /**
  109979. * Gets wether the color curves effect is enabled.
  109980. */
  109981. get: function () {
  109982. return this.imageProcessingConfiguration.colorCurvesEnabled;
  109983. },
  109984. /**
  109985. * Sets wether the color curves effect is enabled.
  109986. */
  109987. set: function (value) {
  109988. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  109989. },
  109990. enumerable: true,
  109991. configurable: true
  109992. });
  109993. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingEnabled", {
  109994. /**
  109995. * Gets wether the color grading effect is enabled.
  109996. */
  109997. get: function () {
  109998. return this.imageProcessingConfiguration.colorGradingEnabled;
  109999. },
  110000. /**
  110001. * Gets wether the color grading effect is enabled.
  110002. */
  110003. set: function (value) {
  110004. this.imageProcessingConfiguration.colorGradingEnabled = value;
  110005. },
  110006. enumerable: true,
  110007. configurable: true
  110008. });
  110009. Object.defineProperty(BackgroundMaterial.prototype, "cameraToneMappingEnabled", {
  110010. /**
  110011. * Gets wether tonemapping is enabled or not.
  110012. */
  110013. get: function () {
  110014. return this._imageProcessingConfiguration.toneMappingEnabled;
  110015. },
  110016. /**
  110017. * Sets wether tonemapping is enabled or not
  110018. */
  110019. set: function (value) {
  110020. this._imageProcessingConfiguration.toneMappingEnabled = value;
  110021. },
  110022. enumerable: true,
  110023. configurable: true
  110024. });
  110025. ;
  110026. ;
  110027. Object.defineProperty(BackgroundMaterial.prototype, "cameraExposure", {
  110028. /**
  110029. * The camera exposure used on this material.
  110030. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  110031. * This corresponds to a photographic exposure.
  110032. */
  110033. get: function () {
  110034. return this._imageProcessingConfiguration.exposure;
  110035. },
  110036. /**
  110037. * The camera exposure used on this material.
  110038. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  110039. * This corresponds to a photographic exposure.
  110040. */
  110041. set: function (value) {
  110042. this._imageProcessingConfiguration.exposure = value;
  110043. },
  110044. enumerable: true,
  110045. configurable: true
  110046. });
  110047. ;
  110048. ;
  110049. Object.defineProperty(BackgroundMaterial.prototype, "cameraContrast", {
  110050. /**
  110051. * Gets The camera contrast used on this material.
  110052. */
  110053. get: function () {
  110054. return this._imageProcessingConfiguration.contrast;
  110055. },
  110056. /**
  110057. * Sets The camera contrast used on this material.
  110058. */
  110059. set: function (value) {
  110060. this._imageProcessingConfiguration.contrast = value;
  110061. },
  110062. enumerable: true,
  110063. configurable: true
  110064. });
  110065. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingTexture", {
  110066. /**
  110067. * Gets the Color Grading 2D Lookup Texture.
  110068. */
  110069. get: function () {
  110070. return this._imageProcessingConfiguration.colorGradingTexture;
  110071. },
  110072. /**
  110073. * Sets the Color Grading 2D Lookup Texture.
  110074. */
  110075. set: function (value) {
  110076. this.imageProcessingConfiguration.colorGradingTexture = value;
  110077. },
  110078. enumerable: true,
  110079. configurable: true
  110080. });
  110081. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurves", {
  110082. /**
  110083. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  110084. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  110085. * 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;
  110086. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  110087. */
  110088. get: function () {
  110089. return this.imageProcessingConfiguration.colorCurves;
  110090. },
  110091. /**
  110092. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  110093. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  110094. * 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;
  110095. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  110096. */
  110097. set: function (value) {
  110098. this.imageProcessingConfiguration.colorCurves = value;
  110099. },
  110100. enumerable: true,
  110101. configurable: true
  110102. });
  110103. Object.defineProperty(BackgroundMaterial.prototype, "hasRenderTargetTextures", {
  110104. /**
  110105. * Gets a boolean indicating that current material needs to register RTT
  110106. */
  110107. get: function () {
  110108. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  110109. return true;
  110110. }
  110111. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  110112. return true;
  110113. }
  110114. return false;
  110115. },
  110116. enumerable: true,
  110117. configurable: true
  110118. });
  110119. /**
  110120. * The entire material has been created in order to prevent overdraw.
  110121. * @returns false
  110122. */
  110123. BackgroundMaterial.prototype.needAlphaTesting = function () {
  110124. return true;
  110125. };
  110126. /**
  110127. * The entire material has been created in order to prevent overdraw.
  110128. * @returns true if blending is enable
  110129. */
  110130. BackgroundMaterial.prototype.needAlphaBlending = function () {
  110131. return ((this.alpha < 0) || (this._diffuseTexture != null && this._diffuseTexture.hasAlpha));
  110132. };
  110133. /**
  110134. * Checks wether the material is ready to be rendered for a given mesh.
  110135. * @param mesh The mesh to render
  110136. * @param subMesh The submesh to check against
  110137. * @param useInstances Specify wether or not the material is used with instances
  110138. * @returns true if all the dependencies are ready (Textures, Effects...)
  110139. */
  110140. BackgroundMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  110141. var _this = this;
  110142. if (useInstances === void 0) { useInstances = false; }
  110143. if (subMesh.effect && this.isFrozen) {
  110144. if (this._wasPreviouslyReady) {
  110145. return true;
  110146. }
  110147. }
  110148. if (!subMesh._materialDefines) {
  110149. subMesh._materialDefines = new BackgroundMaterialDefines();
  110150. }
  110151. var scene = this.getScene();
  110152. var defines = subMesh._materialDefines;
  110153. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  110154. if (defines._renderId === scene.getRenderId()) {
  110155. return true;
  110156. }
  110157. }
  110158. var engine = scene.getEngine();
  110159. // Lights
  110160. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights);
  110161. defines._needNormals = true;
  110162. // Textures
  110163. if (defines._areTexturesDirty) {
  110164. defines._needUVs = false;
  110165. if (scene.texturesEnabled) {
  110166. if (scene.getEngine().getCaps().textureLOD) {
  110167. defines.TEXTURELODSUPPORT = true;
  110168. }
  110169. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  110170. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  110171. return false;
  110172. }
  110173. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  110174. defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha;
  110175. defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace;
  110176. defines.OPACITYFRESNEL = this._opacityFresnel;
  110177. }
  110178. else {
  110179. defines.DIFFUSE = false;
  110180. defines.DIFFUSEHASALPHA = false;
  110181. defines.GAMMADIFFUSE = false;
  110182. defines.OPACITYFRESNEL = false;
  110183. }
  110184. var reflectionTexture = this._reflectionTexture;
  110185. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  110186. if (!reflectionTexture.isReadyOrNotBlocking()) {
  110187. return false;
  110188. }
  110189. defines.REFLECTION = true;
  110190. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  110191. defines.RGBDREFLECTION = reflectionTexture.isRGBD;
  110192. defines.REFLECTIONBLUR = this._reflectionBlur > 0;
  110193. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  110194. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  110195. defines.EQUIRECTANGULAR_RELFECTION_FOV = this.useEquirectangularFOV;
  110196. defines.REFLECTIONBGR = this.switchToBGR;
  110197. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  110198. defines.INVERTCUBICMAP = true;
  110199. }
  110200. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  110201. switch (reflectionTexture.coordinatesMode) {
  110202. case BABYLON.Texture.EXPLICIT_MODE:
  110203. defines.REFLECTIONMAP_EXPLICIT = true;
  110204. break;
  110205. case BABYLON.Texture.PLANAR_MODE:
  110206. defines.REFLECTIONMAP_PLANAR = true;
  110207. break;
  110208. case BABYLON.Texture.PROJECTION_MODE:
  110209. defines.REFLECTIONMAP_PROJECTION = true;
  110210. break;
  110211. case BABYLON.Texture.SKYBOX_MODE:
  110212. defines.REFLECTIONMAP_SKYBOX = true;
  110213. defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = !reflectionTexture.getReflectionTextureMatrix().isIdentity();
  110214. break;
  110215. case BABYLON.Texture.SPHERICAL_MODE:
  110216. defines.REFLECTIONMAP_SPHERICAL = true;
  110217. break;
  110218. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  110219. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  110220. break;
  110221. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  110222. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  110223. break;
  110224. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  110225. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  110226. break;
  110227. case BABYLON.Texture.CUBIC_MODE:
  110228. case BABYLON.Texture.INVCUBIC_MODE:
  110229. default:
  110230. defines.REFLECTIONMAP_CUBIC = true;
  110231. break;
  110232. }
  110233. if (this.reflectionFresnel) {
  110234. defines.REFLECTIONFRESNEL = true;
  110235. defines.REFLECTIONFALLOFF = this.reflectionFalloffDistance > 0;
  110236. this._reflectionControls.x = this.reflectionAmount;
  110237. this._reflectionControls.y = this.reflectionReflectance0;
  110238. this._reflectionControls.z = this.reflectionReflectance90;
  110239. this._reflectionControls.w = 1 / this.reflectionFalloffDistance;
  110240. }
  110241. else {
  110242. defines.REFLECTIONFRESNEL = false;
  110243. defines.REFLECTIONFALLOFF = false;
  110244. }
  110245. }
  110246. else {
  110247. defines.REFLECTION = false;
  110248. defines.REFLECTIONFRESNEL = false;
  110249. defines.REFLECTIONFALLOFF = false;
  110250. defines.REFLECTIONBLUR = false;
  110251. defines.REFLECTIONMAP_3D = false;
  110252. defines.REFLECTIONMAP_SPHERICAL = false;
  110253. defines.REFLECTIONMAP_PLANAR = false;
  110254. defines.REFLECTIONMAP_CUBIC = false;
  110255. defines.REFLECTIONMAP_PROJECTION = false;
  110256. defines.REFLECTIONMAP_SKYBOX = false;
  110257. defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = false;
  110258. defines.REFLECTIONMAP_EXPLICIT = false;
  110259. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  110260. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  110261. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  110262. defines.INVERTCUBICMAP = false;
  110263. defines.REFLECTIONMAP_OPPOSITEZ = false;
  110264. defines.LODINREFLECTIONALPHA = false;
  110265. defines.GAMMAREFLECTION = false;
  110266. defines.RGBDREFLECTION = false;
  110267. }
  110268. }
  110269. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  110270. defines.USERGBCOLOR = this._useRGBColor;
  110271. defines.NOISE = this._enableNoise;
  110272. }
  110273. if (defines._areLightsDirty) {
  110274. defines.USEHIGHLIGHTANDSHADOWCOLORS = !this._useRGBColor && (this._primaryColorShadowLevel !== 0 || this._primaryColorHighlightLevel !== 0);
  110275. }
  110276. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  110277. if (!this._imageProcessingConfiguration.isReady()) {
  110278. return false;
  110279. }
  110280. this._imageProcessingConfiguration.prepareDefines(defines);
  110281. }
  110282. // Misc.
  110283. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  110284. // Values that need to be evaluated on every frame
  110285. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  110286. // Attribs
  110287. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, false, true, false)) {
  110288. if (mesh) {
  110289. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  110290. mesh.createNormals(true);
  110291. BABYLON.Tools.Warn("BackgroundMaterial: Normals have been created for the mesh: " + mesh.name);
  110292. }
  110293. }
  110294. }
  110295. // Get correct effect
  110296. if (defines.isDirty) {
  110297. defines.markAsProcessed();
  110298. scene.resetCachedMaterial();
  110299. // Fallbacks
  110300. var fallbacks = new BABYLON.EffectFallbacks();
  110301. if (defines.FOG) {
  110302. fallbacks.addFallback(0, "FOG");
  110303. }
  110304. if (defines.POINTSIZE) {
  110305. fallbacks.addFallback(1, "POINTSIZE");
  110306. }
  110307. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  110308. if (defines.NUM_BONE_INFLUENCERS > 0) {
  110309. fallbacks.addCPUSkinningFallback(0, mesh);
  110310. }
  110311. //Attributes
  110312. var attribs = [BABYLON.VertexBuffer.PositionKind];
  110313. if (defines.NORMAL) {
  110314. attribs.push(BABYLON.VertexBuffer.NormalKind);
  110315. }
  110316. if (defines.UV1) {
  110317. attribs.push(BABYLON.VertexBuffer.UVKind);
  110318. }
  110319. if (defines.UV2) {
  110320. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  110321. }
  110322. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  110323. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  110324. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType",
  110325. "vFogInfos", "vFogColor", "pointSize",
  110326. "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "mBones",
  110327. "vPrimaryColor", "vPrimaryColorShadow",
  110328. "vReflectionInfos", "reflectionMatrix", "vReflectionMicrosurfaceInfos", "fFovMultiplier",
  110329. "shadowLevel", "alpha",
  110330. "vBackgroundCenter", "vReflectionControl",
  110331. "vDiffuseInfos", "diffuseMatrix",
  110332. ];
  110333. var samplers = ["diffuseSampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh"];
  110334. var uniformBuffers = ["Material", "Scene"];
  110335. if (BABYLON.ImageProcessingConfiguration) {
  110336. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  110337. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  110338. }
  110339. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  110340. uniformsNames: uniforms,
  110341. uniformBuffersNames: uniformBuffers,
  110342. samplers: samplers,
  110343. defines: defines,
  110344. maxSimultaneousLights: this._maxSimultaneousLights
  110345. });
  110346. var onCompiled = function (effect) {
  110347. if (_this.onCompiled) {
  110348. _this.onCompiled(effect);
  110349. }
  110350. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  110351. };
  110352. var join = defines.toString();
  110353. subMesh.setEffect(scene.getEngine().createEffect("background", {
  110354. attributes: attribs,
  110355. uniformsNames: uniforms,
  110356. uniformBuffersNames: uniformBuffers,
  110357. samplers: samplers,
  110358. defines: join,
  110359. fallbacks: fallbacks,
  110360. onCompiled: onCompiled,
  110361. onError: this.onError,
  110362. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights }
  110363. }, engine), defines);
  110364. this.buildUniformLayout();
  110365. }
  110366. if (!subMesh.effect || !subMesh.effect.isReady()) {
  110367. return false;
  110368. }
  110369. defines._renderId = scene.getRenderId();
  110370. this._wasPreviouslyReady = true;
  110371. return true;
  110372. };
  110373. /**
  110374. * Compute the primary color according to the chosen perceptual color.
  110375. */
  110376. BackgroundMaterial.prototype._computePrimaryColorFromPerceptualColor = function () {
  110377. if (!this.__perceptualColor) {
  110378. return;
  110379. }
  110380. this._primaryColor.copyFrom(this.__perceptualColor);
  110381. // Revert gamma space.
  110382. this._primaryColor.toLinearSpaceToRef(this._primaryColor);
  110383. // Revert image processing configuration.
  110384. if (this._imageProcessingConfiguration) {
  110385. // Revert Exposure.
  110386. this._primaryColor.scaleToRef(1 / this._imageProcessingConfiguration.exposure, this._primaryColor);
  110387. }
  110388. this._computePrimaryColors();
  110389. };
  110390. /**
  110391. * Compute the highlights and shadow colors according to their chosen levels.
  110392. */
  110393. BackgroundMaterial.prototype._computePrimaryColors = function () {
  110394. if (this._primaryColorShadowLevel === 0 && this._primaryColorHighlightLevel === 0) {
  110395. return;
  110396. }
  110397. // Find the highlight color based on the configuration.
  110398. this._primaryColor.scaleToRef(this._primaryColorShadowLevel, this._primaryShadowColor);
  110399. this._primaryColor.subtractToRef(this._primaryShadowColor, this._primaryShadowColor);
  110400. // Find the shadow color based on the configuration.
  110401. this._white.subtractToRef(this._primaryColor, this._primaryHighlightColor);
  110402. this._primaryHighlightColor.scaleToRef(this._primaryColorHighlightLevel, this._primaryHighlightColor);
  110403. this._primaryColor.addToRef(this._primaryHighlightColor, this._primaryHighlightColor);
  110404. };
  110405. /**
  110406. * Build the uniform buffer used in the material.
  110407. */
  110408. BackgroundMaterial.prototype.buildUniformLayout = function () {
  110409. // Order is important !
  110410. this._uniformBuffer.addUniform("vPrimaryColor", 4);
  110411. this._uniformBuffer.addUniform("vPrimaryColorShadow", 4);
  110412. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  110413. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  110414. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  110415. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  110416. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  110417. this._uniformBuffer.addUniform("fFovMultiplier", 1);
  110418. this._uniformBuffer.addUniform("pointSize", 1);
  110419. this._uniformBuffer.addUniform("shadowLevel", 1);
  110420. this._uniformBuffer.addUniform("alpha", 1);
  110421. this._uniformBuffer.addUniform("vBackgroundCenter", 3);
  110422. this._uniformBuffer.addUniform("vReflectionControl", 4);
  110423. this._uniformBuffer.create();
  110424. };
  110425. /**
  110426. * Unbind the material.
  110427. */
  110428. BackgroundMaterial.prototype.unbind = function () {
  110429. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  110430. this._uniformBuffer.setTexture("diffuseSampler", null);
  110431. }
  110432. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  110433. this._uniformBuffer.setTexture("reflectionSampler", null);
  110434. }
  110435. _super.prototype.unbind.call(this);
  110436. };
  110437. /**
  110438. * Bind only the world matrix to the material.
  110439. * @param world The world matrix to bind.
  110440. */
  110441. BackgroundMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  110442. this._activeEffect.setMatrix("world", world);
  110443. };
  110444. /**
  110445. * Bind the material for a dedicated submeh (every used meshes will be considered opaque).
  110446. * @param world The world matrix to bind.
  110447. * @param subMesh The submesh to bind for.
  110448. */
  110449. BackgroundMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  110450. var scene = this.getScene();
  110451. var defines = subMesh._materialDefines;
  110452. if (!defines) {
  110453. return;
  110454. }
  110455. var effect = subMesh.effect;
  110456. if (!effect) {
  110457. return;
  110458. }
  110459. this._activeEffect = effect;
  110460. // Matrices
  110461. this.bindOnlyWorldMatrix(world);
  110462. // Bones
  110463. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  110464. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  110465. if (mustRebind) {
  110466. this._uniformBuffer.bindToEffect(effect, "Material");
  110467. this.bindViewProjection(effect);
  110468. var reflectionTexture = this._reflectionTexture;
  110469. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  110470. // Texture uniforms
  110471. if (scene.texturesEnabled) {
  110472. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  110473. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  110474. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  110475. }
  110476. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  110477. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  110478. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, this._reflectionBlur);
  110479. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  110480. }
  110481. }
  110482. if (this.shadowLevel > 0) {
  110483. this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel);
  110484. }
  110485. this._uniformBuffer.updateFloat("alpha", this.alpha);
  110486. // Point size
  110487. if (this.pointsCloud) {
  110488. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  110489. }
  110490. if (defines.USEHIGHLIGHTANDSHADOWCOLORS) {
  110491. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryHighlightColor, 1.0);
  110492. this._uniformBuffer.updateColor4("vPrimaryColorShadow", this._primaryShadowColor, 1.0);
  110493. }
  110494. else {
  110495. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryColor, 1.0);
  110496. }
  110497. }
  110498. this._uniformBuffer.updateFloat("fFovMultiplier", this._fovMultiplier);
  110499. // Textures
  110500. if (scene.texturesEnabled) {
  110501. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  110502. this._uniformBuffer.setTexture("diffuseSampler", this._diffuseTexture);
  110503. }
  110504. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  110505. if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) {
  110506. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  110507. }
  110508. else if (!defines.REFLECTIONBLUR) {
  110509. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  110510. }
  110511. else {
  110512. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  110513. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  110514. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  110515. }
  110516. if (defines.REFLECTIONFRESNEL) {
  110517. this._uniformBuffer.updateFloat3("vBackgroundCenter", this.sceneCenter.x, this.sceneCenter.y, this.sceneCenter.z);
  110518. this._uniformBuffer.updateFloat4("vReflectionControl", this._reflectionControls.x, this._reflectionControls.y, this._reflectionControls.z, this._reflectionControls.w);
  110519. }
  110520. }
  110521. }
  110522. // Clip plane
  110523. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  110524. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  110525. }
  110526. if (mustRebind || !this.isFrozen) {
  110527. if (scene.lightsEnabled) {
  110528. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, false);
  110529. }
  110530. // View
  110531. this.bindView(effect);
  110532. // Fog
  110533. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect, true);
  110534. // image processing
  110535. if (this._imageProcessingConfiguration) {
  110536. this._imageProcessingConfiguration.bind(this._activeEffect);
  110537. }
  110538. }
  110539. this._uniformBuffer.update();
  110540. this._afterBind(mesh, this._activeEffect);
  110541. };
  110542. /**
  110543. * Dispose the material.
  110544. * @param forceDisposeEffect Force disposal of the associated effect.
  110545. * @param forceDisposeTextures Force disposal of the associated textures.
  110546. */
  110547. BackgroundMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  110548. if (forceDisposeEffect === void 0) { forceDisposeEffect = false; }
  110549. if (forceDisposeTextures === void 0) { forceDisposeTextures = false; }
  110550. if (forceDisposeTextures) {
  110551. if (this.diffuseTexture) {
  110552. this.diffuseTexture.dispose();
  110553. }
  110554. if (this.reflectionTexture) {
  110555. this.reflectionTexture.dispose();
  110556. }
  110557. }
  110558. this._renderTargets.dispose();
  110559. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  110560. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  110561. }
  110562. _super.prototype.dispose.call(this, forceDisposeEffect);
  110563. };
  110564. /**
  110565. * Clones the material.
  110566. * @param name The cloned name.
  110567. * @returns The cloned material.
  110568. */
  110569. BackgroundMaterial.prototype.clone = function (name) {
  110570. var _this = this;
  110571. return BABYLON.SerializationHelper.Clone(function () { return new BackgroundMaterial(name, _this.getScene()); }, this);
  110572. };
  110573. /**
  110574. * Serializes the current material to its JSON representation.
  110575. * @returns The JSON representation.
  110576. */
  110577. BackgroundMaterial.prototype.serialize = function () {
  110578. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  110579. serializationObject.customType = "BABYLON.BackgroundMaterial";
  110580. return serializationObject;
  110581. };
  110582. /**
  110583. * Gets the class name of the material
  110584. * @returns "BackgroundMaterial"
  110585. */
  110586. BackgroundMaterial.prototype.getClassName = function () {
  110587. return "BackgroundMaterial";
  110588. };
  110589. /**
  110590. * Parse a JSON input to create back a background material.
  110591. * @param source The JSON data to parse
  110592. * @param scene The scene to create the parsed material in
  110593. * @param rootUrl The root url of the assets the material depends upon
  110594. * @returns the instantiated BackgroundMaterial.
  110595. */
  110596. BackgroundMaterial.Parse = function (source, scene, rootUrl) {
  110597. return BABYLON.SerializationHelper.Parse(function () { return new BackgroundMaterial(source.name, scene); }, source, scene, rootUrl);
  110598. };
  110599. /**
  110600. * Standard reflectance value at parallel view angle.
  110601. */
  110602. BackgroundMaterial.StandardReflectance0 = 0.05;
  110603. /**
  110604. * Standard reflectance value at grazing angle.
  110605. */
  110606. BackgroundMaterial.StandardReflectance90 = 0.5;
  110607. __decorate([
  110608. BABYLON.serializeAsColor3()
  110609. ], BackgroundMaterial.prototype, "_primaryColor", void 0);
  110610. __decorate([
  110611. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  110612. ], BackgroundMaterial.prototype, "primaryColor", void 0);
  110613. __decorate([
  110614. BABYLON.serializeAsColor3()
  110615. ], BackgroundMaterial.prototype, "__perceptualColor", void 0);
  110616. __decorate([
  110617. BABYLON.serialize()
  110618. ], BackgroundMaterial.prototype, "_primaryColorShadowLevel", void 0);
  110619. __decorate([
  110620. BABYLON.serialize()
  110621. ], BackgroundMaterial.prototype, "_primaryColorHighlightLevel", void 0);
  110622. __decorate([
  110623. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  110624. ], BackgroundMaterial.prototype, "primaryColorHighlightLevel", null);
  110625. __decorate([
  110626. BABYLON.serializeAsTexture()
  110627. ], BackgroundMaterial.prototype, "_reflectionTexture", void 0);
  110628. __decorate([
  110629. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  110630. ], BackgroundMaterial.prototype, "reflectionTexture", void 0);
  110631. __decorate([
  110632. BABYLON.serialize()
  110633. ], BackgroundMaterial.prototype, "_reflectionBlur", void 0);
  110634. __decorate([
  110635. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  110636. ], BackgroundMaterial.prototype, "reflectionBlur", void 0);
  110637. __decorate([
  110638. BABYLON.serializeAsTexture()
  110639. ], BackgroundMaterial.prototype, "_diffuseTexture", void 0);
  110640. __decorate([
  110641. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  110642. ], BackgroundMaterial.prototype, "diffuseTexture", void 0);
  110643. __decorate([
  110644. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  110645. ], BackgroundMaterial.prototype, "shadowLights", void 0);
  110646. __decorate([
  110647. BABYLON.serialize()
  110648. ], BackgroundMaterial.prototype, "_shadowLevel", void 0);
  110649. __decorate([
  110650. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  110651. ], BackgroundMaterial.prototype, "shadowLevel", void 0);
  110652. __decorate([
  110653. BABYLON.serializeAsVector3()
  110654. ], BackgroundMaterial.prototype, "_sceneCenter", void 0);
  110655. __decorate([
  110656. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  110657. ], BackgroundMaterial.prototype, "sceneCenter", void 0);
  110658. __decorate([
  110659. BABYLON.serialize()
  110660. ], BackgroundMaterial.prototype, "_opacityFresnel", void 0);
  110661. __decorate([
  110662. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  110663. ], BackgroundMaterial.prototype, "opacityFresnel", void 0);
  110664. __decorate([
  110665. BABYLON.serialize()
  110666. ], BackgroundMaterial.prototype, "_reflectionFresnel", void 0);
  110667. __decorate([
  110668. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  110669. ], BackgroundMaterial.prototype, "reflectionFresnel", void 0);
  110670. __decorate([
  110671. BABYLON.serialize()
  110672. ], BackgroundMaterial.prototype, "_reflectionFalloffDistance", void 0);
  110673. __decorate([
  110674. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  110675. ], BackgroundMaterial.prototype, "reflectionFalloffDistance", void 0);
  110676. __decorate([
  110677. BABYLON.serialize()
  110678. ], BackgroundMaterial.prototype, "_reflectionAmount", void 0);
  110679. __decorate([
  110680. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  110681. ], BackgroundMaterial.prototype, "reflectionAmount", void 0);
  110682. __decorate([
  110683. BABYLON.serialize()
  110684. ], BackgroundMaterial.prototype, "_reflectionReflectance0", void 0);
  110685. __decorate([
  110686. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  110687. ], BackgroundMaterial.prototype, "reflectionReflectance0", void 0);
  110688. __decorate([
  110689. BABYLON.serialize()
  110690. ], BackgroundMaterial.prototype, "_reflectionReflectance90", void 0);
  110691. __decorate([
  110692. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  110693. ], BackgroundMaterial.prototype, "reflectionReflectance90", void 0);
  110694. __decorate([
  110695. BABYLON.serialize()
  110696. ], BackgroundMaterial.prototype, "_useRGBColor", void 0);
  110697. __decorate([
  110698. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  110699. ], BackgroundMaterial.prototype, "useRGBColor", void 0);
  110700. __decorate([
  110701. BABYLON.serialize()
  110702. ], BackgroundMaterial.prototype, "_enableNoise", void 0);
  110703. __decorate([
  110704. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  110705. ], BackgroundMaterial.prototype, "enableNoise", void 0);
  110706. __decorate([
  110707. BABYLON.serialize()
  110708. ], BackgroundMaterial.prototype, "_maxSimultaneousLights", void 0);
  110709. __decorate([
  110710. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  110711. ], BackgroundMaterial.prototype, "maxSimultaneousLights", void 0);
  110712. __decorate([
  110713. BABYLON.serializeAsImageProcessingConfiguration()
  110714. ], BackgroundMaterial.prototype, "_imageProcessingConfiguration", void 0);
  110715. return BackgroundMaterial;
  110716. }(BABYLON.PushMaterial));
  110717. BABYLON.BackgroundMaterial = BackgroundMaterial;
  110718. })(BABYLON || (BABYLON = {}));
  110719. //# sourceMappingURL=babylon.backgroundMaterial.js.map
  110720. var __assign = (this && this.__assign) || function () {
  110721. __assign = Object.assign || function(t) {
  110722. for (var s, i = 1, n = arguments.length; i < n; i++) {
  110723. s = arguments[i];
  110724. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  110725. t[p] = s[p];
  110726. }
  110727. return t;
  110728. };
  110729. return __assign.apply(this, arguments);
  110730. };
  110731. var BABYLON;
  110732. (function (BABYLON) {
  110733. /**
  110734. * The Environment helper class can be used to add a fully featuread none expensive background to your scene.
  110735. * It includes by default a skybox and a ground relying on the BackgroundMaterial.
  110736. * It also helps with the default setup of your imageProcessing configuration.
  110737. */
  110738. var EnvironmentHelper = /** @class */ (function () {
  110739. /**
  110740. * constructor
  110741. * @param options
  110742. * @param scene The scene to add the material to
  110743. */
  110744. function EnvironmentHelper(options, scene) {
  110745. var _this = this;
  110746. this._errorHandler = function (message, exception) {
  110747. _this.onErrorObservable.notifyObservers({ message: message, exception: exception });
  110748. };
  110749. this._options = __assign({}, EnvironmentHelper._getDefaultOptions(), options);
  110750. this._scene = scene;
  110751. this.onErrorObservable = new BABYLON.Observable();
  110752. this._setupBackground();
  110753. this._setupImageProcessing();
  110754. }
  110755. /**
  110756. * Creates the default options for the helper.
  110757. */
  110758. EnvironmentHelper._getDefaultOptions = function () {
  110759. return {
  110760. createGround: true,
  110761. groundSize: 15,
  110762. groundTexture: this._groundTextureCDNUrl,
  110763. groundColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  110764. groundOpacity: 0.9,
  110765. enableGroundShadow: true,
  110766. groundShadowLevel: 0.5,
  110767. enableGroundMirror: false,
  110768. groundMirrorSizeRatio: 0.3,
  110769. groundMirrorBlurKernel: 64,
  110770. groundMirrorAmount: 1,
  110771. groundMirrorFresnelWeight: 1,
  110772. groundMirrorFallOffDistance: 0,
  110773. groundMirrorTextureType: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT,
  110774. groundYBias: 0.00001,
  110775. createSkybox: true,
  110776. skyboxSize: 20,
  110777. skyboxTexture: this._skyboxTextureCDNUrl,
  110778. skyboxColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  110779. backgroundYRotation: 0,
  110780. sizeAuto: true,
  110781. rootPosition: BABYLON.Vector3.Zero(),
  110782. setupImageProcessing: true,
  110783. environmentTexture: this._environmentTextureCDNUrl,
  110784. cameraExposure: 0.8,
  110785. cameraContrast: 1.2,
  110786. toneMappingEnabled: true,
  110787. };
  110788. };
  110789. Object.defineProperty(EnvironmentHelper.prototype, "rootMesh", {
  110790. /**
  110791. * Gets the root mesh created by the helper.
  110792. */
  110793. get: function () {
  110794. return this._rootMesh;
  110795. },
  110796. enumerable: true,
  110797. configurable: true
  110798. });
  110799. Object.defineProperty(EnvironmentHelper.prototype, "skybox", {
  110800. /**
  110801. * Gets the skybox created by the helper.
  110802. */
  110803. get: function () {
  110804. return this._skybox;
  110805. },
  110806. enumerable: true,
  110807. configurable: true
  110808. });
  110809. Object.defineProperty(EnvironmentHelper.prototype, "skyboxTexture", {
  110810. /**
  110811. * Gets the skybox texture created by the helper.
  110812. */
  110813. get: function () {
  110814. return this._skyboxTexture;
  110815. },
  110816. enumerable: true,
  110817. configurable: true
  110818. });
  110819. Object.defineProperty(EnvironmentHelper.prototype, "skyboxMaterial", {
  110820. /**
  110821. * Gets the skybox material created by the helper.
  110822. */
  110823. get: function () {
  110824. return this._skyboxMaterial;
  110825. },
  110826. enumerable: true,
  110827. configurable: true
  110828. });
  110829. Object.defineProperty(EnvironmentHelper.prototype, "ground", {
  110830. /**
  110831. * Gets the ground mesh created by the helper.
  110832. */
  110833. get: function () {
  110834. return this._ground;
  110835. },
  110836. enumerable: true,
  110837. configurable: true
  110838. });
  110839. Object.defineProperty(EnvironmentHelper.prototype, "groundTexture", {
  110840. /**
  110841. * Gets the ground texture created by the helper.
  110842. */
  110843. get: function () {
  110844. return this._groundTexture;
  110845. },
  110846. enumerable: true,
  110847. configurable: true
  110848. });
  110849. Object.defineProperty(EnvironmentHelper.prototype, "groundMirror", {
  110850. /**
  110851. * Gets the ground mirror created by the helper.
  110852. */
  110853. get: function () {
  110854. return this._groundMirror;
  110855. },
  110856. enumerable: true,
  110857. configurable: true
  110858. });
  110859. Object.defineProperty(EnvironmentHelper.prototype, "groundMirrorRenderList", {
  110860. /**
  110861. * Gets the ground mirror render list to helps pushing the meshes
  110862. * you wish in the ground reflection.
  110863. */
  110864. get: function () {
  110865. if (this._groundMirror) {
  110866. return this._groundMirror.renderList;
  110867. }
  110868. return null;
  110869. },
  110870. enumerable: true,
  110871. configurable: true
  110872. });
  110873. Object.defineProperty(EnvironmentHelper.prototype, "groundMaterial", {
  110874. /**
  110875. * Gets the ground material created by the helper.
  110876. */
  110877. get: function () {
  110878. return this._groundMaterial;
  110879. },
  110880. enumerable: true,
  110881. configurable: true
  110882. });
  110883. /**
  110884. * Updates the background according to the new options
  110885. * @param options
  110886. */
  110887. EnvironmentHelper.prototype.updateOptions = function (options) {
  110888. var newOptions = __assign({}, this._options, options);
  110889. if (this._ground && !newOptions.createGround) {
  110890. this._ground.dispose();
  110891. this._ground = null;
  110892. }
  110893. if (this._groundMaterial && !newOptions.createGround) {
  110894. this._groundMaterial.dispose();
  110895. this._groundMaterial = null;
  110896. }
  110897. if (this._groundTexture) {
  110898. if (this._options.groundTexture != newOptions.groundTexture) {
  110899. this._groundTexture.dispose();
  110900. this._groundTexture = null;
  110901. }
  110902. }
  110903. if (this._skybox && !newOptions.createSkybox) {
  110904. this._skybox.dispose();
  110905. this._skybox = null;
  110906. }
  110907. if (this._skyboxMaterial && !newOptions.createSkybox) {
  110908. this._skyboxMaterial.dispose();
  110909. this._skyboxMaterial = null;
  110910. }
  110911. if (this._skyboxTexture) {
  110912. if (this._options.skyboxTexture != newOptions.skyboxTexture) {
  110913. this._skyboxTexture.dispose();
  110914. this._skyboxTexture = null;
  110915. }
  110916. }
  110917. if (this._groundMirror && !newOptions.enableGroundMirror) {
  110918. this._groundMirror.dispose();
  110919. this._groundMirror = null;
  110920. }
  110921. if (this._scene.environmentTexture) {
  110922. if (this._options.environmentTexture != newOptions.environmentTexture) {
  110923. this._scene.environmentTexture.dispose();
  110924. }
  110925. }
  110926. this._options = newOptions;
  110927. this._setupBackground();
  110928. this._setupImageProcessing();
  110929. };
  110930. /**
  110931. * Sets the primary color of all the available elements.
  110932. * @param color the main color to affect to the ground and the background
  110933. */
  110934. EnvironmentHelper.prototype.setMainColor = function (color) {
  110935. if (this.groundMaterial) {
  110936. this.groundMaterial.primaryColor = color;
  110937. }
  110938. if (this.skyboxMaterial) {
  110939. this.skyboxMaterial.primaryColor = color;
  110940. }
  110941. if (this.groundMirror) {
  110942. this.groundMirror.clearColor = new BABYLON.Color4(color.r, color.g, color.b, 1.0);
  110943. }
  110944. };
  110945. /**
  110946. * Setup the image processing according to the specified options.
  110947. */
  110948. EnvironmentHelper.prototype._setupImageProcessing = function () {
  110949. if (this._options.setupImageProcessing) {
  110950. this._scene.imageProcessingConfiguration.contrast = this._options.cameraContrast;
  110951. this._scene.imageProcessingConfiguration.exposure = this._options.cameraExposure;
  110952. this._scene.imageProcessingConfiguration.toneMappingEnabled = this._options.toneMappingEnabled;
  110953. this._setupEnvironmentTexture();
  110954. }
  110955. };
  110956. /**
  110957. * Setup the environment texture according to the specified options.
  110958. */
  110959. EnvironmentHelper.prototype._setupEnvironmentTexture = function () {
  110960. if (this._scene.environmentTexture) {
  110961. return;
  110962. }
  110963. if (this._options.environmentTexture instanceof BABYLON.BaseTexture) {
  110964. this._scene.environmentTexture = this._options.environmentTexture;
  110965. return;
  110966. }
  110967. var environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(this._options.environmentTexture, this._scene);
  110968. this._scene.environmentTexture = environmentTexture;
  110969. };
  110970. /**
  110971. * Setup the background according to the specified options.
  110972. */
  110973. EnvironmentHelper.prototype._setupBackground = function () {
  110974. if (!this._rootMesh) {
  110975. this._rootMesh = new BABYLON.Mesh("BackgroundHelper", this._scene);
  110976. }
  110977. this._rootMesh.rotation.y = this._options.backgroundYRotation;
  110978. var sceneSize = this._getSceneSize();
  110979. if (this._options.createGround) {
  110980. this._setupGround(sceneSize);
  110981. this._setupGroundMaterial();
  110982. this._setupGroundDiffuseTexture();
  110983. if (this._options.enableGroundMirror) {
  110984. this._setupGroundMirrorTexture(sceneSize);
  110985. }
  110986. this._setupMirrorInGroundMaterial();
  110987. }
  110988. if (this._options.createSkybox) {
  110989. this._setupSkybox(sceneSize);
  110990. this._setupSkyboxMaterial();
  110991. this._setupSkyboxReflectionTexture();
  110992. }
  110993. this._rootMesh.position.x = sceneSize.rootPosition.x;
  110994. this._rootMesh.position.z = sceneSize.rootPosition.z;
  110995. this._rootMesh.position.y = sceneSize.rootPosition.y;
  110996. };
  110997. /**
  110998. * Get the scene sizes according to the setup.
  110999. */
  111000. EnvironmentHelper.prototype._getSceneSize = function () {
  111001. var _this = this;
  111002. var groundSize = this._options.groundSize;
  111003. var skyboxSize = this._options.skyboxSize;
  111004. var rootPosition = this._options.rootPosition;
  111005. if (!this._scene.meshes || this._scene.meshes.length === 1) { // 1 only means the root of the helper.
  111006. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  111007. }
  111008. var sceneExtends = this._scene.getWorldExtends(function (mesh) {
  111009. return (mesh !== _this._ground && mesh !== _this._rootMesh && mesh !== _this._skybox);
  111010. });
  111011. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  111012. if (this._options.sizeAuto) {
  111013. if (this._scene.activeCamera instanceof BABYLON.ArcRotateCamera &&
  111014. this._scene.activeCamera.upperRadiusLimit) {
  111015. groundSize = this._scene.activeCamera.upperRadiusLimit * 2;
  111016. skyboxSize = groundSize;
  111017. }
  111018. var sceneDiagonalLenght = sceneDiagonal.length();
  111019. if (sceneDiagonalLenght > groundSize) {
  111020. groundSize = sceneDiagonalLenght * 2;
  111021. skyboxSize = groundSize;
  111022. }
  111023. // 10 % bigger.
  111024. groundSize *= 1.1;
  111025. skyboxSize *= 1.5;
  111026. rootPosition = sceneExtends.min.add(sceneDiagonal.scale(0.5));
  111027. rootPosition.y = sceneExtends.min.y - this._options.groundYBias;
  111028. }
  111029. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  111030. };
  111031. /**
  111032. * Setup the ground according to the specified options.
  111033. */
  111034. EnvironmentHelper.prototype._setupGround = function (sceneSize) {
  111035. var _this = this;
  111036. if (!this._ground || this._ground.isDisposed()) {
  111037. this._ground = BABYLON.Mesh.CreatePlane("BackgroundPlane", sceneSize.groundSize, this._scene);
  111038. this._ground.rotation.x = Math.PI / 2; // Face up by default.
  111039. this._ground.parent = this._rootMesh;
  111040. this._ground.onDisposeObservable.add(function () { _this._ground = null; });
  111041. }
  111042. this._ground.receiveShadows = this._options.enableGroundShadow;
  111043. };
  111044. /**
  111045. * Setup the ground material according to the specified options.
  111046. */
  111047. EnvironmentHelper.prototype._setupGroundMaterial = function () {
  111048. if (!this._groundMaterial) {
  111049. this._groundMaterial = new BABYLON.BackgroundMaterial("BackgroundPlaneMaterial", this._scene);
  111050. }
  111051. this._groundMaterial.alpha = this._options.groundOpacity;
  111052. this._groundMaterial.alphaMode = BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
  111053. this._groundMaterial.shadowLevel = this._options.groundShadowLevel;
  111054. this._groundMaterial.primaryColor = this._options.groundColor;
  111055. this._groundMaterial.useRGBColor = false;
  111056. this._groundMaterial.enableNoise = true;
  111057. if (this._ground) {
  111058. this._ground.material = this._groundMaterial;
  111059. }
  111060. };
  111061. /**
  111062. * Setup the ground diffuse texture according to the specified options.
  111063. */
  111064. EnvironmentHelper.prototype._setupGroundDiffuseTexture = function () {
  111065. if (!this._groundMaterial) {
  111066. return;
  111067. }
  111068. if (this._groundTexture) {
  111069. return;
  111070. }
  111071. if (this._options.groundTexture instanceof BABYLON.BaseTexture) {
  111072. this._groundMaterial.diffuseTexture = this._options.groundTexture;
  111073. return;
  111074. }
  111075. var diffuseTexture = new BABYLON.Texture(this._options.groundTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  111076. diffuseTexture.gammaSpace = false;
  111077. diffuseTexture.hasAlpha = true;
  111078. this._groundMaterial.diffuseTexture = diffuseTexture;
  111079. };
  111080. /**
  111081. * Setup the ground mirror texture according to the specified options.
  111082. */
  111083. EnvironmentHelper.prototype._setupGroundMirrorTexture = function (sceneSize) {
  111084. var wrapping = BABYLON.Texture.CLAMP_ADDRESSMODE;
  111085. if (!this._groundMirror) {
  111086. this._groundMirror = new BABYLON.MirrorTexture("BackgroundPlaneMirrorTexture", { ratio: this._options.groundMirrorSizeRatio }, this._scene, false, this._options.groundMirrorTextureType, BABYLON.Texture.BILINEAR_SAMPLINGMODE, true);
  111087. this._groundMirror.mirrorPlane = new BABYLON.Plane(0, -1, 0, sceneSize.rootPosition.y);
  111088. this._groundMirror.anisotropicFilteringLevel = 1;
  111089. this._groundMirror.wrapU = wrapping;
  111090. this._groundMirror.wrapV = wrapping;
  111091. this._groundMirror.gammaSpace = false;
  111092. if (this._groundMirror.renderList) {
  111093. for (var i = 0; i < this._scene.meshes.length; i++) {
  111094. var mesh = this._scene.meshes[i];
  111095. if (mesh !== this._ground &&
  111096. mesh !== this._skybox &&
  111097. mesh !== this._rootMesh) {
  111098. this._groundMirror.renderList.push(mesh);
  111099. }
  111100. }
  111101. }
  111102. }
  111103. this._groundMirror.clearColor = new BABYLON.Color4(this._options.groundColor.r, this._options.groundColor.g, this._options.groundColor.b, 1);
  111104. this._groundMirror.adaptiveBlurKernel = this._options.groundMirrorBlurKernel;
  111105. };
  111106. /**
  111107. * Setup the ground to receive the mirror texture.
  111108. */
  111109. EnvironmentHelper.prototype._setupMirrorInGroundMaterial = function () {
  111110. if (this._groundMaterial) {
  111111. this._groundMaterial.reflectionTexture = this._groundMirror;
  111112. this._groundMaterial.reflectionFresnel = true;
  111113. this._groundMaterial.reflectionAmount = this._options.groundMirrorAmount;
  111114. this._groundMaterial.reflectionStandardFresnelWeight = this._options.groundMirrorFresnelWeight;
  111115. this._groundMaterial.reflectionFalloffDistance = this._options.groundMirrorFallOffDistance;
  111116. }
  111117. };
  111118. /**
  111119. * Setup the skybox according to the specified options.
  111120. */
  111121. EnvironmentHelper.prototype._setupSkybox = function (sceneSize) {
  111122. var _this = this;
  111123. if (!this._skybox || this._skybox.isDisposed()) {
  111124. this._skybox = BABYLON.Mesh.CreateBox("BackgroundSkybox", sceneSize.skyboxSize, this._scene, undefined, BABYLON.Mesh.BACKSIDE);
  111125. this._skybox.onDisposeObservable.add(function () { _this._skybox = null; });
  111126. }
  111127. this._skybox.parent = this._rootMesh;
  111128. };
  111129. /**
  111130. * Setup the skybox material according to the specified options.
  111131. */
  111132. EnvironmentHelper.prototype._setupSkyboxMaterial = function () {
  111133. if (!this._skybox) {
  111134. return;
  111135. }
  111136. if (!this._skyboxMaterial) {
  111137. this._skyboxMaterial = new BABYLON.BackgroundMaterial("BackgroundSkyboxMaterial", this._scene);
  111138. }
  111139. this._skyboxMaterial.useRGBColor = false;
  111140. this._skyboxMaterial.primaryColor = this._options.skyboxColor;
  111141. this._skyboxMaterial.enableNoise = true;
  111142. this._skybox.material = this._skyboxMaterial;
  111143. };
  111144. /**
  111145. * Setup the skybox reflection texture according to the specified options.
  111146. */
  111147. EnvironmentHelper.prototype._setupSkyboxReflectionTexture = function () {
  111148. if (!this._skyboxMaterial) {
  111149. return;
  111150. }
  111151. if (this._skyboxTexture) {
  111152. return;
  111153. }
  111154. if (this._options.skyboxTexture instanceof BABYLON.BaseTexture) {
  111155. this._skyboxMaterial.reflectionTexture = this._options.skyboxTexture;
  111156. return;
  111157. }
  111158. this._skyboxTexture = new BABYLON.CubeTexture(this._options.skyboxTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  111159. this._skyboxTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  111160. this._skyboxTexture.gammaSpace = false;
  111161. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  111162. };
  111163. /**
  111164. * Dispose all the elements created by the Helper.
  111165. */
  111166. EnvironmentHelper.prototype.dispose = function () {
  111167. if (this._groundMaterial) {
  111168. this._groundMaterial.dispose(true, true);
  111169. }
  111170. if (this._skyboxMaterial) {
  111171. this._skyboxMaterial.dispose(true, true);
  111172. }
  111173. this._rootMesh.dispose(false);
  111174. };
  111175. /**
  111176. * Default ground texture URL.
  111177. */
  111178. EnvironmentHelper._groundTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundGround.png";
  111179. /**
  111180. * Default skybox texture URL.
  111181. */
  111182. EnvironmentHelper._skyboxTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundSkybox.dds";
  111183. /**
  111184. * Default environment texture URL.
  111185. */
  111186. EnvironmentHelper._environmentTextureCDNUrl = "https://assets.babylonjs.com/environments/environmentSpecular.env";
  111187. return EnvironmentHelper;
  111188. }());
  111189. BABYLON.EnvironmentHelper = EnvironmentHelper;
  111190. })(BABYLON || (BABYLON = {}));
  111191. //# sourceMappingURL=babylon.environmentHelper.js.map
  111192. var BABYLON;
  111193. (function (BABYLON) {
  111194. /** Internal class used to store shapes for emitters */
  111195. var ParticleSystemSetEmitterCreationOptions = /** @class */ (function () {
  111196. function ParticleSystemSetEmitterCreationOptions() {
  111197. }
  111198. return ParticleSystemSetEmitterCreationOptions;
  111199. }());
  111200. /**
  111201. * Represents a set of particle systems working together to create a specific effect
  111202. */
  111203. var ParticleSystemSet = /** @class */ (function () {
  111204. function ParticleSystemSet() {
  111205. /**
  111206. * Gets the particle system list
  111207. */
  111208. this.systems = new Array();
  111209. }
  111210. Object.defineProperty(ParticleSystemSet.prototype, "emitterNode", {
  111211. /**
  111212. * Gets the emitter node used with this set
  111213. */
  111214. get: function () {
  111215. return this._emitterNode;
  111216. },
  111217. enumerable: true,
  111218. configurable: true
  111219. });
  111220. /**
  111221. * Creates a new emitter mesh as a sphere
  111222. * @param options defines the options used to create the sphere
  111223. * @param renderingGroupId defines the renderingGroupId to use for the sphere
  111224. * @param scene defines the hosting scene
  111225. */
  111226. ParticleSystemSet.prototype.setEmitterAsSphere = function (options, renderingGroupId, scene) {
  111227. if (this._emitterNode) {
  111228. this._emitterNode.dispose();
  111229. }
  111230. this._emitterCreationOptions = {
  111231. kind: "Sphere",
  111232. options: options,
  111233. renderingGroupId: renderingGroupId
  111234. };
  111235. var emitterMesh = BABYLON.MeshBuilder.CreateSphere("emitterSphere", { diameter: options.diameter, segments: options.segments }, scene);
  111236. emitterMesh.renderingGroupId = renderingGroupId;
  111237. var material = new BABYLON.StandardMaterial("emitterSphereMaterial", scene);
  111238. material.emissiveColor = options.color;
  111239. emitterMesh.material = material;
  111240. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  111241. var system = _a[_i];
  111242. system.emitter = emitterMesh;
  111243. }
  111244. this._emitterNode = emitterMesh;
  111245. };
  111246. /**
  111247. * Starts all particle systems of the set
  111248. * @param emitter defines an optional mesh to use as emitter for the particle systems
  111249. */
  111250. ParticleSystemSet.prototype.start = function (emitter) {
  111251. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  111252. var system = _a[_i];
  111253. if (emitter) {
  111254. system.emitter = emitter;
  111255. }
  111256. system.start();
  111257. }
  111258. };
  111259. /**
  111260. * Release all associated resources
  111261. */
  111262. ParticleSystemSet.prototype.dispose = function () {
  111263. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  111264. var system = _a[_i];
  111265. system.dispose();
  111266. }
  111267. this.systems = [];
  111268. if (this._emitterNode) {
  111269. this._emitterNode.dispose();
  111270. this._emitterNode = null;
  111271. }
  111272. };
  111273. /**
  111274. * Serialize the set into a JSON compatible object
  111275. * @returns a JSON compatible representation of the set
  111276. */
  111277. ParticleSystemSet.prototype.serialize = function () {
  111278. var result = {};
  111279. result.systems = [];
  111280. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  111281. var system = _a[_i];
  111282. result.systems.push(system.serialize());
  111283. }
  111284. if (this._emitterNode) {
  111285. result.emitter = this._emitterCreationOptions;
  111286. }
  111287. return result;
  111288. };
  111289. /**
  111290. * Parse a new ParticleSystemSet from a serialized source
  111291. * @param data defines a JSON compatible representation of the set
  111292. * @param scene defines the hosting scene
  111293. * @param gpu defines if we want GPU particles or CPU particles
  111294. * @returns a new ParticleSystemSet
  111295. */
  111296. ParticleSystemSet.Parse = function (data, scene, gpu) {
  111297. if (gpu === void 0) { gpu = false; }
  111298. var result = new ParticleSystemSet();
  111299. var rootUrl = BABYLON.ParticleHelper.BaseAssetsUrl + "/textures/";
  111300. scene = scene || BABYLON.Engine.LastCreatedScene;
  111301. for (var _i = 0, _a = data.systems; _i < _a.length; _i++) {
  111302. var system = _a[_i];
  111303. result.systems.push(gpu ? BABYLON.GPUParticleSystem.Parse(system, scene, rootUrl) : BABYLON.ParticleSystem.Parse(system, scene, rootUrl));
  111304. }
  111305. if (data.emitter) {
  111306. var options = data.emitter.options;
  111307. switch (data.emitter.kind) {
  111308. case "Sphere":
  111309. result.setEmitterAsSphere({
  111310. diameter: options.diameter,
  111311. segments: options.segments,
  111312. color: BABYLON.Color3.FromArray(options.color)
  111313. }, data.emitter.renderingGroupId, scene);
  111314. break;
  111315. }
  111316. }
  111317. return result;
  111318. };
  111319. return ParticleSystemSet;
  111320. }());
  111321. BABYLON.ParticleSystemSet = ParticleSystemSet;
  111322. })(BABYLON || (BABYLON = {}));
  111323. //# sourceMappingURL=babylon.particleSystemSet.js.map
  111324. var BABYLON;
  111325. (function (BABYLON) {
  111326. /**
  111327. * This class is made for on one-liner static method to help creating particle system set.
  111328. */
  111329. var ParticleHelper = /** @class */ (function () {
  111330. function ParticleHelper() {
  111331. }
  111332. /**
  111333. * Create a default particle system that you can tweak
  111334. * @param emitter defines the emitter to use
  111335. * @param capacity defines the system capacity (default is 500 particles)
  111336. * @param scene defines the hosting scene
  111337. * @param useGPU defines if a GPUParticleSystem must be created (default is false)
  111338. * @returns the new Particle system
  111339. */
  111340. ParticleHelper.CreateDefault = function (emitter, capacity, scene, useGPU) {
  111341. if (capacity === void 0) { capacity = 500; }
  111342. if (useGPU === void 0) { useGPU = false; }
  111343. var system;
  111344. if (useGPU) {
  111345. system = new BABYLON.GPUParticleSystem("default system", { capacity: capacity }, scene);
  111346. }
  111347. else {
  111348. system = new BABYLON.ParticleSystem("default system", capacity, scene);
  111349. }
  111350. system.emitter = emitter;
  111351. system.particleTexture = new BABYLON.Texture("https://www.babylonjs.com/assets/Flare.png", system.getScene());
  111352. system.createConeEmitter(0.1, Math.PI / 4);
  111353. // Particle color
  111354. system.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  111355. system.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  111356. system.colorDead = new BABYLON.Color4(1.0, 1.0, 1.0, 0.0);
  111357. // Particle Size
  111358. system.minSize = 0.1;
  111359. system.maxSize = 0.1;
  111360. // Emission speed
  111361. system.minEmitPower = 2;
  111362. system.maxEmitPower = 2;
  111363. // Update speed
  111364. system.updateSpeed = 1 / 60;
  111365. system.emitRate = 30;
  111366. return system;
  111367. };
  111368. /**
  111369. * This is the main static method (one-liner) of this helper to create different particle systems
  111370. * @param type This string represents the type to the particle system to create
  111371. * @param scene The scene where the particle system should live
  111372. * @param gpu If the system will use gpu
  111373. * @returns the ParticleSystemSet created
  111374. */
  111375. ParticleHelper.CreateAsync = function (type, scene, gpu) {
  111376. if (gpu === void 0) { gpu = false; }
  111377. if (!scene) {
  111378. scene = BABYLON.Engine.LastCreatedScene;
  111379. ;
  111380. }
  111381. var token = {};
  111382. scene._addPendingData(token);
  111383. return new Promise(function (resolve, reject) {
  111384. if (gpu && !BABYLON.GPUParticleSystem.IsSupported) {
  111385. scene._removePendingData(token);
  111386. return reject("Particle system with GPU is not supported.");
  111387. }
  111388. BABYLON.Tools.LoadFile(ParticleHelper.BaseAssetsUrl + "/systems/" + type + ".json", function (data, response) {
  111389. scene._removePendingData(token);
  111390. var newData = JSON.parse(data.toString());
  111391. return resolve(BABYLON.ParticleSystemSet.Parse(newData, scene, gpu));
  111392. }, undefined, undefined, undefined, function (req, exception) {
  111393. scene._removePendingData(token);
  111394. return reject("An error occured while the creation of your particle system. Check if your type '" + type + "' exists.");
  111395. });
  111396. });
  111397. };
  111398. /**
  111399. * Static function used to export a particle system to a ParticleSystemSet variable.
  111400. * Please note that the emitter shape is not exported
  111401. * @param system defines the particle systems to export
  111402. */
  111403. ParticleHelper.ExportSet = function (systems) {
  111404. var set = new BABYLON.ParticleSystemSet();
  111405. for (var _i = 0, systems_1 = systems; _i < systems_1.length; _i++) {
  111406. var system = systems_1[_i];
  111407. set.systems.push(system);
  111408. }
  111409. return set;
  111410. };
  111411. /**
  111412. * Gets or sets base Assets URL
  111413. */
  111414. ParticleHelper.BaseAssetsUrl = "https://assets.babylonjs.com/particles";
  111415. return ParticleHelper;
  111416. }());
  111417. BABYLON.ParticleHelper = ParticleHelper;
  111418. })(BABYLON || (BABYLON = {}));
  111419. //# sourceMappingURL=babylon.particleHelper.js.map
  111420. var BABYLON;
  111421. (function (BABYLON) {
  111422. /**
  111423. * Display a 360 degree video on an approximately spherical surface, useful for VR applications or skyboxes.
  111424. * As a subclass of TransformNode, this allow parenting to the camera or multiple videos with different locations in the scene.
  111425. * This class achieves its effect with a VideoTexture and a correctly configured BackgroundMaterial on an inverted sphere.
  111426. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  111427. */
  111428. var VideoDome = /** @class */ (function (_super) {
  111429. __extends(VideoDome, _super);
  111430. /**
  111431. * Create an instance of this class and pass through the parameters to the relevant classes, VideoTexture, StandardMaterial, and Mesh.
  111432. * @param name Element's name, child elements will append suffixes for their own names.
  111433. * @param urlsOrVideo defines the url(s) or the video element to use
  111434. * @param options An object containing optional or exposed sub element properties
  111435. */
  111436. function VideoDome(name, urlsOrVideo, options, scene) {
  111437. var _this = _super.call(this, name, scene) || this;
  111438. _this._useDirectMapping = false;
  111439. // set defaults and manage values
  111440. name = name || "videoDome";
  111441. options.resolution = (Math.abs(options.resolution) | 0) || 32;
  111442. options.clickToPlay = Boolean(options.clickToPlay);
  111443. options.autoPlay = options.autoPlay === undefined ? true : Boolean(options.autoPlay);
  111444. options.loop = options.loop === undefined ? true : Boolean(options.loop);
  111445. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  111446. if (options.useDirectMapping === undefined) {
  111447. _this._useDirectMapping = true;
  111448. }
  111449. else {
  111450. _this._useDirectMapping = options.useDirectMapping;
  111451. }
  111452. _this._setReady(false);
  111453. // create
  111454. var tempOptions = { loop: options.loop, autoPlay: options.autoPlay, autoUpdateTexture: true, poster: options.poster };
  111455. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  111456. var texture = _this._videoTexture = new BABYLON.VideoTexture(name + "_texture", urlsOrVideo, scene, false, _this._useDirectMapping, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, tempOptions);
  111457. _this._mesh = BABYLON.Mesh.CreateSphere(name + "_mesh", options.resolution, options.size, scene, false, BABYLON.Mesh.BACKSIDE);
  111458. texture.onLoadObservable.addOnce(function () {
  111459. _this._setReady(true);
  111460. });
  111461. // configure material
  111462. material.useEquirectangularFOV = true;
  111463. material.fovMultiplier = 1.0;
  111464. material.opacityFresnel = false;
  111465. if (_this._useDirectMapping) {
  111466. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  111467. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  111468. material.diffuseTexture = texture;
  111469. }
  111470. else {
  111471. texture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  111472. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  111473. material.reflectionTexture = texture;
  111474. }
  111475. // configure mesh
  111476. _this._mesh.material = material;
  111477. _this._mesh.parent = _this;
  111478. // optional configuration
  111479. if (options.clickToPlay) {
  111480. scene.onPointerUp = function () {
  111481. _this._videoTexture.video.play();
  111482. };
  111483. }
  111484. return _this;
  111485. }
  111486. Object.defineProperty(VideoDome.prototype, "videoTexture", {
  111487. /**
  111488. * Gets the video texture being displayed on the sphere
  111489. */
  111490. get: function () {
  111491. return this._videoTexture;
  111492. },
  111493. enumerable: true,
  111494. configurable: true
  111495. });
  111496. Object.defineProperty(VideoDome.prototype, "fovMultiplier", {
  111497. /**
  111498. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  111499. * Also see the options.resolution property.
  111500. */
  111501. get: function () {
  111502. return this._material.fovMultiplier;
  111503. },
  111504. set: function (value) {
  111505. this._material.fovMultiplier = value;
  111506. },
  111507. enumerable: true,
  111508. configurable: true
  111509. });
  111510. /**
  111511. * Releases resources associated with this node.
  111512. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  111513. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  111514. */
  111515. VideoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  111516. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  111517. this._videoTexture.dispose();
  111518. this._mesh.dispose();
  111519. this._material.dispose();
  111520. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  111521. };
  111522. return VideoDome;
  111523. }(BABYLON.TransformNode));
  111524. BABYLON.VideoDome = VideoDome;
  111525. })(BABYLON || (BABYLON = {}));
  111526. //# sourceMappingURL=babylon.videoDome.js.map
  111527. var BABYLON;
  111528. (function (BABYLON) {
  111529. /**
  111530. * Display a 360 degree photo on an approximately spherical surface, useful for VR applications or skyboxes.
  111531. * As a subclass of TransformNode, this allow parenting to the camera with different locations in the scene.
  111532. * This class achieves its effect with a Texture and a correctly configured BackgroundMaterial on an inverted sphere.
  111533. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  111534. */
  111535. var PhotoDome = /** @class */ (function (_super) {
  111536. __extends(PhotoDome, _super);
  111537. /**
  111538. * Create an instance of this class and pass through the parameters to the relevant classes, Texture, StandardMaterial, and Mesh.
  111539. * @param name Element's name, child elements will append suffixes for their own names.
  111540. * @param urlsOfPhoto defines the url of the photo to display
  111541. * @param options defines an object containing optional or exposed sub element properties
  111542. * @param onError defines a callback called when an error occured while loading the texture
  111543. */
  111544. function PhotoDome(name, urlOfPhoto, options, scene, onError) {
  111545. if (onError === void 0) { onError = null; }
  111546. var _this = _super.call(this, name, scene) || this;
  111547. _this._useDirectMapping = false;
  111548. /**
  111549. * Observable raised when an error occured while loading the 360 image
  111550. */
  111551. _this.onLoadErrorObservable = new BABYLON.Observable();
  111552. // set defaults and manage values
  111553. name = name || "photoDome";
  111554. options.resolution = (Math.abs(options.resolution) | 0) || 32;
  111555. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  111556. if (options.useDirectMapping === undefined) {
  111557. _this._useDirectMapping = true;
  111558. }
  111559. else {
  111560. _this._useDirectMapping = options.useDirectMapping;
  111561. }
  111562. _this._setReady(false);
  111563. // create
  111564. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  111565. _this._mesh = BABYLON.Mesh.CreateSphere(name + "_mesh", options.resolution, options.size, scene, false, BABYLON.Mesh.BACKSIDE);
  111566. // configure material
  111567. material.opacityFresnel = false;
  111568. material.useEquirectangularFOV = true;
  111569. material.fovMultiplier = 1.0;
  111570. _this.photoTexture = new BABYLON.Texture(urlOfPhoto, scene, true, !_this._useDirectMapping, undefined, undefined, function (message, exception) {
  111571. _this.onLoadErrorObservable.notifyObservers(message || "Unknown error occured");
  111572. if (onError) {
  111573. onError(message, exception);
  111574. }
  111575. });
  111576. _this.photoTexture.onLoadObservable.addOnce(function () {
  111577. _this._setReady(true);
  111578. });
  111579. // configure mesh
  111580. _this._mesh.material = material;
  111581. _this._mesh.parent = _this;
  111582. return _this;
  111583. }
  111584. Object.defineProperty(PhotoDome.prototype, "photoTexture", {
  111585. /**
  111586. * Gets or sets the texture being displayed on the sphere
  111587. */
  111588. get: function () {
  111589. return this._photoTexture;
  111590. },
  111591. set: function (value) {
  111592. if (this._photoTexture === value) {
  111593. return;
  111594. }
  111595. this._photoTexture = value;
  111596. if (this._useDirectMapping) {
  111597. this._photoTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  111598. this._photoTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  111599. this._material.diffuseTexture = this._photoTexture;
  111600. }
  111601. else {
  111602. this._photoTexture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  111603. this._photoTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  111604. this._material.reflectionTexture = this._photoTexture;
  111605. }
  111606. },
  111607. enumerable: true,
  111608. configurable: true
  111609. });
  111610. Object.defineProperty(PhotoDome.prototype, "fovMultiplier", {
  111611. /**
  111612. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  111613. * Also see the options.resolution property.
  111614. */
  111615. get: function () {
  111616. return this._material.fovMultiplier;
  111617. },
  111618. set: function (value) {
  111619. this._material.fovMultiplier = value;
  111620. },
  111621. enumerable: true,
  111622. configurable: true
  111623. });
  111624. /**
  111625. * Releases resources associated with this node.
  111626. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  111627. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  111628. */
  111629. PhotoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  111630. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  111631. this._photoTexture.dispose();
  111632. this._mesh.dispose();
  111633. this._material.dispose();
  111634. this.onLoadErrorObservable.clear();
  111635. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  111636. };
  111637. return PhotoDome;
  111638. }(BABYLON.TransformNode));
  111639. BABYLON.PhotoDome = PhotoDome;
  111640. })(BABYLON || (BABYLON = {}));
  111641. //# sourceMappingURL=babylon.photoDome.js.map
  111642. var BABYLON;
  111643. (function (BABYLON) {
  111644. BABYLON.Engine.prototype.createQuery = function () {
  111645. return this._gl.createQuery();
  111646. };
  111647. BABYLON.Engine.prototype.deleteQuery = function (query) {
  111648. this._gl.deleteQuery(query);
  111649. return this;
  111650. };
  111651. BABYLON.Engine.prototype.isQueryResultAvailable = function (query) {
  111652. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  111653. };
  111654. BABYLON.Engine.prototype.getQueryResult = function (query) {
  111655. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  111656. };
  111657. BABYLON.Engine.prototype.beginOcclusionQuery = function (algorithmType, query) {
  111658. var glAlgorithm = this._getGlAlgorithmType(algorithmType);
  111659. this._gl.beginQuery(glAlgorithm, query);
  111660. return this;
  111661. };
  111662. BABYLON.Engine.prototype.endOcclusionQuery = function (algorithmType) {
  111663. var glAlgorithm = this._getGlAlgorithmType(algorithmType);
  111664. this._gl.endQuery(glAlgorithm);
  111665. return this;
  111666. };
  111667. BABYLON.Engine.prototype._createTimeQuery = function () {
  111668. var timerQuery = this.getCaps().timerQuery;
  111669. if (timerQuery.createQueryEXT) {
  111670. return timerQuery.createQueryEXT();
  111671. }
  111672. return this.createQuery();
  111673. };
  111674. BABYLON.Engine.prototype._deleteTimeQuery = function (query) {
  111675. var timerQuery = this.getCaps().timerQuery;
  111676. if (timerQuery.deleteQueryEXT) {
  111677. timerQuery.deleteQueryEXT(query);
  111678. return;
  111679. }
  111680. this.deleteQuery(query);
  111681. };
  111682. BABYLON.Engine.prototype._getTimeQueryResult = function (query) {
  111683. var timerQuery = this.getCaps().timerQuery;
  111684. if (timerQuery.getQueryObjectEXT) {
  111685. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
  111686. }
  111687. return this.getQueryResult(query);
  111688. };
  111689. BABYLON.Engine.prototype._getTimeQueryAvailability = function (query) {
  111690. var timerQuery = this.getCaps().timerQuery;
  111691. if (timerQuery.getQueryObjectEXT) {
  111692. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
  111693. }
  111694. return this.isQueryResultAvailable(query);
  111695. };
  111696. BABYLON.Engine.prototype.startTimeQuery = function () {
  111697. var caps = this.getCaps();
  111698. var timerQuery = caps.timerQuery;
  111699. if (!timerQuery) {
  111700. return null;
  111701. }
  111702. var token = new BABYLON._TimeToken();
  111703. this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  111704. if (caps.canUseTimestampForTimerQuery) {
  111705. token._startTimeQuery = this._createTimeQuery();
  111706. timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
  111707. }
  111708. else {
  111709. if (this._currentNonTimestampToken) {
  111710. return this._currentNonTimestampToken;
  111711. }
  111712. token._timeElapsedQuery = this._createTimeQuery();
  111713. if (timerQuery.beginQueryEXT) {
  111714. timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  111715. }
  111716. else {
  111717. this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  111718. }
  111719. this._currentNonTimestampToken = token;
  111720. }
  111721. return token;
  111722. };
  111723. BABYLON.Engine.prototype.endTimeQuery = function (token) {
  111724. var caps = this.getCaps();
  111725. var timerQuery = caps.timerQuery;
  111726. if (!timerQuery || !token) {
  111727. return -1;
  111728. }
  111729. if (caps.canUseTimestampForTimerQuery) {
  111730. if (!token._startTimeQuery) {
  111731. return -1;
  111732. }
  111733. if (!token._endTimeQuery) {
  111734. token._endTimeQuery = this._createTimeQuery();
  111735. timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
  111736. }
  111737. }
  111738. else if (!token._timeElapsedQueryEnded) {
  111739. if (!token._timeElapsedQuery) {
  111740. return -1;
  111741. }
  111742. if (timerQuery.endQueryEXT) {
  111743. timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
  111744. }
  111745. else {
  111746. this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
  111747. }
  111748. token._timeElapsedQueryEnded = true;
  111749. }
  111750. var disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  111751. var available = false;
  111752. if (token._endTimeQuery) {
  111753. available = this._getTimeQueryAvailability(token._endTimeQuery);
  111754. }
  111755. else if (token._timeElapsedQuery) {
  111756. available = this._getTimeQueryAvailability(token._timeElapsedQuery);
  111757. }
  111758. if (available && !disjoint) {
  111759. var result = 0;
  111760. if (caps.canUseTimestampForTimerQuery) {
  111761. if (!token._startTimeQuery || !token._endTimeQuery) {
  111762. return -1;
  111763. }
  111764. var timeStart = this._getTimeQueryResult(token._startTimeQuery);
  111765. var timeEnd = this._getTimeQueryResult(token._endTimeQuery);
  111766. result = timeEnd - timeStart;
  111767. this._deleteTimeQuery(token._startTimeQuery);
  111768. this._deleteTimeQuery(token._endTimeQuery);
  111769. token._startTimeQuery = null;
  111770. token._endTimeQuery = null;
  111771. }
  111772. else {
  111773. if (!token._timeElapsedQuery) {
  111774. return -1;
  111775. }
  111776. result = this._getTimeQueryResult(token._timeElapsedQuery);
  111777. this._deleteTimeQuery(token._timeElapsedQuery);
  111778. token._timeElapsedQuery = null;
  111779. token._timeElapsedQueryEnded = false;
  111780. this._currentNonTimestampToken = null;
  111781. }
  111782. return result;
  111783. }
  111784. return -1;
  111785. };
  111786. BABYLON.Engine.prototype._getGlAlgorithmType = function (algorithmType) {
  111787. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  111788. };
  111789. // We also need to update AbstractMesh as there is a portion of the code there
  111790. BABYLON.AbstractMesh.prototype._checkOcclusionQuery = function () {
  111791. if (this.occlusionType === BABYLON.AbstractMesh.OCCLUSION_TYPE_NONE) {
  111792. this._isOccluded = false;
  111793. return;
  111794. }
  111795. var engine = this.getEngine();
  111796. if (engine.webGLVersion < 2) {
  111797. this._isOccluded = false;
  111798. return;
  111799. }
  111800. if (!engine.isQueryResultAvailable) { // Occlusion query where not referenced
  111801. this._isOccluded = false;
  111802. return;
  111803. }
  111804. if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
  111805. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  111806. if (isOcclusionQueryAvailable) {
  111807. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  111808. this._isOcclusionQueryInProgress = false;
  111809. this._occlusionInternalRetryCounter = 0;
  111810. this._isOccluded = occlusionQueryResult === 1 ? false : true;
  111811. }
  111812. else {
  111813. this._occlusionInternalRetryCounter++;
  111814. if (this.occlusionRetryCount !== -1 && this._occlusionInternalRetryCounter > this.occlusionRetryCount) {
  111815. this._isOcclusionQueryInProgress = false;
  111816. this._occlusionInternalRetryCounter = 0;
  111817. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  111818. // if strict continue the last state of the object.
  111819. this._isOccluded = this.occlusionType === BABYLON.AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : this._isOccluded;
  111820. }
  111821. else {
  111822. return;
  111823. }
  111824. }
  111825. }
  111826. var scene = this.getScene();
  111827. if (scene.getBoundingBoxRenderer) {
  111828. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  111829. if (!this._occlusionQuery) {
  111830. this._occlusionQuery = engine.createQuery();
  111831. }
  111832. engine.beginOcclusionQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery);
  111833. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  111834. engine.endOcclusionQuery(this.occlusionQueryAlgorithmType);
  111835. this._isOcclusionQueryInProgress = true;
  111836. }
  111837. };
  111838. })(BABYLON || (BABYLON = {}));
  111839. //# sourceMappingURL=babylon.engine.occlusionQuery.js.map
  111840. var BABYLON;
  111841. (function (BABYLON) {
  111842. /**
  111843. * Class used to generate noise procedural textures
  111844. */
  111845. var NoiseProceduralTexture = /** @class */ (function (_super) {
  111846. __extends(NoiseProceduralTexture, _super);
  111847. /**
  111848. * Creates a new NoiseProceduralTexture
  111849. * @param name defines the name fo the texture
  111850. * @param size defines the size of the texture (default is 256)
  111851. * @param scene defines the hosting scene
  111852. * @param fallbackTexture defines the texture to use if the NoiseProceduralTexture can't be created
  111853. * @param generateMipMaps defines if mipmaps must be generated (true by default)
  111854. */
  111855. function NoiseProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  111856. if (size === void 0) { size = 256; }
  111857. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  111858. var _this = _super.call(this, name, size, "noise", scene, fallbackTexture, generateMipMaps) || this;
  111859. _this._time = 0;
  111860. /** Gets or sets a value between 0 and 1 indicating the overall brightness of the texture (default is 0.2) */
  111861. _this.brightness = 0.2;
  111862. /** Defines the number of octaves to process */
  111863. _this.octaves = 3;
  111864. /** Defines the level of persistence (0.8 by default) */
  111865. _this.persistence = 0.8;
  111866. /** Gets or sets animation speed factor (default is 1) */
  111867. _this.animationSpeedFactor = 1;
  111868. _this._updateShaderUniforms();
  111869. return _this;
  111870. }
  111871. NoiseProceduralTexture.prototype._updateShaderUniforms = function () {
  111872. var scene = this.getScene();
  111873. if (!scene) {
  111874. return;
  111875. }
  111876. this._time += scene.getAnimationRatio() * this.animationSpeedFactor * 0.01;
  111877. this.setFloat("brightness", this.brightness);
  111878. this.setFloat("persistence", this.persistence);
  111879. this.setFloat("timeScale", this._time);
  111880. };
  111881. NoiseProceduralTexture.prototype._getDefines = function () {
  111882. return "#define OCTAVES " + (this.octaves | 0);
  111883. };
  111884. /** Generate the current state of the procedural texture */
  111885. NoiseProceduralTexture.prototype.render = function (useCameraPostProcess) {
  111886. this._updateShaderUniforms();
  111887. _super.prototype.render.call(this, useCameraPostProcess);
  111888. };
  111889. /**
  111890. * Serializes this noise procedural texture
  111891. * @returns a serialized noise procedural texture object
  111892. */
  111893. NoiseProceduralTexture.prototype.serialize = function () {
  111894. var serializationObject = {};
  111895. serializationObject.customType = "BABYLON.NoiseProceduralTexture";
  111896. serializationObject.brightness = this.brightness;
  111897. serializationObject.octaves = this.octaves;
  111898. serializationObject.persistence = this.persistence;
  111899. serializationObject.animationSpeedFactor = this.animationSpeedFactor;
  111900. serializationObject.size = this.getSize().width;
  111901. serializationObject.generateMipMaps = this._generateMipMaps;
  111902. return serializationObject;
  111903. };
  111904. /**
  111905. * Creates a NoiseProceduralTexture from parsed noise procedural texture data
  111906. * @param parsedTexture defines parsed texture data
  111907. * @param scene defines the current scene
  111908. * @param rootUrl defines the root URL containing noise procedural texture information
  111909. * @returns a parsed NoiseProceduralTexture
  111910. */
  111911. NoiseProceduralTexture.Parse = function (parsedTexture, scene, rootUrl) {
  111912. var texture = new NoiseProceduralTexture(parsedTexture.name, parsedTexture.size, scene, undefined, parsedTexture.generateMipMaps);
  111913. texture.brightness = parsedTexture.brightness;
  111914. texture.octaves = parsedTexture.octaves;
  111915. texture.persistence = parsedTexture.persistence;
  111916. texture.animationSpeedFactor = parsedTexture.animationSpeedFactor;
  111917. return texture;
  111918. };
  111919. return NoiseProceduralTexture;
  111920. }(BABYLON.ProceduralTexture));
  111921. BABYLON.NoiseProceduralTexture = NoiseProceduralTexture;
  111922. })(BABYLON || (BABYLON = {}));
  111923. //# sourceMappingURL=babylon.noiseProceduralTexture.js.map
  111924. var __assign = (this && this.__assign) || function () {
  111925. __assign = Object.assign || function(t) {
  111926. for (var s, i = 1, n = arguments.length; i < n; i++) {
  111927. s = arguments[i];
  111928. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  111929. t[p] = s[p];
  111930. }
  111931. return t;
  111932. };
  111933. return __assign.apply(this, arguments);
  111934. };
  111935. var BABYLON;
  111936. (function (BABYLON) {
  111937. /**
  111938. * This can helps recording videos from BabylonJS.
  111939. * This is based on the available WebRTC functionalities of the browser.
  111940. *
  111941. * @see http://doc.babylonjs.com/how_to/render_scene_on_a_video
  111942. */
  111943. var VideoRecorder = /** @class */ (function () {
  111944. /**
  111945. * Create a new VideoCapture object which can help converting what you see in Babylon to
  111946. * a video file.
  111947. * @param engine Defines the BabylonJS Engine you wish to record
  111948. * @param options Defines options that can be used to customized the capture
  111949. */
  111950. function VideoRecorder(engine, options) {
  111951. if (options === void 0) { options = null; }
  111952. if (!VideoRecorder.IsSupported(engine)) {
  111953. throw "Your browser does not support recording so far.";
  111954. }
  111955. var canvas = engine.getRenderingCanvas();
  111956. if (!canvas) {
  111957. throw "The babylon engine must have a canvas to be recorded";
  111958. }
  111959. this._canvas = canvas;
  111960. this._canvas.isRecording = false;
  111961. this._options = __assign({}, VideoRecorder._defaultOptions, options);
  111962. var stream = this._canvas.captureStream(this._options.fps);
  111963. this._mediaRecorder = new MediaRecorder(stream, { mimeType: this._options.mimeType });
  111964. this._mediaRecorder.ondataavailable = this._handleDataAvailable.bind(this);
  111965. this._mediaRecorder.onerror = this._handleError.bind(this);
  111966. this._mediaRecorder.onstop = this._handleStop.bind(this);
  111967. }
  111968. /**
  111969. * Returns wehther or not the VideoRecorder is available in your browser.
  111970. * @param engine Defines the Babylon Engine to check the support for
  111971. * @returns true if supported otherwise false
  111972. */
  111973. VideoRecorder.IsSupported = function (engine) {
  111974. var canvas = engine.getRenderingCanvas();
  111975. return (!!canvas && typeof canvas.captureStream === "function");
  111976. };
  111977. Object.defineProperty(VideoRecorder.prototype, "isRecording", {
  111978. /**
  111979. * True wether a recording is already in progress.
  111980. */
  111981. get: function () {
  111982. return !!this._canvas && this._canvas.isRecording;
  111983. },
  111984. enumerable: true,
  111985. configurable: true
  111986. });
  111987. /**
  111988. * Stops the current recording before the default capture timeout passed in the startRecording
  111989. * functions.
  111990. */
  111991. VideoRecorder.prototype.stopRecording = function () {
  111992. if (!this._canvas || !this._mediaRecorder) {
  111993. return;
  111994. }
  111995. if (!this.isRecording) {
  111996. return;
  111997. }
  111998. this._canvas.isRecording = false;
  111999. this._mediaRecorder.stop();
  112000. };
  112001. /**
  112002. * Starts recording the canvas for a max duration specified in parameters.
  112003. * @param fileName Defines the name of the file to be downloaded when the recording stop. If null no automatic download will start and you can rely on the promise to get the data back.
  112004. * @param maxDuration Defines the maximum recording time in seconds.
  112005. * It default to 7 seconds. A value of zero will not stop automatically, you would need to call stopRecording manually.
  112006. * @return a promise callback at the end of the recording with the video data in Blob.
  112007. */
  112008. VideoRecorder.prototype.startRecording = function (fileName, maxDuration) {
  112009. var _this = this;
  112010. if (fileName === void 0) { fileName = "babylonjs.webm"; }
  112011. if (maxDuration === void 0) { maxDuration = 7; }
  112012. if (!this._canvas || !this._mediaRecorder) {
  112013. throw "Recorder has already been disposed";
  112014. }
  112015. if (this.isRecording) {
  112016. throw "Recording already in progress";
  112017. }
  112018. if (maxDuration > 0) {
  112019. setTimeout(function () {
  112020. _this.stopRecording();
  112021. }, maxDuration * 1000);
  112022. }
  112023. this._fileName = fileName;
  112024. this._recordedChunks = [];
  112025. this._resolve = null;
  112026. this._reject = null;
  112027. this._canvas.isRecording = true;
  112028. this._mediaRecorder.start(this._options.recordChunckSize);
  112029. return new Promise(function (resolve, reject) {
  112030. _this._resolve = resolve;
  112031. _this._reject = reject;
  112032. });
  112033. };
  112034. /**
  112035. * Releases internal resources used during the recording.
  112036. */
  112037. VideoRecorder.prototype.dispose = function () {
  112038. this._canvas = null;
  112039. this._mediaRecorder = null;
  112040. this._recordedChunks = [];
  112041. this._fileName = null;
  112042. this._resolve = null;
  112043. this._reject = null;
  112044. };
  112045. VideoRecorder.prototype._handleDataAvailable = function (event) {
  112046. if (event.data.size > 0) {
  112047. this._recordedChunks.push(event.data);
  112048. }
  112049. };
  112050. VideoRecorder.prototype._handleError = function (event) {
  112051. this.stopRecording();
  112052. if (this._reject) {
  112053. this._reject(event.error);
  112054. }
  112055. else {
  112056. throw new event.error;
  112057. }
  112058. };
  112059. VideoRecorder.prototype._handleStop = function () {
  112060. this.stopRecording();
  112061. var superBuffer = new Blob(this._recordedChunks);
  112062. if (this._resolve) {
  112063. this._resolve(superBuffer);
  112064. }
  112065. window.URL.createObjectURL(superBuffer);
  112066. if (this._fileName) {
  112067. BABYLON.Tools.Download(superBuffer, this._fileName);
  112068. }
  112069. };
  112070. VideoRecorder._defaultOptions = {
  112071. mimeType: "video/webm",
  112072. fps: 25,
  112073. recordChunckSize: 3000
  112074. };
  112075. return VideoRecorder;
  112076. }());
  112077. BABYLON.VideoRecorder = VideoRecorder;
  112078. })(BABYLON || (BABYLON = {}));
  112079. //# sourceMappingURL=babylon.videoRecorder.js.map
  112080. var BABYLON;
  112081. (function (BABYLON) {
  112082. BABYLON.Scene.prototype.createDefaultLight = function (replace) {
  112083. if (replace === void 0) { replace = false; }
  112084. // Dispose existing light in replace mode.
  112085. if (replace) {
  112086. if (this.lights) {
  112087. for (var i = 0; i < this.lights.length; i++) {
  112088. this.lights[i].dispose();
  112089. }
  112090. }
  112091. }
  112092. // Light
  112093. if (this.lights.length === 0) {
  112094. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  112095. }
  112096. };
  112097. BABYLON.Scene.prototype.createDefaultCamera = function (createArcRotateCamera, replace, attachCameraControls) {
  112098. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  112099. if (replace === void 0) { replace = false; }
  112100. if (attachCameraControls === void 0) { attachCameraControls = false; }
  112101. // Dispose existing camera in replace mode.
  112102. if (replace) {
  112103. if (this.activeCamera) {
  112104. this.activeCamera.dispose();
  112105. this.activeCamera = null;
  112106. }
  112107. }
  112108. // Camera
  112109. if (!this.activeCamera) {
  112110. var worldExtends = this.getWorldExtends();
  112111. var worldSize = worldExtends.max.subtract(worldExtends.min);
  112112. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  112113. var camera;
  112114. var radius = worldSize.length() * 1.5;
  112115. // empty scene scenario!
  112116. if (!isFinite(radius)) {
  112117. radius = 1;
  112118. worldCenter.copyFromFloats(0, 0, 0);
  112119. }
  112120. if (createArcRotateCamera) {
  112121. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  112122. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  112123. arcRotateCamera.wheelPrecision = 100 / radius;
  112124. camera = arcRotateCamera;
  112125. }
  112126. else {
  112127. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  112128. freeCamera.setTarget(worldCenter);
  112129. camera = freeCamera;
  112130. }
  112131. camera.minZ = radius * 0.01;
  112132. camera.maxZ = radius * 1000;
  112133. camera.speed = radius * 0.2;
  112134. this.activeCamera = camera;
  112135. var canvas = this.getEngine().getRenderingCanvas();
  112136. if (attachCameraControls && canvas) {
  112137. camera.attachControl(canvas);
  112138. }
  112139. }
  112140. };
  112141. BABYLON.Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  112142. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  112143. if (replace === void 0) { replace = false; }
  112144. if (attachCameraControls === void 0) { attachCameraControls = false; }
  112145. this.createDefaultLight(replace);
  112146. this.createDefaultCamera(createArcRotateCamera, replace, attachCameraControls);
  112147. };
  112148. BABYLON.Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur, setGlobalEnvTexture) {
  112149. if (pbr === void 0) { pbr = false; }
  112150. if (scale === void 0) { scale = 1000; }
  112151. if (blur === void 0) { blur = 0; }
  112152. if (setGlobalEnvTexture === void 0) { setGlobalEnvTexture = true; }
  112153. if (!environmentTexture) {
  112154. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  112155. return null;
  112156. }
  112157. if (setGlobalEnvTexture) {
  112158. if (environmentTexture) {
  112159. this.environmentTexture = environmentTexture;
  112160. }
  112161. }
  112162. // Skybox
  112163. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  112164. if (pbr) {
  112165. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  112166. hdrSkyboxMaterial.backFaceCulling = false;
  112167. hdrSkyboxMaterial.reflectionTexture = environmentTexture.clone();
  112168. if (hdrSkyboxMaterial.reflectionTexture) {
  112169. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  112170. }
  112171. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  112172. hdrSkyboxMaterial.disableLighting = true;
  112173. hdrSkyboxMaterial.twoSidedLighting = true;
  112174. hdrSkybox.infiniteDistance = true;
  112175. hdrSkybox.material = hdrSkyboxMaterial;
  112176. }
  112177. else {
  112178. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  112179. skyboxMaterial.backFaceCulling = false;
  112180. skyboxMaterial.reflectionTexture = environmentTexture.clone();
  112181. if (skyboxMaterial.reflectionTexture) {
  112182. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  112183. }
  112184. skyboxMaterial.disableLighting = true;
  112185. hdrSkybox.infiniteDistance = true;
  112186. hdrSkybox.material = skyboxMaterial;
  112187. }
  112188. return hdrSkybox;
  112189. };
  112190. BABYLON.Scene.prototype.createDefaultEnvironment = function (options) {
  112191. if (BABYLON.EnvironmentHelper) {
  112192. return new BABYLON.EnvironmentHelper(options, this);
  112193. }
  112194. return null;
  112195. };
  112196. BABYLON.Scene.prototype.createDefaultVRExperience = function (webVROptions) {
  112197. if (webVROptions === void 0) { webVROptions = {}; }
  112198. return new BABYLON.VRExperienceHelper(this, webVROptions);
  112199. };
  112200. })(BABYLON || (BABYLON = {}));
  112201. //# sourceMappingURL=babylon.sceneHelpers.js.map
  112202. 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\n#ifdef REFLECTIONMAP_SKYBOX_TRANSFORMED\nvPositionUVW=(reflectionMatrix*vec4(position,1.0)).xyz;\n#else\nvPositionUVW=position;\n#endif\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\n#ifdef REFLECTIONMAP_SKYBOX_TRANSFORMED\nvPositionUVW=(reflectionMatrix*vec4(positionUpdated,1.0)).xyz;\n#else\nvPositionUVW=positionUpdated;\n#endif\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;\npointLightingInfo pointInfo;\nspotLightingInfo spotInfo;\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#ifdef AMBIENT\nvec3 ambientOcclusionForDirectDiffuse=mix(vec3(1.),ambientOcclusionColor,vAmbientInfos.w);\n#else\nvec3 ambientOcclusionForDirectDiffuse=ambientOcclusionColor;\n#endif\n\n\n\nvec4 finalColor=vec4(\nfinalDiffuse*ambientOcclusionForDirectDiffuse*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\n#ifdef BILLBOARDSTRETCHED\nattribute vec3 direction; \n#endif\n#ifdef RAMPGRADIENT\nattribute vec4 remapData;\n#endif\nattribute vec2 offset;\n\nuniform mat4 view;\nuniform mat4 projection;\nuniform vec2 translationPivot;\n#ifdef ANIMATESHEET \nuniform vec3 particlesInfos; \n#endif\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#ifdef RAMPGRADIENT\nvarying vec4 remapRanges;\n#endif\n#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4)\nuniform mat4 invView;\n#endif\n#include<clipPlaneVertexDeclaration>\n#ifdef BILLBOARD\nuniform vec3 eyePosition; \n#endif\nvec3 rotate(vec3 yaxis,vec3 rotatedCorner) {\nvec3 xaxis=normalize(cross(vec3(0.,1.0,0.),yaxis));\nvec3 zaxis=normalize(cross(yaxis,xaxis));\nvec3 row0=vec3(xaxis.x,xaxis.y,xaxis.z);\nvec3 row1=vec3(yaxis.x,yaxis.y,yaxis.z);\nvec3 row2=vec3(zaxis.x,zaxis.y,zaxis.z);\nmat3 rotMatrix=mat3(row0,row1,row2);\nvec3 alignedCorner=rotMatrix*rotatedCorner;\nreturn position+alignedCorner; \n}\n#ifdef BILLBOARDSTRETCHED\nvec3 rotateAlign(vec3 toCamera,vec3 rotatedCorner) {\nvec3 normalizedToCamera=normalize(toCamera);\nvec3 normalizedCrossDirToCamera=normalize(cross(normalize(direction),normalizedToCamera));\nvec3 crossProduct=normalize(cross(normalizedToCamera,normalizedCrossDirToCamera));\nvec3 row0=vec3(normalizedCrossDirToCamera.x,normalizedCrossDirToCamera.y,normalizedCrossDirToCamera.z);\nvec3 row1=vec3(crossProduct.x,crossProduct.y,crossProduct.z);\nvec3 row2=vec3(normalizedToCamera.x,normalizedToCamera.y,normalizedToCamera.z);\nmat3 rotMatrix=mat3(row0,row1,row2);\nvec3 alignedCorner=rotMatrix*rotatedCorner;\nreturn position+alignedCorner; \n}\n#endif\nvoid main(void) { \nvec2 cornerPos;\ncornerPos=(vec2(offset.x-0.5,offset.y-0.5)-translationPivot)*size+translationPivot;\n#ifdef BILLBOARD \n\nvec3 rotatedCorner;\n#ifdef BILLBOARDY \nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.y=0.;\nvec3 yaxis=position-eyePosition;\nyaxis.y=0.;\nvec3 worldPos=rotate(normalize(yaxis),rotatedCorner);\nvec3 viewPos=(view*vec4(worldPos,1.0)).xyz; \n#elif defined(BILLBOARDSTRETCHED)\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\nvec3 toCamera=position-eyePosition; \nvec3 worldPos=rotateAlign(toCamera,rotatedCorner);\nvec3 viewPos=(view*vec4(worldPos,1.0)).xyz; \n#else\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\nvec3 viewPos=(view*vec4(position,1.0)).xyz+rotatedCorner; \n#endif\n#ifdef RAMPGRADIENT\nremapRanges=remapData;\n#endif\n\ngl_Position=projection*vec4(viewPos,1.0); \n#else\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.y=0.;\nvec3 yaxis=normalize(direction);\nvec3 worldPos=rotate(yaxis,rotatedCorner);\ngl_Position=projection*view*vec4(worldPos,1.0); \n#endif \nvColor=color;\n#ifdef ANIMATESHEET\nfloat rowOffset=floor(cellIndex/particlesInfos.z);\nfloat columnOffset=cellIndex-rowOffset*particlesInfos.z;\nvec2 uvScale=particlesInfos.xy;\nvec2 uvOffset=vec2(offset.x ,1.0-offset.y);\nvUV=(uvOffset+vec2(columnOffset,rowOffset))*uvScale;\n#else\nvUV=offset;\n#endif\n\n#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4)\nvec4 worldPos=invView*vec4(viewPos,1.0);\n#endif\n#include<clipPlaneVertex>\n}","particlesPixelShader":"\nvarying vec2 vUV;\nvarying vec4 vColor;\nuniform vec4 textureMask;\nuniform sampler2D diffuseSampler;\n#include<clipPlaneFragmentDeclaration>\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\n#ifdef RAMPGRADIENT\nvarying vec4 remapRanges;\nuniform sampler2D rampSampler;\n#endif\nvoid main(void) {\n#include<clipPlaneFragment>\nvec4 textureColor=texture2D(diffuseSampler,vUV);\nvec4 baseColor=(textureColor*textureMask+(vec4(1.,1.,1.,1.)-textureMask))*vColor;\n#ifdef RAMPGRADIENT\nfloat alpha=baseColor.a;\nfloat remappedColorIndex=clamp((alpha-remapRanges.x)/remapRanges.y,0.0,1.0);\nvec4 rampColor=texture2D(rampSampler,vec2(1.0-remappedColorIndex,0.));\nbaseColor.rgb*=rampColor.rgb;\n\nfloat finalAlpha=baseColor.a;\nbaseColor.a=clamp((alpha*rampColor.a-remapRanges.z)/remapRanges.w,0.0,1.0);\n#endif\n#ifdef BLENDMULTIPLYMODE\nfloat sourceAlpha=vColor.a*textureColor.a;\nbaseColor.rgb=baseColor.rgb*sourceAlpha+vec3(1.0)*(1.0-sourceAlpha);\n#endif\n\n\n#ifdef IMAGEPROCESSINGPOSTPROCESS\nbaseColor.rgb=toLinearSpace(baseColor.rgb);\n#else\n#ifdef IMAGEPROCESSING\nbaseColor.rgb=toLinearSpace(baseColor.rgb);\nbaseColor=applyImageProcessing(baseColor);\n#endif\n#endif\ngl_FragColor=baseColor;\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}","gpuRenderParticlesVertexShader":"#version 300 es\nuniform mat4 view;\nuniform mat4 projection;\nuniform vec2 translationPivot;\n\nin vec3 position;\nin float age;\nin float life;\nin vec3 size;\n#ifndef BILLBOARD\nin vec3 initialDirection;\n#endif\n#ifdef BILLBOARDSTRETCHED\nin vec3 direction;\n#endif\nin float angle;\n#ifdef ANIMATESHEET\nin float cellIndex;\n#endif\nin vec2 offset;\nin vec2 uv;\nout vec2 vUV;\nout vec4 vColor;\n#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4)\nuniform mat4 invView;\n#endif\n#include<clipPlaneVertexDeclaration2>\n#ifdef COLORGRADIENTS\nuniform sampler2D colorGradientSampler;\n#else\nuniform vec4 colorDead;\nin vec4 color;\n#endif\n#ifdef ANIMATESHEET\nuniform vec3 sheetInfos;\n#endif\n#ifdef BILLBOARD\nuniform vec3 eyePosition; \n#endif\nvec3 rotate(vec3 yaxis,vec3 rotatedCorner) {\nvec3 xaxis=normalize(cross(vec3(0.,1.0,0.),yaxis));\nvec3 zaxis=normalize(cross(yaxis,xaxis));\nvec3 row0=vec3(xaxis.x,xaxis.y,xaxis.z);\nvec3 row1=vec3(yaxis.x,yaxis.y,yaxis.z);\nvec3 row2=vec3(zaxis.x,zaxis.y,zaxis.z);\nmat3 rotMatrix=mat3(row0,row1,row2);\nvec3 alignedCorner=rotMatrix*rotatedCorner;\nreturn position+alignedCorner;\n}\n#ifdef BILLBOARDSTRETCHED\nvec3 rotateAlign(vec3 toCamera,vec3 rotatedCorner) {\nvec3 normalizedToCamera=normalize(toCamera);\nvec3 normalizedCrossDirToCamera=normalize(cross(normalize(direction),normalizedToCamera));\nvec3 crossProduct=normalize(cross(normalizedToCamera,normalizedCrossDirToCamera));\nvec3 row0=vec3(normalizedCrossDirToCamera.x,normalizedCrossDirToCamera.y,normalizedCrossDirToCamera.z);\nvec3 row1=vec3(crossProduct.x,crossProduct.y,crossProduct.z);\nvec3 row2=vec3(normalizedToCamera.x,normalizedToCamera.y,normalizedToCamera.z);\nmat3 rotMatrix=mat3(row0,row1,row2);\nvec3 alignedCorner=rotMatrix*rotatedCorner;\nreturn position+alignedCorner; \n}\n#endif\nvoid main() {\n#ifdef ANIMATESHEET\nfloat rowOffset=floor(cellIndex/sheetInfos.z);\nfloat columnOffset=cellIndex-rowOffset*sheetInfos.z;\nvec2 uvScale=sheetInfos.xy;\nvec2 uvOffset=vec2(uv.x ,1.0-uv.y);\nvUV=(uvOffset+vec2(columnOffset,rowOffset))*uvScale;\n#else \nvUV=uv;\n#endif\nfloat ratio=age/life;\n#ifdef COLORGRADIENTS\nvColor=texture(colorGradientSampler,vec2(ratio,0));\n#else\nvColor=color*vec4(1.0-ratio)+colorDead*vec4(ratio);\n#endif\nvec2 cornerPos=(offset-translationPivot)*size.yz*size.x+translationPivot;\n#ifdef BILLBOARD\nvec4 rotatedCorner;\nrotatedCorner.w=0.;\n#ifdef BILLBOARDY \nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.y=0.;\nvec3 yaxis=position-eyePosition;\nyaxis.y=0.;\nvec3 worldPos=rotate(normalize(yaxis),rotatedCorner.xyz);\nvec4 viewPosition=(view*vec4(worldPos,1.0)); \n#elif defined(BILLBOARDSTRETCHED)\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\nvec3 toCamera=position-eyePosition; \nvec3 worldPos=rotateAlign(toCamera,rotatedCorner.xyz);\nvec4 viewPosition=(view*vec4(worldPos,1.0)); \n#else\n\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nvec4 viewPosition=view*vec4(position,1.0)+rotatedCorner;\n#endif\n#else\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=0.;\nrotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nvec3 yaxis=normalize(initialDirection);\nvec3 worldPos=rotate(yaxis,rotatedCorner);\n\nvec4 viewPosition=view*vec4(worldPos,1.0); \n#endif\ngl_Position=projection*viewPosition;\n\n#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4)\nvec4 worldPos=invView*viewPosition;\n#endif \n#include<clipPlaneVertex>\n}","gpuRenderParticlesPixelShader":"#version 300 es\nuniform sampler2D textureSampler;\nin vec2 vUV;\nin vec4 vColor;\nout vec4 outFragColor;\n#include<clipPlaneFragmentDeclaration2> \n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\nvoid main() {\n#include<clipPlaneFragment> \nvec4 textureColor=texture(textureSampler,vUV);\noutFragColor=textureColor*vColor;\n#ifdef BLENDMULTIPLYMODE\nfloat alpha=vColor.a*textureColor.a;\noutFragColor.rgb=outFragColor.rgb*alpha+vec3(1.0)*(1.0-alpha); \n#endif \n\n\n#ifdef IMAGEPROCESSINGPOSTPROCESS\noutFragColor.rgb=toLinearSpace(outFragColor.rgb);\n#else\n#ifdef IMAGEPROCESSING\noutFragColor.rgb=toLinearSpace(outFragColor.rgb);\noutFragColor=applyImageProcessing(outFragColor);\n#endif\n#endif\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 POINTEMITTER\nuniform vec3 direction1;\nuniform vec3 direction2;\n#endif\n#ifdef HEMISPHERICEMITTER\nuniform float radius;\nuniform float radiusRange;\nuniform float directionRandomizer;\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 CYLINDEREMITTER\nuniform float radius;\nuniform float height;\nuniform float radiusRange;\n#ifdef DIRECTEDCYLINDEREMITTER\nuniform vec3 direction1;\nuniform vec3 direction2;\n#else\nuniform float directionRandomizer;\n#endif\n#endif\n#ifdef CONEEMITTER\nuniform vec2 radius;\nuniform float coneAngle;\nuniform vec2 height;\nuniform float directionRandomizer;\n#endif\n\nin vec3 position;\nin float age;\nin float life;\nin vec4 seed;\nin vec3 size;\n#ifndef COLORGRADIENTS\nin vec4 color;\n#endif\nin vec3 direction;\n#ifndef BILLBOARD\nin vec3 initialDirection;\n#endif\n#ifdef ANGULARSPEEDGRADIENTS\nin float angle;\n#else\nin vec2 angle;\n#endif\n#ifdef ANIMATESHEET\nin float cellIndex;\n#ifdef ANIMATESHEETRANDOMSTART\nin float cellStartOffset;\n#endif\n#endif\n#ifdef NOISE\nin vec3 noiseCoordinates1;\nin vec3 noiseCoordinates2;\n#endif\n\nout vec3 outPosition;\nout float outAge;\nout float outLife;\nout vec4 outSeed;\nout vec3 outSize;\n#ifndef COLORGRADIENTS\nout vec4 outColor;\n#endif\nout vec3 outDirection;\n#ifndef BILLBOARD\nout vec3 outInitialDirection;\n#endif\n#ifdef ANGULARSPEEDGRADIENTS\nout float outAngle;\n#else\nout vec2 outAngle;\n#endif\n#ifdef ANIMATESHEET\nout float outCellIndex;\n#ifdef ANIMATESHEETRANDOMSTART\nout float outCellStartOffset;\n#endif\n#endif\n#ifdef NOISE\nout vec3 outNoiseCoordinates1;\nout vec3 outNoiseCoordinates2;\n#endif\n#ifdef SIZEGRADIENTS\nuniform sampler2D sizeGradientSampler;\n#endif \n#ifdef ANGULARSPEEDGRADIENTS\nuniform sampler2D angularSpeedGradientSampler;\n#endif \n#ifdef VELOCITYGRADIENTS\nuniform sampler2D velocityGradientSampler;\n#endif\n#ifdef LIMITVELOCITYGRADIENTS\nuniform sampler2D limitVelocityGradientSampler;\nuniform float limitVelocityDamping;\n#endif\n#ifdef DRAGGRADIENTS\nuniform sampler2D dragGradientSampler;\n#endif\n#ifdef NOISE\nuniform vec3 noiseStrength;\nuniform sampler2D noiseSampler;\n#endif\n#ifdef ANIMATESHEET\nuniform vec3 cellInfos;\n#endif\nvec3 getRandomVec3(float offset) {\nreturn texture(randomSampler2,vec2(float(gl_VertexID)*offset/currentCount,0)).rgb;\n}\nvec4 getRandomVec4(float offset) {\nreturn texture(randomSampler,vec2(float(gl_VertexID)*offset/currentCount,0));\n}\nvoid main() {\nfloat newAge=age+timeDelta; \n\nif (newAge>=life && stopFactor != 0.) {\nvec3 position;\nvec3 direction;\n\nvec4 randoms=getRandomVec4(seed.x);\n\noutLife=lifeTime.x+(lifeTime.y-lifeTime.x)*randoms.r;\noutAge=mod(newAge,outLife);\n\noutSeed=seed;\n\n#ifdef SIZEGRADIENTS \noutSize.x=texture(sizeGradientSampler,vec2(0,0)).r;\n#else\noutSize.x=sizeRange.x+(sizeRange.y-sizeRange.x)*randoms.g;\n#endif\noutSize.y=scaleRange.x+(scaleRange.y-scaleRange.x)*randoms.b;\noutSize.z=scaleRange.z+(scaleRange.w-scaleRange.z)*randoms.a; \n#ifndef COLORGRADIENTS\n\noutColor=color1+(color2-color1)*randoms.b;\n#endif\n\n#ifndef ANGULARSPEEDGRADIENTS \noutAngle.y=angleRange.x+(angleRange.y-angleRange.x)*randoms.a;\noutAngle.x=angleRange.z+(angleRange.w-angleRange.z)*randoms.r;\n#else\noutAngle=angleRange.z+(angleRange.w-angleRange.z)*randoms.r;\n#endif \n\n#ifdef POINTEMITTER\nvec3 randoms2=getRandomVec3(seed.y);\nvec3 randoms3=getRandomVec3(seed.z);\nposition=vec3(0,0,0);\ndirection=direction1+(direction2-direction1)*randoms3;\n#elif defined(BOXEMITTER)\nvec3 randoms2=getRandomVec3(seed.y);\nvec3 randoms3=getRandomVec3(seed.z);\nposition=minEmitBox+(maxEmitBox-minEmitBox)*randoms2;\ndirection=direction1+(direction2-direction1)*randoms3; \n#elif defined(HEMISPHERICEMITTER)\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,abs(randY),randZ);\ndirection=position+directionRandomizer*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(CYLINDEREMITTER)\nvec3 randoms2=getRandomVec3(seed.y);\nvec3 randoms3=getRandomVec3(seed.z);\n\nfloat yPos=(randoms2.x-0.5)*height;\nfloat angle=randoms2.y*PI*2.;\nfloat inverseRadiusRangeSquared=((1.-radiusRange)*(1.-radiusRange));\nfloat positionRadius=radius*sqrt(inverseRadiusRangeSquared+(randoms2.z*(1.-inverseRadiusRangeSquared)));\nfloat xPos=positionRadius*cos(angle);\nfloat zPos=positionRadius*sin(angle);\nposition=vec3(xPos,yPos,zPos);\n#ifdef DIRECTEDCYLINDEREMITTER\ndirection=direction1+(direction2-direction1)*randoms3;\n#else\n\nangle=angle+((randoms3.x-0.5)*PI);\ndirection=vec3(cos(angle),randoms3.y-0.5,sin(angle));\ndirection=normalize(direction);\n#endif\n#elif defined(CONEEMITTER)\nvec3 randoms2=getRandomVec3(seed.y);\nfloat s=2.0*PI*randoms2.x;\n#ifdef CONEEMITTERSPAWNPOINT\nfloat h=0.00001;\n#else\nfloat h=randoms2.y*height.y;\n\nh=1.-h*h; \n#endif\nfloat lRadius=radius.x-radius.x*randoms2.z*radius.y;\nlRadius=lRadius*h;\nfloat randX=lRadius*sin(s);\nfloat randZ=lRadius*cos(s);\nfloat randY=h*height.x;\nposition=vec3(randX,randY,randZ); \n\nif (abs(cos(coneAngle)) == 1.0) {\ndirection=vec3(0.,1.0,0.);\n} else {\nvec3 randoms3=getRandomVec3(seed.z);\ndirection=position+directionRandomizer*randoms3;\n}\n#else \n\nposition=vec3(0.,0.,0.);\n\ndirection=2.0*(getRandomVec3(seed.w)-vec3(0.5,0.5,0.5));\n#endif\nfloat power=emitPower.x+(emitPower.y-emitPower.x)*randoms.a;\noutPosition=(emitterWM*vec4(position,1.)).xyz;\nvec3 initial=(emitterWM*vec4(normalize(direction),0.)).xyz;\noutDirection=initial*power;\n#ifndef BILLBOARD \noutInitialDirection=initial;\n#endif\n#ifdef ANIMATESHEET \noutCellIndex=cellInfos.x;\n#ifdef ANIMATESHEETRANDOMSTART\noutCellStartOffset=randoms.a*outLife;\n#endif \n#endif\n#ifdef NOISE\noutNoiseCoordinates1=noiseCoordinates1;\noutNoiseCoordinates2=noiseCoordinates2;\n#endif\n} else {\nfloat directionScale=timeDelta;\noutAge=newAge;\nfloat ageGradient=newAge/life;\n#ifdef VELOCITYGRADIENTS\ndirectionScale*=texture(velocityGradientSampler,vec2(ageGradient,0)).r;\n#endif\n#ifdef DRAGGRADIENTS\ndirectionScale*=1.0-texture(dragGradientSampler,vec2(ageGradient,0)).r;\n#endif\noutPosition=position+direction*directionScale;\noutLife=life;\noutSeed=seed;\n#ifndef COLORGRADIENTS \noutColor=color;\n#endif\n#ifdef SIZEGRADIENTS\noutSize.x=texture(sizeGradientSampler,vec2(ageGradient,0)).r;\noutSize.yz=size.yz;\n#else\noutSize=size;\n#endif \n#ifndef BILLBOARD \noutInitialDirection=initialDirection;\n#endif\nvec3 updatedDirection=direction+gravity*timeDelta;\n#ifdef LIMITVELOCITYGRADIENTS\nfloat limitVelocity=texture(limitVelocityGradientSampler,vec2(ageGradient,0)).r;\nfloat currentVelocity=length(updatedDirection);\nif (currentVelocity>limitVelocity) {\nupdatedDirection=updatedDirection*limitVelocityDamping;\n}\n#endif\noutDirection=updatedDirection;\n#ifdef NOISE\nvec3 localPosition=outPosition-emitterWM[3].xyz;\nfloat fetchedR=texture(noiseSampler,vec2(noiseCoordinates1.x,noiseCoordinates1.y)*vec2(0.5)+vec2(0.5)).r;\nfloat fetchedG=texture(noiseSampler,vec2(noiseCoordinates1.z,noiseCoordinates2.x)*vec2(0.5)+vec2(0.5)).r;\nfloat fetchedB=texture(noiseSampler,vec2(noiseCoordinates2.y,noiseCoordinates2.z)*vec2(0.5)+vec2(0.5)).r;\nvec3 force=vec3(2.*fetchedR-1.,2.*fetchedG-1.,2.*fetchedB-1.)*noiseStrength;\noutDirection=outDirection+force*timeDelta;\noutNoiseCoordinates1=noiseCoordinates1;\noutNoiseCoordinates2=noiseCoordinates2;\n#endif \n#ifdef ANGULARSPEEDGRADIENTS\nfloat angularSpeed=texture(angularSpeedGradientSampler,vec2(ageGradient,0)).r;\noutAngle=angle+angularSpeed*timeDelta;\n#else\noutAngle=vec2(angle.x+angle.y*timeDelta,angle.y);\n#endif\n#ifdef ANIMATESHEET \nfloat offsetAge=outAge;\nfloat dist=cellInfos.y-cellInfos.x;\n#ifdef ANIMATESHEETRANDOMSTART\noutCellStartOffset=cellStartOffset;\noffsetAge+=cellStartOffset;\n#endif \nfloat ratio=clamp(mod(offsetAge*cellInfos.z,life)/life,0.,1.0);\noutCellIndex=float(int(cellInfos.x+ratio*dist));\n#endif\n}\n}","gpuUpdateParticlesPixelShader":"#version 300 es\nvoid main() {\ndiscard;\n}\n","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}","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}","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;\nfloat scales[16]=float[16](\n0.1,\n0.11406250000000001,\n0.131640625,\n0.15625,\n0.187890625,\n0.2265625,\n0.272265625,\n0.325,\n0.384765625,\n0.4515625,\n0.525390625,\n0.60625,\n0.694140625,\n0.7890625,\n0.891015625,\n1.0\n);\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;\n\nfloat dotProduct=dot(rvec,normal);\nrvec=1.0-abs(dotProduct)>1e-2 ? rvec : vec3(-rvec.y,0.0,rvec.x);\nvec3 tangent=normalize(rvec-normal*dot(rvec,normal));\nvec3 bitangent=cross(normal,tangent);\nmat3 tbn=mat3(tangent,bitangent,normal);\nfloat difference;\nfor (int i=0; i<SAMPLES; ++i) {\n\nvec3 samplePosition=scales[(i+int(random.x*16.0)) % 16]*tbn*sampleSphere[(i+int(random.y*16.0)) % 16];\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\ndifference=depthSign*samplePosition.z-sampleDepth;\nfloat rangeCheck=1.0-smoothstep(correctedRadius*0.5,correctedRadius,difference);\nocclusion+=(difference>=0.0 ? 1.0 : 0.0)*rangeCheck;\n}\nocclusion=occlusion*(1.0-smoothstep(maxZ*0.75,maxZ,depth));\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}","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\n#ifdef REFLECTIONMAP_SKYBOX_TRANSFORMED\nvPositionUVW=(reflectionMatrix*vec4(position,1.0)).xyz;\n#else\nvPositionUVW=position;\n#endif\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","noisePixelShader":"\n\nuniform float brightness;\nuniform float persistence;\nuniform float timeScale;\n\nvarying vec2 vUV;\n\nvec2 hash22(vec2 p)\n{\np=p*mat2(127.1,311.7,269.5,183.3);\np=-1.0+2.0*fract(sin(p)*43758.5453123);\nreturn sin(p*6.283+timeScale);\n}\nfloat interpolationNoise(vec2 p)\n{\nvec2 pi=floor(p);\nvec2 pf=p-pi;\nvec2 w=pf*pf*(3.-2.*pf);\nfloat f00=dot(hash22(pi+vec2(.0,.0)),pf-vec2(.0,.0));\nfloat f01=dot(hash22(pi+vec2(.0,1.)),pf-vec2(.0,1.));\nfloat f10=dot(hash22(pi+vec2(1.0,0.)),pf-vec2(1.0,0.));\nfloat f11=dot(hash22(pi+vec2(1.0,1.)),pf-vec2(1.0,1.));\nfloat xm1=mix(f00,f10,w.x);\nfloat xm2=mix(f01,f11,w.x);\nfloat ym=mix(xm1,xm2,w.y); \nreturn ym;\n}\nfloat perlinNoise2D(float x,float y)\n{\nfloat sum=0.0;\nfloat frequency=0.0;\nfloat amplitude=0.0;\nfor(int i=0; i<OCTAVES; i++)\n{\nfrequency=pow(2.0,float(i));\namplitude=pow(persistence,float(i));\nsum=sum+interpolationNoise(vec2(x*frequency,y*frequency))*amplitude;\n}\nreturn sum;\n}\n\nvoid main(void)\n{\nfloat x=abs(vUV.x);\nfloat y=abs(vUV.y);\nfloat noise=brightness+(1.0-brightness)*perlinNoise2D(x,y);\ngl_FragColor=vec4(noise,noise,noise,1.0);\n}\n"};
  112203. 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\n#ifdef CLIPPLANE2\nuniform vec4 vClipPlane2;\nvarying float fClipDistance2;\n#endif\n#ifdef CLIPPLANE3\nuniform vec4 vClipPlane3;\nvarying float fClipDistance3;\n#endif\n#ifdef CLIPPLANE4\nuniform vec4 vClipPlane4;\nvarying float fClipDistance4;\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\n#ifdef CLIPPLANE2\nfClipDistance2=dot(worldPos,vClipPlane2);\n#endif\n#ifdef CLIPPLANE3\nfClipDistance3=dot(worldPos,vClipPlane3);\n#endif\n#ifdef CLIPPLANE4\nfClipDistance4=dot(worldPos,vClipPlane4);\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};\nuniform vec4 vLightFalloff{X};\n#elif defined(POINTLIGHT{X})\nuniform vec4 vLightFalloff{X};\n#elif defined(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;\nvec4 vLightFalloff;\n#elif defined(POINTLIGHT{X})\nvec4 vLightFalloff;\n#elif defined(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 REFLECTION\nuniform mat4 reflectionMatrix;\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\n#ifdef TONEMAPPING_ACES\n\n\n\n\n\nconst mat3 ACESInputMat=mat3(\nvec3(0.59719,0.07600,0.02840),\nvec3(0.35458,0.90834,0.13383),\nvec3(0.04823,0.01566,0.83777)\n);\n\nconst mat3 ACESOutputMat=mat3(\nvec3( 1.60475,-0.10208,-0.00327),\nvec3(-0.53108,1.10813,-0.07276),\nvec3(-0.07367,-0.00605,1.07602)\n);\nvec3 RRTAndODTFit(vec3 v)\n{\nvec3 a=v*(v+0.0245786)-0.000090537;\nvec3 b=v*(0.983729*v+0.4329510)+0.238081;\nreturn a/b;\n}\nvec3 ACESFitted(vec3 color)\n{\ncolor=ACESInputMat*color;\n\ncolor=RRTAndODTFit(color);\ncolor=ACESOutputMat*color;\n\ncolor=clamp(color,0.0,1.0);\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\n#ifdef TONEMAPPING_ACES\nresult.rgb=ACESFitted(result.rgb);\n#else\nconst float tonemappingCalibration=1.590579;\nresult.rgb=1.0-exp2(-tonemappingCalibration*result.rgb);\n#endif\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\n#ifdef CLIPPLANE2\nvarying float fClipDistance2;\n#endif\n#ifdef CLIPPLANE3\nvarying float fClipDistance3;\n#endif\n#ifdef CLIPPLANE4\nvarying float fClipDistance4;\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\n#ifdef CLIPPLANE2\nif (fClipDistance2>0.0)\n{\ndiscard;\n}\n#endif\n#ifdef CLIPPLANE3\nif (fClipDistance3>0.0)\n{\ndiscard;\n}\n#endif\n#ifdef CLIPPLANE4\nif (fClipDistance4>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}\nspotInfo=computeSpotLightingInfo(light{X}.vLightData);\n#ifdef LIGHT_FALLOFF_GLTF{X}\nspotInfo.attenuation=computeDistanceLightFalloff_GLTF(spotInfo.lightDistanceSquared,light{X}.vLightFalloff.y);\nspotInfo.attenuation*=computeDirectionalLightFalloff_GLTF(light{X}.vLightDirection.xyz,spotInfo.directionToLightCenterW,light{X}.vLightFalloff.z,light{X}.vLightFalloff.w);\n#elif defined(LIGHT_FALLOFF_PHYSICAL{X})\nspotInfo.attenuation=computeDistanceLightFalloff_Physical(spotInfo.lightDistanceSquared);\nspotInfo.attenuation*=computeDirectionalLightFalloff_Physical(light{X}.vLightDirection.xyz,spotInfo.directionToLightCenterW,light{X}.vLightDirection.w);\n#elif defined(LIGHT_FALLOFF_STANDARD{X})\nspotInfo.attenuation=computeDistanceLightFalloff_Standard(spotInfo.lightOffset,light{X}.vLightFalloff.x);\nspotInfo.attenuation*=computeDirectionalLightFalloff_Standard(light{X}.vLightDirection.xyz,spotInfo.directionToLightCenterW,light{X}.vLightDirection.w,light{X}.vLightData.w);\n#else\nspotInfo.attenuation=computeDistanceLightFalloff(spotInfo.lightOffset,spotInfo.lightDistanceSquared,light{X}.vLightFalloff.x,light{X}.vLightFalloff.y);\nspotInfo.attenuation*=computeDirectionalLightFalloff(light{X}.vLightDirection.xyz,spotInfo.directionToLightCenterW,light{X}.vLightDirection.w,light{X}.vLightData.w,light{X}.vLightFalloff.z,light{X}.vLightFalloff.w);\n#endif\ninfo=computeSpotLighting(spotInfo,viewDirectionW,normalW,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,geometricRoughnessFactor,NdotL);\n#elif defined(POINTLIGHT{X})\npointInfo=computePointLightingInfo(light{X}.vLightData);\n#ifdef LIGHT_FALLOFF_GLTF{X}\npointInfo.attenuation=computeDistanceLightFalloff_GLTF(pointInfo.lightDistanceSquared,light{X}.vLightFalloff.y);\n#elif defined(LIGHT_FALLOFF_PHYSICAL{X})\npointInfo.attenuation=computeDistanceLightFalloff_Physical(pointInfo.lightDistanceSquared);\n#elif defined(LIGHT_FALLOFF_STANDARD{X})\npointInfo.attenuation=computeDistanceLightFalloff_Standard(pointInfo.lightOffset,light{X}.vLightFalloff.x);\n#else\npointInfo.attenuation=computeDistanceLightFalloff(pointInfo.lightOffset,pointInfo.lightDistanceSquared,light{X}.vLightFalloff.x,light{X}.vLightFalloff.y);\n#endif\ninfo=computePointLighting(pointInfo,viewDirectionW,normalW,light{X}.vLightDiffuse.rgb,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,geometricRoughnessFactor,NdotL);\n#elif defined(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#elif defined(DIRLIGHT{X})\ninfo=computeDirectionalLighting(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#elif defined(HEMILIGHT{X})\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,glossiness);\n#elif 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 vec4 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 vec4 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 vec4 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#if defined(USEPHYSICALLIGHTFALLOFF) || defined(USEGLTFLIGHTFALLOFF)\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};\nstruct pointLightingInfo\n{\nvec3 lightOffset;\nfloat lightDistanceSquared;\nfloat attenuation;\n};\nstruct spotLightingInfo\n{\nvec3 lightOffset;\nfloat lightDistanceSquared;\nvec3 directionToLightCenterW;\nfloat attenuation;\n};\nfloat computeDistanceLightFalloff_Standard(vec3 lightOffset,float range)\n{\nreturn max(0.,1.0-length(lightOffset)/range);\n}\nfloat computeDistanceLightFalloff_Physical(float lightDistanceSquared)\n{\nreturn 1.0/((lightDistanceSquared+0.001));\n}\nfloat computeDistanceLightFalloff_GLTF(float lightDistanceSquared,float inverseSquaredRange)\n{\nconst float minDistanceSquared=0.01*0.01;\nfloat lightDistanceFalloff=1.0/(max(lightDistanceSquared,minDistanceSquared));\nfloat factor=lightDistanceSquared*inverseSquaredRange;\nfloat attenuation=clamp(1.0-factor*factor,0.,1.);\nattenuation*=attenuation;\n\nlightDistanceFalloff*=attenuation;\nreturn lightDistanceFalloff;\n}\nfloat computeDistanceLightFalloff(vec3 lightOffset,float lightDistanceSquared,float range,float inverseSquaredRange)\n{ \n#ifdef USEPHYSICALLIGHTFALLOFF\nreturn computeDistanceLightFalloff_Physical(lightDistanceSquared);\n#elif defined(USEGLTFLIGHTFALLOFF)\nreturn computeDistanceLightFalloff_GLTF(lightDistanceSquared,inverseSquaredRange);\n#else\nreturn computeDistanceLightFalloff_Standard(lightOffset,range);\n#endif\n}\nfloat computeDirectionalLightFalloff_Standard(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle,float exponent)\n{\nfloat falloff=0.0;\nfloat cosAngle=max(0.000000000000001,dot(-lightDirection,directionToLightCenterW));\nif (cosAngle>=cosHalfAngle)\n{\nfalloff=max(0.,pow(cosAngle,exponent));\n}\nreturn falloff;\n}\nfloat computeDirectionalLightFalloff_Physical(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle)\n{\nconst float kMinusLog2ConeAngleIntensityRatio=6.64385618977; \n\n\n\n\n\nfloat concentrationKappa=kMinusLog2ConeAngleIntensityRatio/(1.0-cosHalfAngle);\n\n\nvec4 lightDirectionSpreadSG=vec4(-lightDirection*concentrationKappa,-concentrationKappa);\nfloat falloff=exp2(dot(vec4(directionToLightCenterW,1.0),lightDirectionSpreadSG));\nreturn falloff;\n}\nfloat computeDirectionalLightFalloff_GLTF(vec3 lightDirection,vec3 directionToLightCenterW,float lightAngleScale,float lightAngleOffset)\n{\n\n\n\nfloat cd=dot(-lightDirection,directionToLightCenterW);\nfloat falloff=clamp(cd*lightAngleScale+lightAngleOffset,0.,1.);\n\nfalloff*=falloff;\nreturn falloff;\n}\nfloat computeDirectionalLightFalloff(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle,float exponent,float lightAngleScale,float lightAngleOffset)\n{\n#ifdef USEPHYSICALLIGHTFALLOFF\nreturn computeDirectionalLightFalloff_Physical(lightDirection,directionToLightCenterW,cosHalfAngle);\n#elif defined(USEGLTFLIGHTFALLOFF)\nreturn computeDirectionalLightFalloff_GLTF(lightDirection,directionToLightCenterW,lightAngleScale,lightAngleOffset);\n#else\nreturn computeDirectionalLightFalloff_Standard(lightDirection,directionToLightCenterW,cosHalfAngle,exponent);\n#endif\n}\npointLightingInfo computePointLightingInfo(vec4 lightData) {\npointLightingInfo result;\nresult.lightOffset=lightData.xyz-vPositionW;\nresult.lightDistanceSquared=dot(result.lightOffset,result.lightOffset);\nreturn result;\n}\nspotLightingInfo computeSpotLightingInfo(vec4 lightData) {\nspotLightingInfo result;\nresult.lightOffset=lightData.xyz-vPositionW;\nresult.directionToLightCenterW=normalize(result.lightOffset);\nresult.lightDistanceSquared=dot(result.lightOffset,result.lightOffset);\nreturn result;\n}\nlightingInfo computePointLighting(pointLightingInfo info,vec3 viewDirectionW,vec3 vNormal,vec3 diffuseColor,float lightRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,out float NdotL) {\nlightingInfo result;\nfloat lightDistance=sqrt(info.lightDistanceSquared);\nvec3 lightDirection=normalize(info.lightOffset);\n\nroughness=adjustRoughnessFromLightProperties(roughness,lightRadius,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*info.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*info.attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(spotLightingInfo info,vec3 viewDirectionW,vec3 vNormal,vec4 lightDirection,vec3 diffuseColor,float lightRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,out float NdotL) {\nlightingInfo result;\n\nfloat lightDistance=sqrt(info.lightDistanceSquared);\nroughness=adjustRoughnessFromLightProperties(roughness,lightRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+info.directionToLightCenterW);\nNdotL=clamp(dot(vNormal,info.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*info.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*info.attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeDirectionalLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float lightRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,out float NdotL) {\nlightingInfo result;\nfloat lightDistance=length(-lightData.xyz);\nvec3 lightDirection=normalize(-lightData.xyz);\n\nroughness=adjustRoughnessFromLightProperties(roughness,lightRadius,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;\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;\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}","clipPlaneVertexDeclaration2":"#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nout float fClipDistance;\n#endif\n#ifdef CLIPPLANE2\nuniform vec4 vClipPlane2;\nout float fClipDistance2;\n#endif\n#ifdef CLIPPLANE3\nuniform vec4 vClipPlane3;\nout float fClipDistance3;\n#endif\n#ifdef CLIPPLANE4\nuniform vec4 vClipPlane4;\nout float fClipDistance4;\n#endif","clipPlaneFragmentDeclaration2":"#ifdef CLIPPLANE\nin float fClipDistance;\n#endif\n#ifdef CLIPPLANE2\nin float fClipDistance2;\n#endif\n#ifdef CLIPPLANE3\nin float fClipDistance3;\n#endif\n#ifdef CLIPPLANE4\nin float fClipDistance4;\n#endif","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","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};","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};"};